content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace CreatingAHoldingPage { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); } } }
21.666667
64
0.588462
[ "MIT" ]
AnzhelikaKravchuk/asp-dot-net-core-in-action
chapter03/1.0/CreatingAHoldingPage/CreatingAHoldingPage/Program.cs
522
C#
// <copyright file="IFindsByTagName.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace OpenQA.Selenium.Internal { /// <summary> /// Defines the interface through which the user finds elements by their tag name. /// </summary> public interface IFindsByTagName { /// <summary> /// Finds the first element matching the specified tag name. /// </summary> /// <param name="tagName">The tag name to match.</param> /// <returns>The first <see cref="IWebElement"/> matching the criteria.</returns> IWebElement FindElementByTagName(string tagName); /// <summary> /// Finds all elements matching the specified tag name. /// </summary> /// <param name="tagName">The tag name to match.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> containing all /// <see cref="IWebElement">IWebElements</see> matching the criteria.</returns> ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName); } }
41.446809
89
0.702259
[ "Apache-2.0" ]
BlackSmith/selenium
dotnet/src/webdriver/Internal/IFindsByTagName.cs
1,948
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02. Maximal Sum")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. Maximal Sum")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("46f1cbba-a510-4a19-9d8a-b0b8bd4e2f2d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.918919
84
0.741981
[ "MIT" ]
matir8/TelerikAcademy-2016-2017
Homework/C# Advanced/02. Multidimensional-Arrays/02. Maximal Sum/Properties/AssemblyInfo.cs
1,406
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Management.Automation.Configuration; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Management.Automation.Host { /// <summary> /// Defines the properties and facilities providing by an hosting application deriving from /// <see cref="System.Management.Automation.Host.PSHost"/> that offers dialog-oriented and /// line-oriented interactive features. /// </summary> /// <seealso cref="System.Management.Automation.Host.PSHost"/> /// <seealso cref="System.Management.Automation.Host.PSHostRawUserInterface"/> public abstract class PSHostUserInterface { /// <summary> /// Gets hosting application's implementation of the /// <see cref="System.Management.Automation.Host.PSHostRawUserInterface"/> abstract base class /// that implements that class. /// </summary> /// <value> /// A reference to an instance of the hosting application's implementation of a class derived from /// <see cref="System.Management.Automation.Host.PSHostUserInterface"/>, or null to indicate that /// low-level user interaction is not supported. /// </value> public abstract System.Management.Automation.Host.PSHostRawUserInterface RawUI { get; } /// <summary> /// Returns true for hosts that support VT100 like virtual terminals. /// </summary> public virtual bool SupportsVirtualTerminal { get { return false; } } #region Line-oriented interaction /// <summary> /// Reads characters from the console until a newline (a carriage return) is encountered. /// </summary> /// <returns> /// The characters typed by the user. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> public abstract string ReadLine(); /// <summary> /// Same as ReadLine, except that the result is a SecureString, and that the input is not echoed to the user while it is /// collected (or is echoed in some obfuscated way, such as showing a dot for each character). /// </summary> /// <returns> /// The characters typed by the user in an encrypted form. /// </returns> /// <remarks> /// Note that credentials (a user name and password) should be gathered with /// <see cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/> /// <see cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/> /// </remarks> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> public abstract SecureString ReadLineAsSecureString(); /// <summary> /// Writes characters to the screen buffer. Does not append a carriage return. /// <!-- Here we choose to just offer string parameters rather than the 18 overloads from TextWriter --> /// </summary> /// <param name="value"> /// The characters to be written. null is not allowed. /// </param> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(ConsoleColor, ConsoleColor, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(System.ConsoleColor, System.ConsoleColor, string)"/> public abstract void Write(string value); /// <summary> /// Same as <see cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/>, /// except that colors can be specified. /// </summary> /// <param name="foregroundColor"> /// The foreground color to display the text with. /// </param> /// <param name="backgroundColor"> /// The foreground color to display the text with. /// </param> /// <param name="value"> /// The characters to be written. null is not allowed. /// </param> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(System.ConsoleColor, System.ConsoleColor, string)"/> public abstract void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value); /// <summary> /// The default implementation writes a carriage return to the screen buffer. /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(System.ConsoleColor, System.ConsoleColor, string)"/> /// </summary> public virtual void WriteLine() { WriteLine(string.Empty); } /// <summary> /// Writes characters to the screen buffer, and appends a carriage return. /// </summary> /// <param name="value"> /// The characters to be written. null is not allowed. /// </param> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(System.ConsoleColor, System.ConsoleColor, string)"/> public abstract void WriteLine(string value); /// <summary> /// Same as <see cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/>, /// except that colors can be specified. /// </summary> /// <param name="foregroundColor"> /// The foreground color to display the text with. /// </param> /// <param name="backgroundColor"> /// The foreground color to display the text with. /// </param> /// <param name="value"> /// The characters to be written. null is not allowed. /// </param> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/> public virtual void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value) { // #pragma warning disable 56506 // expressly not checking for value == null so that attempts to write a null cause an exception if ((value != null) && (value.Length != 0)) { Write(foregroundColor, backgroundColor, value); } Write("\n"); // #pragma warning restore 56506 } /// <summary> /// Writes a line to the "error display" of the host, as opposed to the "output display," which is /// written to by the variants of /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/> and /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/> /// </summary> /// <param name="value"> /// The characters to be written. /// </param> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Write(System.ConsoleColor, System.ConsoleColor, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine()"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteLine(string)"/> public abstract void WriteErrorLine(string value); /// <summary> /// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteDebug"/> to display a debugging message /// to the user. /// </summary> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteProgress"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteVerboseLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteWarningLine"/> public abstract void WriteDebugLine(string message); /// <summary> /// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteProgress(Int64, System.Management.Automation.ProgressRecord)"/> to display a progress record. /// </summary> /// <param name="sourceId"> /// Unique identifier of the source of the record. An int64 is used because typically, the 'this' pointer of /// the command from whence the record is originating is used, and that may be from a remote Runspace on a 64-bit /// machine. /// </param> /// <param name="record"> /// The record being reported to the host. /// </param> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteDebugLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteVerboseLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteWarningLine"/> public abstract void WriteProgress(Int64 sourceId, ProgressRecord record); /// <summary> /// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteVerbose"/> to display a verbose processing message to the user. /// </summary> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteDebugLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteProgress"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteWarningLine"/> public abstract void WriteVerboseLine(string message); /// <summary> /// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteWarning"/> to display a warning processing message to the user. /// </summary> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteDebugLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteProgress"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.WriteVerboseLine"/> public abstract void WriteWarningLine(string message); /// <summary> /// Invoked by <see cref="System.Management.Automation.Cmdlet.WriteInformation(InformationRecord)"/> to give the host a chance to intercept /// informational messages. These should not be displayed to the user by default, but may be useful to display in /// a separate area of the user interface. /// </summary> public virtual void WriteInformation(InformationRecord record) { } // Gets the state associated with PowerShell transcription. // // Ideally, this would be associated with the host instance, but remoting recycles host instances // for each command that gets invoked (so that it can keep track of the order of commands and their // output.) Therefore, we store this transcription data in the runspace. However, the // Runspace.DefaultRunspace property isn't always available (i.e.: when the pipeline is being set up), // so we have to cache it the first time it becomes available. private TranscriptionData TranscriptionData { get { // If we have access to a runspace, use the transcription data for that runspace. // This is important when you have multiple runspaces within a host. LocalRunspace localRunspace = Runspace.DefaultRunspace as LocalRunspace; if (localRunspace != null) { _volatileTranscriptionData = localRunspace.TranscriptionData; if (_volatileTranscriptionData != null) { return _volatileTranscriptionData; } } // Otherwise, use the last stored transcription data. This will let us transcribe // errors where the runspace has gone away. if (_volatileTranscriptionData != null) { return _volatileTranscriptionData; } TranscriptionData temporaryTranscriptionData = new TranscriptionData(); return temporaryTranscriptionData; } } private TranscriptionData _volatileTranscriptionData; /// <summary> /// Transcribes a command being invoked. /// </summary> /// <param name="commandText">The text of the command being invoked.</param> /// <param name="invocation">The invocation info of the command being transcribed.</param> internal void TranscribeCommand(string commandText, InvocationInfo invocation) { if (ShouldIgnoreCommand(commandText, invocation)) { return; } if (IsTranscribing) { // We don't actually log the output here, because there may be multiple command invocations // in a single input - especially in the case of API logging, which logs the command and // its parameters as separate calls. // Instead, we add this to the 'pendingOutput' collection, which we flush when either // the command generates output, or when we are told to invoke ignore the next command. foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend<TranscriptionOption>(TranscriptionData.SystemTranscript)) { if (transcript != null) { lock (transcript.OutputToLog) { if (transcript.OutputToLog.Count == 0) { if (transcript.IncludeInvocationHeader) { transcript.OutputToLog.Add("**********************"); transcript.OutputToLog.Add( string.Format( Globalization.CultureInfo.InvariantCulture, InternalHostUserInterfaceStrings.CommandStartTime, DateTime.Now.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture))); transcript.OutputToLog.Add("**********************"); } transcript.OutputToLog.Add(TranscriptionData.PromptText + commandText); } else { transcript.OutputToLog.Add(">> " + commandText); } } } } } } private bool ShouldIgnoreCommand(string logElement, InvocationInfo invocation) { string commandName = logElement; if (invocation != null) { commandName = invocation.InvocationName; // Do not transcribe Out-Default CmdletInfo invocationCmdlet = invocation.MyCommand as CmdletInfo; if (invocationCmdlet != null) { if (invocationCmdlet.ImplementingType == typeof(Microsoft.PowerShell.Commands.OutDefaultCommand)) { // We will ignore transcribing the command itself, but not call the IgnoreCommand() method // (because that will ignore the results) return true; } } // Don't log internal commands to the transcript. if (invocation.CommandOrigin == CommandOrigin.Internal) { IgnoreCommand(logElement, invocation); return true; } } // Don't log helper commands to the transcript string[] helperCommands = { "TabExpansion2", "prompt", "TabExpansion", "PSConsoleHostReadline" }; foreach (string helperCommand in helperCommands) { if (string.Equals(helperCommand, commandName, StringComparison.OrdinalIgnoreCase)) { IgnoreCommand(logElement, invocation); // Record that this is a helper command. In this case, we ignore even the results // from Out-Default TranscriptionData.IsHelperCommand = true; return true; } } return false; } /// <summary> /// Signals that a command being invoked (and its output) should be ignored. /// </summary> /// <param name="commandText">The text of the command being invoked.</param> /// <param name="invocation">The invocation info of the command being transcribed.</param> internal void IgnoreCommand(string commandText, InvocationInfo invocation) { TranscribeCommandComplete(null); if (TranscriptionData.CommandBeingIgnored == null) { TranscriptionData.CommandBeingIgnored = commandText; TranscriptionData.IsHelperCommand = false; if ((invocation != null) && (invocation.MyCommand != null)) { TranscriptionData.CommandBeingIgnored = invocation.MyCommand.Name; } } } /// <summary> /// Flag to determine whether the host is in "Transcribe Only" mode, /// so that when content is sent through Out-Default it doesn't /// make it to the actual host. /// </summary> internal bool TranscribeOnly => Interlocked.CompareExchange(ref _transcribeOnlyCount, 0, 0) != 0; private int _transcribeOnlyCount = 0; internal IDisposable SetTranscribeOnly() => new TranscribeOnlyCookie(this); private sealed class TranscribeOnlyCookie : IDisposable { private readonly PSHostUserInterface _ui; private bool _disposed = false; public TranscribeOnlyCookie(PSHostUserInterface ui) { _ui = ui; Interlocked.Increment(ref _ui._transcribeOnlyCount); } public void Dispose() { if (!_disposed) { Interlocked.Decrement(ref _ui._transcribeOnlyCount); _disposed = true; GC.SuppressFinalize(this); } } ~TranscribeOnlyCookie() => Dispose(); } /// <summary> /// Flag to determine whether the host is transcribing. /// </summary> internal bool IsTranscribing { get { CheckSystemTranscript(); return (TranscriptionData.Transcripts.Count > 0) || (TranscriptionData.SystemTranscript != null); } } private void CheckSystemTranscript() { lock (TranscriptionData) { if (TranscriptionData.SystemTranscript == null) { TranscriptionData.SystemTranscript = PSHostUserInterface.GetSystemTranscriptOption(TranscriptionData.SystemTranscript); if (TranscriptionData.SystemTranscript != null) { LogTranscriptHeader(null, TranscriptionData.SystemTranscript); } } } } internal void StartTranscribing(string path, System.Management.Automation.Remoting.PSSenderInfo senderInfo, bool includeInvocationHeader, bool useMinimalHeader) { TranscriptionOption transcript = new TranscriptionOption(); transcript.Path = path; transcript.IncludeInvocationHeader = includeInvocationHeader; TranscriptionData.Transcripts.Add(transcript); LogTranscriptHeader(senderInfo, transcript, useMinimalHeader); } private void LogTranscriptHeader(System.Management.Automation.Remoting.PSSenderInfo senderInfo, TranscriptionOption transcript, bool useMinimalHeader = false) { // Transcribe the transcript header string line; if (useMinimalHeader) { line = string.Format( Globalization.CultureInfo.InvariantCulture, InternalHostUserInterfaceStrings.MinimalTranscriptPrologue, DateTime.Now); } else { string username = Environment.UserDomainName + "\\" + Environment.UserName; string runAsUser = username; if (senderInfo != null) { username = senderInfo.UserInfo.Identity.Name; } // Add bits from PSVersionTable StringBuilder versionInfoFooter = new StringBuilder(); Hashtable versionInfo = PSVersionInfo.GetPSVersionTable(); foreach (string versionKey in versionInfo.Keys) { object value = versionInfo[versionKey]; if (value != null) { var arrayValue = value as object[]; string valueString = arrayValue != null ? string.Join(", ", arrayValue) : value.ToString(); versionInfoFooter.AppendLine(versionKey + ": " + valueString); } } string configurationName = string.Empty; if (senderInfo != null && !string.IsNullOrEmpty(senderInfo.ConfigurationName)) { configurationName = senderInfo.ConfigurationName; } line = string.Format( Globalization.CultureInfo.InvariantCulture, InternalHostUserInterfaceStrings.TranscriptPrologue, DateTime.Now, username, runAsUser, configurationName, Environment.MachineName, Environment.OSVersion.VersionString, string.Join(" ", Environment.GetCommandLineArgs()), Environment.ProcessId, versionInfoFooter.ToString().TrimEnd()); } lock (transcript.OutputToLog) { transcript.OutputToLog.Add(line); } TranscribeCommandComplete(null); } internal string StopTranscribing() { if (TranscriptionData.Transcripts.Count == 0) { throw new PSInvalidOperationException(InternalHostUserInterfaceStrings.HostNotTranscribing); } TranscriptionOption stoppedTranscript = TranscriptionData.Transcripts[TranscriptionData.Transcripts.Count - 1]; LogTranscriptFooter(stoppedTranscript); stoppedTranscript.Dispose(); TranscriptionData.Transcripts.Remove(stoppedTranscript); return stoppedTranscript.Path; } private void LogTranscriptFooter(TranscriptionOption stoppedTranscript) { // Transcribe the transcript epilogue try { string message = string.Format( Globalization.CultureInfo.InvariantCulture, InternalHostUserInterfaceStrings.TranscriptEpilogue, DateTime.Now); lock (stoppedTranscript.OutputToLog) { stoppedTranscript.OutputToLog.Add(message); } TranscribeCommandComplete(null); } catch (Exception) { // Ignoring errors when stopping transcription (i.e.: file in use, access denied) // since this is probably handling exactly that error. } } internal void StopAllTranscribing() { TranscribeCommandComplete(null); while (TranscriptionData.Transcripts.Count > 0) { StopTranscribing(); } lock (TranscriptionData) { if (TranscriptionData.SystemTranscript != null) { LogTranscriptFooter(TranscriptionData.SystemTranscript); TranscriptionData.SystemTranscript.Dispose(); TranscriptionData.SystemTranscript = null; lock (s_systemTranscriptLock) { systemTranscript = null; } } } } /// <summary> /// Transcribes the supplied result text to the transcription buffer. /// </summary> /// <param name="sourceRunspace">The runspace that was used to generate this result, if it is not the current runspace.</param> /// <param name="resultText">The text to be transcribed.</param> internal void TranscribeResult(Runspace sourceRunspace, string resultText) { if (IsTranscribing) { // If the runspace that this result applies to is not the current runspace, update Runspace.DefaultRunspace // so that the transcript paths / etc. will be available to the TranscriptionData accessor. Runspace originalDefaultRunspace = null; if (sourceRunspace != null) { originalDefaultRunspace = Runspace.DefaultRunspace; Runspace.DefaultRunspace = sourceRunspace; } try { // If we're ignoring a command, ignore its output. if (TranscriptionData.CommandBeingIgnored != null) { // If we're ignoring a prompt, capture the value if (string.Equals("prompt", TranscriptionData.CommandBeingIgnored, StringComparison.OrdinalIgnoreCase)) { TranscriptionData.PromptText = resultText; } return; } resultText = resultText.TrimEnd(); foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend<TranscriptionOption>(TranscriptionData.SystemTranscript)) { if (transcript != null) { lock (transcript.OutputToLog) { transcript.OutputToLog.Add(resultText); } } } } finally { if (originalDefaultRunspace != null) { Runspace.DefaultRunspace = originalDefaultRunspace; } } } } /// <summary> /// Transcribes the supplied result text to the transcription buffer. /// </summary> /// <param name="resultText">The text to be transcribed.</param> internal void TranscribeResult(string resultText) { TranscribeResult(null, resultText); } /// <summary> /// Transcribes / records the completion of a command. /// </summary> /// <param name="invocation"></param> internal void TranscribeCommandComplete(InvocationInfo invocation) { FlushPendingOutput(); if (invocation != null) { // If we're ignoring a command that was internal, we still want the // results of Out-Default. However, if it was a host helper command, // ignore all output (including Out-Default) string commandNameToCheck = TranscriptionData.CommandBeingIgnored; if (TranscriptionData.IsHelperCommand) { commandNameToCheck = "Out-Default"; } // If we're completing a command that we were ignoring, start transcribing results / etc. again. if ((TranscriptionData.CommandBeingIgnored != null) && (invocation != null) && (invocation.MyCommand != null) && string.Equals(commandNameToCheck, invocation.MyCommand.Name, StringComparison.OrdinalIgnoreCase)) { TranscriptionData.CommandBeingIgnored = null; TranscriptionData.IsHelperCommand = false; } } } internal void TranscribePipelineComplete() { FlushPendingOutput(); TranscriptionData.CommandBeingIgnored = null; TranscriptionData.IsHelperCommand = false; } private void FlushPendingOutput() { foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend<TranscriptionOption>(TranscriptionData.SystemTranscript)) { if (transcript != null) { lock (transcript.OutputToLog) { if (transcript.OutputToLog.Count == 0) { continue; } lock (transcript.OutputBeingLogged) { bool alreadyLogging = transcript.OutputBeingLogged.Count > 0; transcript.OutputBeingLogged.AddRange(transcript.OutputToLog); transcript.OutputToLog.Clear(); // If there is already a thread trying to log output, add this output to its buffer // and don't start a new thread. if (alreadyLogging) { continue; } } } // Create the file in the main thread and flush the contents in the background thread. // Transcription should begin only if file generation is successful. // If there is an error in file generation, throw the exception. string baseDirectory = Path.GetDirectoryName(transcript.Path); if (Directory.Exists(transcript.Path) || (string.Equals(baseDirectory, transcript.Path.TrimEnd(Path.DirectorySeparatorChar), StringComparison.Ordinal))) { string errorMessage = string.Format( System.Globalization.CultureInfo.CurrentCulture, InternalHostUserInterfaceStrings.InvalidTranscriptFilePath, transcript.Path); throw new ArgumentException(errorMessage); } if (!Directory.Exists(baseDirectory)) { Directory.CreateDirectory(baseDirectory); } if (!File.Exists(transcript.Path)) { File.Create(transcript.Path).Dispose(); } // Do the actual writing in the background so that it doesn't hold up the UI thread. Task writer = Task.Run(() => { // System transcripts can have high contention. Do exponential back-off on writing // if needed. int delay = new Random().Next(10) + 1; bool written = false; while (!written) { try { transcript.FlushContentToDisk(); written = true; } catch (IOException) { System.Threading.Thread.Sleep(delay); } catch (UnauthorizedAccessException) { System.Threading.Thread.Sleep(delay); } // If we are trying to log, but weren't able too, back of the sleep. // If we're already sleeping for 1 second between tries, then just continue // at this pace until the write is successful. if (delay < 1000) { delay *= 2; } } }); } } } #endregion Line-oriented interaction #region Dialog-oriented Interaction /// <summary> /// Constructs a 'dialog' where the user is presented with a number of fields for which to supply values. /// </summary> /// <param name="caption"> /// Caption to precede or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)" /// </param> /// <param name="message"> /// A text description of the set of fields to be prompt. /// </param> /// <param name="descriptions"> /// Array of FieldDescriptions that contain information about each field to be prompted for. /// </param> /// <returns> /// A Dictionary object with results of prompting. The keys are the field names from the FieldDescriptions, the values /// are objects representing the values of the corresponding fields as collected from the user. To the extent possible, /// the host should return values of the type(s) identified in the FieldDescription. When that is not possible (for /// example, the type is not available to the host), the host should return the value as a string. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/> public abstract Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions); /// <summary> /// Prompt for credentials. /// <!--In future, when we have Credential object from the security team, /// this function will be modified to prompt using secure-path /// if so configured.--> /// </summary> /// <summary> /// Prompt for credential. /// </summary> /// <param name="caption"> /// Caption for the message. /// </param> /// <param name="message"> /// Text description for the credential to be prompt. /// </param> /// <param name="userName"> /// Name of the user whose credential is to be prompted for. If set to null or empty /// string, the function will prompt for user name first. /// </param> /// <param name="targetName"> /// Name of the target for which the credential is being collected. /// </param> /// <returns> /// User input credential. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/> public abstract PSCredential PromptForCredential(string caption, string message, string userName, string targetName ); /// <summary> /// Prompt for credential. /// </summary> /// <param name="caption"> /// Caption for the message. /// </param> /// <param name="message"> /// Text description for the credential to be prompt. /// </param> /// <param name="userName"> /// Name of the user whose credential is to be prompted for. If set to null or empty /// string, the function will prompt for user name first. /// </param> /// <param name="targetName"> /// Name of the target for which the credential is being collected. /// </param> /// <param name="allowedCredentialTypes"> /// Types of credential can be supplied by the user. /// </param> /// <param name="options"> /// Options that control the credential gathering UI behavior /// </param> /// <returns> /// User input credential. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/> public abstract PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options ); /// <summary> /// Presents a dialog allowing the user to choose an option from a set of options. /// </summary> /// <param name="caption"> /// Caption to precede or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)" /// </param> /// <param name="message"> /// A message that describes what the choice is for. /// </param> /// <param name="choices"> /// An Collection of ChoiceDescription objects that describe each choice. /// </param> /// <param name="defaultChoice"> /// The index of the label in the choices collection element to be presented to the user as the default choice. -1 /// means "no default". Must be a valid index. /// </param> /// <returns> /// The index of the choices element that corresponds to the option selected. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLine"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.ReadLineAsSecureString"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.Prompt"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string)"/> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForCredential(string, string, string, string, System.Management.Automation.PSCredentialTypes, System.Management.Automation.PSCredentialUIOptions)"/> public abstract int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice); #endregion Dialog-oriented interaction /// <summary> /// Creates a new instance of the PSHostUserInterface class. /// </summary> protected PSHostUserInterface() { CheckSystemTranscript(); } /// <summary> /// Helper to transcribe an error through formatting and output. /// </summary> /// <param name="context">The Execution Context.</param> /// <param name="invocation">The invocation info associated with the record.</param> /// <param name="errorWrap">The error record.</param> internal void TranscribeError(ExecutionContext context, InvocationInfo invocation, PSObject errorWrap) { context.InternalHost.UI.TranscribeCommandComplete(invocation); InitialSessionState minimalState = InitialSessionState.CreateDefault2(); Collection<PSObject> results = PowerShell.Create(minimalState).AddCommand("Out-String").Invoke( new List<PSObject>() { errorWrap }); TranscribeResult(results[0].ToString()); } /// <summary> /// Get Module Logging information from the registry. /// </summary> internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOption currentTranscript) { var transcription = InternalTestHooks.BypassGroupPolicyCaching ? Utils.GetPolicySetting<Transcription>(Utils.SystemWideThenCurrentUserConfig) : s_transcriptionSettingCache.Value; if (transcription != null) { // If we have an existing system transcript for this process, use that. // Otherwise, populate the static variable with the result of the group policy setting. // // This way, multiple runspaces opened by the same process will share the same transcript. lock (s_systemTranscriptLock) { if (systemTranscript == null) { systemTranscript = PSHostUserInterface.GetTranscriptOptionFromSettings(transcription, currentTranscript); } } } return systemTranscript; } internal static TranscriptionOption systemTranscript = null; private static readonly object s_systemTranscriptLock = new object(); private static readonly Lazy<Transcription> s_transcriptionSettingCache = new Lazy<Transcription>( () => Utils.GetPolicySetting<Transcription>(Utils.SystemWideThenCurrentUserConfig), isThreadSafe: true); private static TranscriptionOption GetTranscriptOptionFromSettings(Transcription transcriptConfig, TranscriptionOption currentTranscript) { TranscriptionOption transcript = null; if (transcriptConfig.EnableTranscripting == true) { if (currentTranscript != null) { return currentTranscript; } transcript = new TranscriptionOption(); // Pull out the transcript path if (transcriptConfig.OutputDirectory != null) { transcript.Path = GetTranscriptPath(transcriptConfig.OutputDirectory, true); } else { transcript.Path = GetTranscriptPath(); } // Pull out the "enable invocation header" transcript.IncludeInvocationHeader = transcriptConfig.EnableInvocationHeader == true; } return transcript; } internal static string GetTranscriptPath() { string baseDirectory = Platform.GetFolderPath(Environment.SpecialFolder.MyDocuments); return GetTranscriptPath(baseDirectory, false); } internal static string GetTranscriptPath(string baseDirectory, bool includeDate) { if (string.IsNullOrEmpty(baseDirectory)) { baseDirectory = Platform.GetFolderPath(Environment.SpecialFolder.MyDocuments); } else { if (!Path.IsPathRooted(baseDirectory)) { baseDirectory = Path.Combine( Platform.GetFolderPath(Environment.SpecialFolder.MyDocuments), baseDirectory); } } if (includeDate) { baseDirectory = Path.Combine(baseDirectory, DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture)); } // transcriptPath includes some randomness so that files can be collected on a central share, // and an attacker can't guess the filename and read the contents if the ACL was poor. // After testing, a computer can do about 10,000 remote path tests per second. So 6 // bytes of randomness (2^48 = 2.8e14) would take an attacker about 891 years to guess // a filename (assuming they knew the time the transcript was started). // (5 bytes = 3 years, 4 bytes = about a month) byte[] randomBytes = new byte[6]; System.Security.Cryptography.RandomNumberGenerator.Create().GetBytes(randomBytes); string filename = string.Format( Globalization.CultureInfo.InvariantCulture, "PowerShell_transcript.{0}.{1}.{2:yyyyMMddHHmmss}.txt", Environment.MachineName, Convert.ToBase64String(randomBytes).Replace('/', '_'), DateTime.Now); string transcriptPath = System.IO.Path.Combine(baseDirectory, filename); return transcriptPath; } } // Holds runspace-wide transcription data / settings for PowerShell transcription internal class TranscriptionData { internal TranscriptionData() { Transcripts = new List<TranscriptionOption>(); SystemTranscript = null; CommandBeingIgnored = null; IsHelperCommand = false; PromptText = "PS>"; } internal List<TranscriptionOption> Transcripts { get; } internal TranscriptionOption SystemTranscript { get; set; } internal string CommandBeingIgnored { get; set; } internal bool IsHelperCommand { get; set; } internal string PromptText { get; set; } } // Holds options for PowerShell transcription internal class TranscriptionOption : IDisposable { internal TranscriptionOption() { OutputToLog = new List<string>(); OutputBeingLogged = new List<string>(); } /// <summary> /// The path that this transcript is being logged to. /// </summary> internal string Path { get; set; } /// <summary> /// Any output to log for this transcript. /// </summary> internal List<string> OutputToLog { get; } /// <summary> /// Any output currently being logged for this transcript. /// </summary> internal List<string> OutputBeingLogged { get; } /// <summary> /// Whether to include time stamp / command separators in /// transcript output. /// </summary> internal bool IncludeInvocationHeader { get; set; } /// <summary> /// Logs buffered content to disk. We use this instead of File.AppendAllLines /// so that we don't need to pay seek penalties all the time, and so that we /// don't need append permission to our own files. /// </summary> internal void FlushContentToDisk() { static Encoding GetPathEncoding(string path) { using StreamReader reader = new StreamReader(path, Utils.utf8NoBom, detectEncodingFromByteOrderMarks: true); _ = reader.Read(); return reader.CurrentEncoding; } lock (OutputBeingLogged) { if (!_disposed) { if (_contentWriter == null) { try { var currentEncoding = GetPathEncoding(this.Path); // Try to first open the file with permissions that will allow us to read from it // later. _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read), currentEncoding); _contentWriter.BaseStream.Seek(0, SeekOrigin.End); } catch (IOException) { // If that doesn't work (i.e.: logging to a tightly-ACL'd share), request fewer // file permissions. _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.Append, FileAccess.Write, FileShare.Read), Utils.utf8NoBom); } _contentWriter.AutoFlush = true; } foreach (string line in this.OutputBeingLogged) { _contentWriter.WriteLine(line); } } OutputBeingLogged.Clear(); } } private StreamWriter _contentWriter = null; /// <summary> /// Disposes this runspace instance. Dispose will close the runspace if not closed already. /// </summary> public void Dispose() { if (_disposed) { return; } // Wait for any pending output to be flushed to disk so that Stop-Transcript // can be trusted to immediately have all content from that session in the file) int outputWait = 0; while ( (outputWait < 1000) && ((OutputToLog.Count > 0) || (OutputBeingLogged.Count > 0))) { System.Threading.Thread.Sleep(100); outputWait += 100; } if (_contentWriter != null) { try { _contentWriter.Flush(); _contentWriter.Dispose(); } catch (ObjectDisposedException) { // Do nothing } catch (IOException) { // Do nothing } _contentWriter = null; } _disposed = true; } private bool _disposed = false; } /// <summary> /// This interface needs to be implemented by PSHost objects that want to support PromptForChoice /// by giving the user ability to select more than one choice. The PromptForChoice method available /// in PSHostUserInterface class supports only one choice selection. /// </summary> public interface IHostUISupportsMultipleChoiceSelection { /// <summary> /// Presents a dialog allowing the user to choose options from a set of options. /// </summary> /// <param name="caption"> /// Caption to precede or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)" /// </param> /// <param name="message"> /// A message that describes what the choice is for. /// </param> /// <param name="choices"> /// An Collection of ChoiceDescription objects that describe each choice. /// </param> /// <param name="defaultChoices"> /// The index of the labels in the choices collection element to be presented to the user as /// the default choice(s). /// </param> /// <returns> /// The indices of the choice elements that corresponds to the options selected. The /// returned collection may contain duplicates depending on a particular host /// implementation. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> Collection<int> PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, IEnumerable<int> defaultChoices); } /// <summary> /// Helper methods used by PowerShell's Hosts: ConsoleHost and InternalHost to process /// PromptForChoice. /// </summary> internal static class HostUIHelperMethods { /// <summary> /// Constructs a string of the choices and their hotkeys. /// </summary> /// <param name="choices"></param> /// <param name="hotkeysAndPlainLabels"></param> /// <exception cref="ArgumentException"> /// 1. Cannot process the hot key because a question mark ("?") cannot be used as a hot key. /// </exception> internal static void BuildHotkeysAndPlainLabels(Collection<ChoiceDescription> choices, out string[,] hotkeysAndPlainLabels) { // we will allocate the result array hotkeysAndPlainLabels = new string[2, choices.Count]; for (int i = 0; i < choices.Count; ++i) { #region SplitLabel hotkeysAndPlainLabels[0, i] = string.Empty; int andPos = choices[i].Label.IndexOf('&'); if (andPos >= 0) { Text.StringBuilder splitLabel = new Text.StringBuilder(choices[i].Label.Substring(0, andPos), choices[i].Label.Length); if (andPos + 1 < choices[i].Label.Length) { splitLabel.Append(choices[i].Label.Substring(andPos + 1)); hotkeysAndPlainLabels[0, i] = CultureInfo.CurrentCulture.TextInfo.ToUpper(choices[i].Label.AsSpan(andPos + 1, 1).Trim().ToString()); } hotkeysAndPlainLabels[1, i] = splitLabel.ToString().Trim(); } else { hotkeysAndPlainLabels[1, i] = choices[i].Label; } #endregion SplitLabel // ? is not localizable if (string.Equals(hotkeysAndPlainLabels[0, i], "?", StringComparison.Ordinal)) { Exception e = PSTraceSource.NewArgumentException( string.Format(Globalization.CultureInfo.InvariantCulture, "choices[{0}].Label", i), InternalHostUserInterfaceStrings.InvalidChoiceHotKeyError); throw e; } } } /// <summary> /// Searches for a corresponding match between the response string and the choices. A match is either the response /// string is the full text of the label (sans hotkey marker), or is a hotkey. Full labels are checked first, and take /// precedence over hotkey matches. /// </summary> /// <param name="response"></param> /// <param name="choices"></param> /// <param name="hotkeysAndPlainLabels"></param> /// <returns> /// Returns the index into the choices array matching the response string, or -1 if there is no match. ///</returns> internal static int DetermineChoicePicked(string response, Collection<ChoiceDescription> choices, string[,] hotkeysAndPlainLabels) { Diagnostics.Assert(choices != null, "choices: expected a value"); Diagnostics.Assert(hotkeysAndPlainLabels != null, "hotkeysAndPlainLabels: expected a value"); int result = -1; // check the full label first, as this is the least ambiguous for (int i = 0; i < choices.Count; ++i) { // pick the one that matches either the hot key or the full label if (string.Equals(response, hotkeysAndPlainLabels[1, i], StringComparison.CurrentCultureIgnoreCase)) { result = i; break; } } // now check the hotkeys if (result == -1) { for (int i = 0; i < choices.Count; ++i) { // Ignore labels with empty hotkeys if (hotkeysAndPlainLabels[0, i].Length > 0) { if (string.Equals(response, hotkeysAndPlainLabels[0, i], StringComparison.CurrentCultureIgnoreCase)) { result = i; break; } } } } return result; } } }
46.067873
235
0.575893
[ "MIT" ]
jlee-consulting/PowerShell
src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs
61,086
C#
using System; using static FileToImage.Ui.ColorConsoleWrite; namespace FileToImage.Core { public class ImageReader { public ImageReader() { // Todo: // Ask the user for a png file // Split the file into equal parts for the workers. (Later optimisations could allow smaller chunks that are handed out when a worker is done with previous piece.) // Start the workers and wait for them all to complete and return their data. // Compile the final data into one file. // Ask the user to select a directory to save the file. ColorWriteLine("Not Implemented!", ConsoleColor.Magenta); } } }
37.052632
175
0.636364
[ "MIT" ]
Zargn/FileToImage
Core/ImageReader.cs
706
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; #if NET20 using Json.Lite.Utilities.LinqBridge; #else using System.Linq; #endif namespace Json.Lite.Utilities { internal static class BufferUtils { public static char[] RentBuffer(IArrayPool<char> bufferPool, int minSize) { if (bufferPool == null) { return new char[minSize]; } char[] buffer = bufferPool.Rent(minSize); return buffer; } public static void ReturnBuffer(IArrayPool<char> bufferPool, char[] buffer) { if (bufferPool == null) { return; } bufferPool.Return(buffer); } public static char[] EnsureBufferSize(IArrayPool<char> bufferPool, int size, char[] buffer) { if (bufferPool == null) { return new char[size]; } if (buffer != null) { bufferPool.Return(buffer); } return bufferPool.Rent(size); } } internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; private const int UnicodeTextLength = 6; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (var escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) { return HtmlCharEscapeFlags; } if (quoteChar == '"') { return DoubleQuoteCharEscapeFlags; } return SingleQuoteCharEscapeFlags; } public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) { if (s == null) { return false; } foreach (char c in s) { if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; } } return false; } public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char> bufferPool, ref char[] writeBuffer) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (s != null) { int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } StringUtils.ToCharAsUnicode(c, writeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); if (i > lastWritePosition) { int length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0); int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length); // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) { Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } BufferUtils.ReturnBuffer(bufferPool, writeBuffer); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { writer.Write(escapedValue); } else { writer.Write(writeBuffer, 0, UnicodeTextLength); } } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { int length = s.Length - lastWritePosition; if (writeBuffer == null || writeBuffer.Length < length) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16)) { char[] buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } } } }
35.455975
150
0.459867
[ "MIT" ]
TFrascaroli/Json.Net.Unity3D
src/Newtonsoft.Json/Utilities/JavaScriptUtils.cs
11,275
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Build.Evaluation; namespace FlatRedBall.Glue.VSHelpers.Projects { public class DesktopGlProject : VisualStudioProject { public override string ProjectId { get { return "DesktopGl"; } } public override string PrecompilerDirective { get { return "DESKTOP_GL"; } } public override bool AllowContentCompile { get { return false; } } public override List<string> LibraryDlls { get { return new List<string> { "FlatRedBallDesktopGL.dll" }; } } public override string ContentDirectory { get { return "Content/"; } } public override string FolderName { get { return "DesktopGl"; } } protected override bool NeedToSaveContentProject { get { return false; } } public override string NeededVisualStudioVersion { get { return "14.0"; } } public DesktopGlProject(Project project) : base(project) { } public override string ProcessInclude(string path) { var returnValue = base.ProcessInclude(path); return returnValue.ToLowerInvariant(); } public override string ProcessLink(string path) { var returnValue = base.ProcessLink(path); // Linux is case-sensitive return returnValue.ToLower(); } } }
23.708333
84
0.551845
[ "MIT" ]
coldacid/FlatRedBall
FRBDK/Glue/Glue/VSHelpers/Projects/DesktopGlProject.cs
1,709
C#
namespace BlazingPizza { public class UserInfo { public bool IsAuthenticated { get; set; } public string Name { get; set; } } }
15.8
49
0.588608
[ "MIT" ]
0468386988/start-point
src/BlazingPizza.Shared/UserInfo.cs
160
C#
#if !DISABLE_PLAYFABENTITY_API using PlayFab.AuthenticationModels; using PlayFab.Internal; using PlayFab.Json; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace PlayFab { /// <summary> /// The Authentication APIs provide a convenient way to convert classic authentication responses into entity authentication /// models. These APIs will provide you with the entity authentication token needed for subsequent Entity API calls. Manage /// API keys for authenticating any entity. /// </summary> public class PlayFabAuthenticationInstanceAPI { public readonly PlayFabApiSettings apiSettings = null; public readonly PlayFabAuthenticationContext authenticationContext = null; public PlayFabAuthenticationInstanceAPI() { authenticationContext = new PlayFabAuthenticationContext(); } public PlayFabAuthenticationInstanceAPI(PlayFabApiSettings settings) { apiSettings = settings; authenticationContext = new PlayFabAuthenticationContext(); } public PlayFabAuthenticationInstanceAPI(PlayFabAuthenticationContext context) { authenticationContext = context ?? new PlayFabAuthenticationContext(); } public PlayFabAuthenticationInstanceAPI(PlayFabApiSettings settings, PlayFabAuthenticationContext context) { apiSettings = settings; authenticationContext = context ?? new PlayFabAuthenticationContext(); } /// <summary> /// Verify entity login. /// </summary> public bool IsEntityLoggedIn() { return authenticationContext == null ? false : authenticationContext.IsEntityLoggedIn(); } /// <summary> /// Clear the Client SessionToken which allows this Client to call API calls requiring login. /// A new/fresh login will be required after calling this. /// </summary> public void ForgetAllCredentials() { authenticationContext?.ForgetAllCredentials(); } /// <summary> /// Method to exchange a legacy AuthenticationTicket or title SecretKey for an Entity Token or to refresh a still valid /// Entity Token. /// </summary> public async Task<PlayFabResult<GetEntityTokenResponse>> GetEntityTokenAsync(GetEntityTokenRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { var requestSettings = apiSettings ?? PlayFabSettings.staticSettings; string authKey = null, authValue = null; #if !DISABLE_PLAYFABCLIENT_API var clientSessionTicket = request?.AuthenticationContext?.ClientSessionTicket ?? authenticationContext.ClientSessionTicket; if (clientSessionTicket != null) { authKey = "X-Authorization"; authValue = clientSessionTicket; } #endif #if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API var settings = apiSettings ?? PlayFabSettings.staticSettings; var developerSecretKey = settings.DeveloperSecretKey; if (developerSecretKey != null) { authKey = "X-SecretKey"; authValue = developerSecretKey; } #endif #if !DISABLE_PLAYFABENTITY_API var entityToken = request?.AuthenticationContext?.EntityToken ?? authenticationContext.EntityToken; if (entityToken != null) { authKey = "X-EntityToken"; authValue = entityToken; } #endif var httpResult = await PlayFabHttp.DoPost("/Authentication/GetEntityToken", request, authKey, authValue, extraHeaders, requestSettings); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetEntityTokenResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetEntityTokenResponse>>(resultRawJson); var result = resultData.data; var updateContext = authenticationContext; updateContext.EntityToken = result.EntityToken; updateContext.EntityId = result.Entity.Id; updateContext.EntityType = result.Entity.Type; return new PlayFabResult<GetEntityTokenResponse> { Result = result, CustomData = customData }; } /// <summary> /// Method for a server to validate a client provided EntityToken. Only callable by the title entity. /// </summary> public async Task<PlayFabResult<ValidateEntityTokenResponse>> ValidateEntityTokenAsync(ValidateEntityTokenRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { var requestSettings = apiSettings ?? PlayFabSettings.staticSettings; if ((request?.AuthenticationContext?.EntityToken ?? authenticationContext.EntityToken) == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Authentication/ValidateEntityToken", request, "X-EntityToken", authenticationContext.EntityToken, extraHeaders, requestSettings); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ValidateEntityTokenResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ValidateEntityTokenResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ValidateEntityTokenResponse> { Result = result, CustomData = customData }; } } } #endif
47.782946
230
0.694354
[ "Apache-2.0" ]
kwasak/CSharpSDK
XamarinTestRunner/XamarinTestRunner/PlayFabSDK/PlayFabAuthenticationInstanceAPI.cs
6,164
C#
using Autofac; using Microsoft.Bot.Builder.Dialogs.Internals; using Microsoft.Bot.Builder.Internals.Fibers; using Microsoft.Bot.Connector; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Sample.AzureTable.Dialogs; namespace Microsoft.Bot.Sample.AzureTable.Controllers { // Autofac provides a mechanism to inject ActionFilterAttributes from the container // but seems to require the implementation of special interfaces // https://github.com/autofac/Autofac.WebApi/issues/6 [BotAuthentication] public class MessagesController : ApiController { // TODO: "service locator" private readonly ILifetimeScope scope; public MessagesController(ILifetimeScope scope) { SetField.NotNull(out this.scope, nameof(scope), scope); } /// <summary> /// POST: api/Messages /// receive a message from a user and send replies /// </summary> /// <param name="activity"></param> [ResponseType(typeof(void))] public virtual async Task<HttpResponseMessage> Post([FromBody] Activity activity) { // check if activity is of type message if (activity != null && activity.GetActivityType() == ActivityTypes.Message) { await Conversation.SendAsync(activity, () => new EchoDialog()); } else { HandleSystemMessage(activity); } return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted); } private Activity HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { // Handle conversation state changes, like members being added and removed // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info // Not available in all channels } else if (message.Type == ActivityTypes.ContactRelationUpdate) { // Handle add/remove from contact lists // Activity.From + Activity.Action represent what happened } else if (message.Type == ActivityTypes.Typing) { // Handle knowing tha the user is typing } else if (message.Type == ActivityTypes.Ping) { } return null; } } }
35.790123
101
0.61435
[ "MIT" ]
Bhaskers-Blu-Org2/BotBuilder-Azure
CSharp/Samples/AzureTable/Controllers/MessagesController.cs
2,901
C#
using System; namespace _12_Number_Checker { class Program { static void Main(string[] args) { try { int number = int.Parse(Console.ReadLine()); Console.WriteLine("It is a number."); } catch (Exception e) { Console.WriteLine("Invalid input!"); } } } }
13.952381
47
0.610922
[ "MIT" ]
alchemistbg/Software-University
02-Tech-Module/01-Programming-Fundamentals/02-Conditional-Statements-and-Loops/01-Lab/12_Number_Checker/Program.cs
295
C#
using MScResearchTool.Server.Core.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace MScResearchTool.Server.Core.Businesses { public interface IReportsBusiness { Task GenerateCrackingReportAsync(int fullCrackingId); Task GenerateIntegrationReportAsync(int fullIntegrationId); Task<IList<Report>> ReadAllAsync(); Task<Report> ReadByIdAsync(int reportId); Task DeleteAsync(int reportId); } }
29.6875
67
0.745263
[ "MIT" ]
zbigniewmarszolik/MScResearchTool
MScResearchTool.Server/MScResearchTool.Server.Core/Businesses/IReportsBusiness.cs
477
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Hangman_Game { public partial class EasyGame : Form { public EasyGame() { InitializeComponent(); } // PictureBoxes holding skeleton pictures. private PictureBox[] PictureBoxes; // The index of the current skeleton picture. private int CurrentPictureIndex = 0; // Words. private string[] Words; // The current word. private string CurrentWord = ""; // Labels to show the current word's letters. private List<Label> LetterLabels = new List<Label>(); // A list holding the letter buttons. private List<Button> KeyboardButtons; // Prepare to play. private void EasyGame_Load(object sender, EventArgs e) { // Save references to the PictureBoxes in the array. PictureBoxes = new PictureBox[] { picSkeleton0, picSkeleton1, picSkeleton2, picSkeleton3, picSkeleton4, picSkeleton5, picSkeleton6 }; // Load the words. Words = File.ReadAllLines(@"C:\Users\Kan\source\repos\Hangman_Game\Hangman_Game\EasyWords.txt"); // Make button images. MakeButtonImages(); } // Make the button images. private void MakeButtonImages() { // Prepare the buttons. KeyboardButtons = new List<Button>(); foreach (Control ctl in this.Controls) { if ((ctl is Button) && (!(ctl == btnNewGame))) { // Set the button's name. ctl.Name = "btn" + ctl.Text; // Attach the Click event handler. ctl.Click += btnKey_Click; // Make the button's image. MakeButtonImage(ctl as Button); // Save in the Buttons list for later use. KeyboardButtons.Add(ctl as Button); } } } // Give this button an image thet fits better than its letter. private void MakeButtonImage(Button btn) { Bitmap bm = new Bitmap(btn.ClientSize.Width, btn.ClientSize.Height); using (Graphics gr = Graphics.FromImage(bm)) { gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; using (StringFormat string_format = new StringFormat()) { string_format.Alignment = StringAlignment.Center; string_format.LineAlignment = StringAlignment.Center; gr.DrawString(btn.Text, btn.Font, Brushes.Black, btn.ClientRectangle, string_format); } } btn.Tag = btn.Text; btn.Image = bm; btn.Text = ""; } // Prepare for a new game. private void btnNewGame_Click(object sender, EventArgs e) { // Delete old letter labels. foreach (Label lbl in LetterLabels) { flpLetters.Controls.Remove(lbl); lbl.Dispose(); } // Pick a new word. Random rand = new Random(); CurrentWord = Words[rand.Next(Words.Length)].ToUpper(); // Console.WriteLine(CurrentWord); // Create new letter labels. LetterLabels = new List<Label>(); foreach (char ch in CurrentWord) { Label lbl = new Label(); flpLetters.Controls.Add(lbl); lbl.Tag = ch.ToString(); lbl.Size = btnQ.Size; lbl.TextAlign = ContentAlignment.MiddleCenter; lbl.BackColor = Color.White; lbl.BorderStyle = BorderStyle.Fixed3D; LetterLabels.Add(lbl); } // Hide the won/lost labels. lblWon.Visible = false; lblLost.Visible = false; // Enable the letter buttons. foreach (Button letter_btn in KeyboardButtons) letter_btn.Enabled = true; // Display the first picture. PictureBoxes[CurrentPictureIndex].Visible = false; CurrentPictureIndex = 0; PictureBoxes[CurrentPictureIndex].Visible = true; } // A key was clicked. private void btnKey_Click(object sender, EventArgs e) { // Disable this button so the user can't click it again. Button btn = sender as Button; btn.Enabled = false; // See if this letter is in the current word. string ch = btn.Tag.ToString(); if (CurrentWord.Contains(ch)) { // Good guess. Display matching letters. bool has_won = true; foreach (Label lbl in LetterLabels) { // See if this letter matches the current guess. if (lbl.Tag.ToString() == ch) lbl.Text = ch.ToString(); // See if the user has found this letter. if (lbl.Text == "") has_won = false; } // See if the user has won. if (has_won) { lblWon.Visible = true; foreach (Button letter_btn in KeyboardButtons) letter_btn.Enabled = false; } } else { // Bad guess. Show the next picture. PictureBoxes[CurrentPictureIndex].Visible = false; CurrentPictureIndex++; PictureBoxes[CurrentPictureIndex].Visible = true; // See if the user has lost. if (CurrentPictureIndex == PictureBoxes.Length - 1) { lblLost.Visible = true; foreach (Button letter_btn in KeyboardButtons) letter_btn.Enabled = false; foreach (Label lbl in LetterLabels) lbl.Text = lbl.Tag.ToString(); } } } private void btnQ_Click(object sender, EventArgs e) { } private void flpLetters_Paint(object sender, PaintEventArgs e) { } private void btnChooseGame_Click(object sender, EventArgs e) { ChooseGame Game = new ChooseGame(); this.Hide(); Game.Show(); } } }
32.782609
108
0.523136
[ "MIT" ]
KAr0ra/HangmanGame
HangmanGame/Hangman_Game/Hangman_Game/EasyGame.cs
6,788
C#
namespace TheBlueAlliance.Models { public class Events { public class Alliance { public object[] declines { get; set; } public string[] picks { get; set; } } public class Event { public string key { get; set; } public string website { get; set; } public string official { get; set; } public string end_date { get; set; } public string name { get; set; } public string short_name { get; set; } public string facebook_eid { get; set; } public string event_district_string { get; set; } public string venue_address { get; set; } public int? event_district { get; set; } public string location { get; set; } public string event_code { get; set; } public int year { get; set; } public Webcast[] webcast { get; set; } public Alliance[] alliances { get; set; } public string event_type_string { get; set; } public string start_date { get; set; } public int event_type { get; set; } } public class Webcast { public string type { get; set; } public string channel { get; set; } public string file { get; set; } } } }
34.25
61
0.518978
[ "MIT" ]
botaberg/TheBlueAlliance_API
TheBlueAlliance/TheBlueAlliance/Models/Events.cs
1,372
C#
using System; using Scriban; using Scriban.Parsing; using Scriban.Syntax; namespace Kalk.Core { public struct KalkBool : IEquatable<KalkBool>, IFormattable, IConvertible, IScriptConvertibleTo, IScriptConvertibleFrom, IScriptCustomTypeInfo { private int _value; public KalkBool(bool value) { _value = value ? -1 : 0; } public override string ToString() { return ToString(null, null); } public bool TryConvertFrom(TemplateContext context, SourceSpan span, object value) { try { _value = Convert.ToBoolean(value) ? -1 : 0; return true; } catch { // ignore } return false; } public bool TryConvertTo(TemplateContext context, SourceSpan span, Type type, out object value) { if (type == typeof(bool)) { value = (bool) this; return true; } try { value = Convert.ChangeType(_value, type); return true; } catch { // ignore } value = null; return false; } public string ToString(string? format, IFormatProvider? formatProvider) { return _value != 0 ? "true" : "false"; } public bool Equals(KalkBool other) { return _value == other._value; } public override bool Equals(object obj) { return obj is KalkBool other && Equals(other); } public override int GetHashCode() { return _value; } public static bool operator ==(KalkBool left, KalkBool right) { return left.Equals(right); } public static bool operator !=(KalkBool left, KalkBool right) { return !left.Equals(right); } public static implicit operator bool(KalkBool b) => b._value != 0; public static implicit operator KalkBool(bool b) => new KalkBool(b); TypeCode IConvertible.GetTypeCode() { return _value.GetTypeCode(); } bool IConvertible.ToBoolean(IFormatProvider? provider) { return ((IConvertible) _value).ToBoolean(provider); } byte IConvertible.ToByte(IFormatProvider? provider) { return ((IConvertible) _value).ToByte(provider); } char IConvertible.ToChar(IFormatProvider? provider) { return ((IConvertible) _value).ToChar(provider); } DateTime IConvertible.ToDateTime(IFormatProvider? provider) { return ((IConvertible) _value).ToDateTime(provider); } decimal IConvertible.ToDecimal(IFormatProvider? provider) { return ((IConvertible) _value).ToDecimal(provider); } double IConvertible.ToDouble(IFormatProvider? provider) { return ((IConvertible) _value).ToDouble(provider); } short IConvertible.ToInt16(IFormatProvider? provider) { return ((IConvertible) _value).ToInt16(provider); } int IConvertible.ToInt32(IFormatProvider? provider) { return ((IConvertible) _value).ToInt32(provider); } long IConvertible.ToInt64(IFormatProvider? provider) { return ((IConvertible) _value).ToInt64(provider); } sbyte IConvertible.ToSByte(IFormatProvider? provider) { return ((IConvertible) _value).ToSByte(provider); } float IConvertible.ToSingle(IFormatProvider? provider) { return ((IConvertible) _value).ToSingle(provider); } string IConvertible.ToString(IFormatProvider? provider) { return _value.ToString(provider); } object IConvertible.ToType(Type conversionType, IFormatProvider? provider) { return ((IConvertible) _value).ToType(conversionType, provider); } ushort IConvertible.ToUInt16(IFormatProvider? provider) { return ((IConvertible) _value).ToUInt16(provider); } uint IConvertible.ToUInt32(IFormatProvider? provider) { return ((IConvertible) _value).ToUInt32(provider); } ulong IConvertible.ToUInt64(IFormatProvider? provider) { return ((IConvertible) _value).ToUInt64(provider); } public string TypeName => "bool"; } }
26.685393
146
0.550526
[ "BSD-2-Clause" ]
thild/kalk
src/Kalk.Core/Modules/Vectors/KalkBool.cs
4,750
C#
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Solver.Base; namespace Solver.Challenges.Day4 { public class Day4Parser : IParser<Day4Input> { // add two new lines to the end of the input file!! public Day4Input Parse(string[] values) { var passports = new List<Passport>(); for (var i = 0; i < values.Length; i++) { var str = ""; for (var j = i; j < values.Length; j++) { if (string.IsNullOrWhiteSpace(values[j])) { var valueDict = str.Split(' ') .Where(r => !string.IsNullOrWhiteSpace(r)) .ToDictionary( r => r.Split(':').First(), r => r.Split(':').ElementAt(1)); int.TryParse(TakeIfExists(valueDict, "byr"), out var byr); int.TryParse(TakeIfExists(valueDict, "iyr"), out var iyr); int.TryParse(TakeIfExists(valueDict, "eyr"), out var eyr); var hgtS = TakeIfExists(valueDict, "hgt"); var hgtMatch = Regex.Match(hgtS, @"[a-z]+"); var hgtType = ""; if (hgtMatch.Success) hgtType = hgtMatch.Value; hgtMatch = Regex.Match(hgtS, @"[0-9]+"); var hgt = 0; if (hgtMatch.Success) int.TryParse(hgtMatch.Value, out hgt); var hcl = TakeIfExists(valueDict, "hcl"); var ecl = TakeIfExists(valueDict, "ecl"); var pid = TakeIfExists(valueDict, "pid"); var cid = TakeIfExists(valueDict, "cid"); passports.Add(new Passport(str, byr, iyr, eyr, hgt, hgtType, hcl, ecl, pid)); i = j; break; } str = $"{str} {values[j]}"; } } return new Day4Input(passports); } private string TakeIfExists(Dictionary<string, string> dict, string str) { if (dict.ContainsKey(str)) return dict[str]; return ""; } } }
24.621622
74
0.583425
[ "MIT" ]
klyse/AdventOfCode2020
Solver/Challenges/Day4/Day4Parser.cs
1,824
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ThreadPool { public class MyThreadPool : IDisposable { private int number; private Queue<Action> queue; private List<Thread> threadLst; private volatile bool stop; public MyThreadPool(int numberOfThreads) { queue = new Queue<Action>(); queue.Clear(); number = numberOfThreads; threadLst = new List<Thread>(); stop = false; for (int i = 0; i < number; i++) { threadLst.Add(new Thread(Work)); threadLst[i].Name = i.ToString(); threadLst[i].Start(); } } public void Enqueue(Action a) { Monitor.Enter(queue); try { queue.Enqueue(a); Monitor.PulseAll(queue); } finally { Monitor.Exit(queue); } } private void Work() { while (!stop) { Action act = null; bool flag; flag = false; Monitor.Enter(queue); try { while ((queue.Count == 0) && (!stop)) Monitor.Wait(queue); if (queue.Count > 0) { act = queue.Dequeue(); flag = true; } } finally { Monitor.Exit(queue); } if (flag) act?.Invoke(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool flag) { stop = true; if (flag) { Monitor.Enter(queue); try { queue.Clear(); Monitor.PulseAll(queue); } finally { Monitor.Exit(queue); } foreach (var t in threadLst) { t.Join(); } threadLst.Clear(); } } ~MyThreadPool() { Dispose(false); } } }
16.656863
43
0.567393
[ "MIT" ]
makar-pelogeiko/spbu-mm-programming
term_3/ThreadPool/ThreadPool.cs
1,701
C#
using Bb.Elastic.Runtimes; namespace Bb.Elastic.SqlParser.Models { public class ParameterBind : AstBase { public ParameterBind(Locator position) : base(position) { } public string Label { get; set; } public override T Accept<T>(IVisitor<T> visitor) { return visitor.VisitParameter(this); } } }
14.846154
63
0.580311
[ "MIT" ]
Black-Beard-Sdk/jslt
src/Black.Beard.Elasticsearch/SqlParser/Models/ParameterBind.cs
388
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WeaponDoc.Models { using System; using System.Collections.Generic; public partial class Program { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Program() { this.CallDetails = new HashSet<CallDetail>(); this.Parameters = new HashSet<Parameter>(); } public System.Guid ProgramID { get; set; } public System.Guid ItemTypeID { get; set; } public string Standard { get; set; } public string ProgramNameFull { get; set; } public string ProgramNameShort { get; set; } public Nullable<double> DurationPerUnit { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<CallDetail> CallDetails { get; set; } public virtual ItemType ItemType { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Parameter> Parameters { get; set; } } }
42.657895
128
0.613202
[ "MIT" ]
SergtoUn/GunSudexDoc
adminlte/Models/Program.cs
1,621
C#
namespace Gerrit.Api.Domain.Changes { /// <summary> /// The ProblemInfo entity contains a description of a potential consistency problem with a change. These are not /// related to the code review process, but rather indicate some inconsistency in Gerrit’s database or repository /// metadata related to the enclosing change. /// </summary> public class ProblemInfo { /// <summary> /// Plaintext message describing the problem with the change. /// </summary> public string Message { get; set; } /// <summary> /// The status of fixing the problem (FIXED, FIX_FAILED). Only set if a fix was attempted. /// </summary> public string Status { get; set; } /// <summary> /// If status is set, an additional plaintext message describing the outcome of the fix. /// </summary> public string Outcome { get; set; } } }
38.48
121
0.610187
[ "Apache-2.0" ]
GerritApiDotNet/Gerrit.Api.Net
src/Gerrit.Api.Domain/Changes/ProblemInfo.cs
966
C#
namespace Interfaces.Model { public interface IElementInfo { string Selector { get; } string Control { get; } string Id { get; } string Class { get; } string Name { get; } } }
19.083333
33
0.532751
[ "MIT" ]
doronguttman/time-tracker
Interfaces/Model/IElementInfo.cs
231
C#
using Godot; using System; namespace GodotFramework { public abstract class BaseSceneController : Singleton<BaseSceneController> { } }
14.8
78
0.743243
[ "MIT" ]
CreatoramaStudio/GodotFramework
Core/Managers/SceneController/BaseSceneController.cs
148
C#
public class Solution { public TreeNode IncreasingBST(TreeNode root) { var inorder = new List<int>(); //in-order traversal var st = new Stack<TreeNode>(); while(true){ while(root != null){ st.Push(root); root = root.left; } if(st.Count == 0) break; root = st.Pop(); inorder.Add(root.val); root = root.right; } root = new TreeNode(0); var cur = root; for(var i = 0; i < inorder.Count; ++i){ cur.right = new TreeNode(inorder[i]); cur = cur.right; } return root.right; } }
28.583333
50
0.457726
[ "MIT" ]
webigboss/Leetcode
897. Increasing Order Search Tree/897_Original_InOrder_Iterative_Traversal_with_a_Stack.cs
686
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace PaperMarioBattleSystem { /// <summary> /// Press a random sequence of buttons in the correct order within the time limit. /// </summary> public class MultiButtonCommand : ActionCommand { /// <summary> /// The minimum number of buttons that can appear in the button sequence. /// This should be greater than 0. /// </summary> protected int MinButtons = 1; /// <summary> /// The maximum number of buttons that can appear in the button sequence. /// </summary> protected int MaxButtons = 5; /// <summary> /// How long the player has to input all the buttons. /// </summary> public double InputDuration { get; protected set; } = 0d; /// <summary> /// The valid buttons that can be featured in the sequence. /// </summary> protected Keys[] ValidSequenceButtons = null; /// <summary> /// The final generated button sequence. /// </summary> public Keys[] ButtonSequence { get; protected set; }= null; /// <summary> /// The current index of the button to press. /// </summary> public int CurButtonIndex {get; protected set;}= 0; /// <summary> /// The next button to press in the button sequence. /// </summary> protected Keys NextButtonToPress => ButtonSequence[CurButtonIndex]; /// <summary> /// The amount of time elapsed since the Action Command started. /// </summary> private double ElapsedTime = 0d; public MultiButtonCommand(IActionCommandHandler commandHandler, int minButtons, int maxButtons, double inputDuration, params Keys[] validSequenceButtons) : base(commandHandler) { MinButtons = minButtons; MaxButtons = maxButtons; InputDuration = inputDuration; ValidSequenceButtons = validSequenceButtons; } public override void StartInput(params object[] values) { base.StartInput(values); //Generate the button sequence GenerateButtonSequence(); ElapsedTime = 0d; } protected override void ReadInput() { //End the Action Command with a Failure when time is up if (ElapsedTime >= InputDuration) { OnComplete(CommandResults.Failure); return; } //Increment time ElapsedTime += Time.ElapsedMilliseconds; //Check if the player pressed the correct button //If a button from the possible ones was pressed and the correct button wasn't, //the command is failed and ends immediately bool pressedCorrectButton = false; bool pressedIncorrectButton = false; //Go through all valid buttons and see which one was pressed for (int i = 0; i < ValidSequenceButtons.Length; i++) { Keys buttonPressed = ValidSequenceButtons[i]; if (AutoComplete == true || Input.GetKeyDown(buttonPressed) == true) { //If the button pressed is the next one that should be pressed, we pressed the correct one if (AutoComplete == true || buttonPressed == NextButtonToPress) { pressedCorrectButton = true; break; } else { pressedIncorrectButton = true; } } } //If we pressed the correct button, progress if (pressedCorrectButton == true) { //Increment the button index and check if we pressed all the buttons CurButtonIndex++; if (CurButtonIndex >= ButtonSequence.Length) { //If we pressed all the buttons, end the Action Command on a success SendCommandRank(CommandRank.Nice); OnComplete(CommandResults.Success); } } //If we pressed the incorrect button and not the correct one, it's a failure else if (pressedIncorrectButton == true) { OnComplete(CommandResults.Failure); } } protected virtual void GenerateButtonSequence() { //Get the number of buttons to be in the sequence int buttonsInSequence = RandomGlobals.Randomizer.Next(MinButtons, MaxButtons + 1); ButtonSequence = new Keys[buttonsInSequence]; //Go through the number of buttons and assign a random button out of the valid ones for (int i = 0; i < ButtonSequence.Length; i++) { int randButtonIndex = RandomGlobals.Randomizer.Next(0, ValidSequenceButtons.Length); ButtonSequence[i] = ValidSequenceButtons[randButtonIndex]; } } } }
37.168919
126
0.551718
[ "Unlicense" ]
kimimaru4000/PaperMarioBattleSystem
PaperMarioBattleSystem/PaperMarioBattleSystem/Classes/Actions/ActionCommands/MultiButtonCommand.cs
5,503
C#
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.ComponentModel.Composition; using System.Drawing; using System.Drawing.Imaging; using System.IO; using LevelEditorCore; using Sce.Atf; using Sce.Atf.Applications; namespace RenderingInterop { /// <summary> /// Generates thumbnail for dds and tga textures. /// </summary> [Export(typeof(IThumbnailResolver))] [PartCreationPolicy(CreationPolicy.Shared)] public class TextureThumbnailResolver : IThumbnailResolver { #region IThumbnailResolver Members Image IThumbnailResolver.Resolve(Uri resourceUri) { Image img = null; string path = resourceUri.LocalPath; if (path == null || !File.Exists(path)) return null; string extension = Path.GetExtension(path).ToLower(); var res = m_gameEngine.Info.ResourceInfos.GetByType(ResourceTypes.Texture); if(res.IsSupported(extension)) { ImageData imgdata = new ImageData(); imgdata.LoadFromFile(resourceUri); imgdata.Convert(ImageDataFORMAT.B8G8R8A8_UNORM); if (imgdata.IsValid) { Bitmap tempImage = new Bitmap((int)imgdata.Width, (int)imgdata.Height, PixelFormat.Format32bppArgb); BitmapData destData = null; try { destData = tempImage.LockBits( new Rectangle(0, 0, tempImage.Width, tempImage.Height), ImageLockMode.WriteOnly, tempImage.PixelFormat); unsafe { byte* srcScan0 = (byte*)imgdata.Data; int srcStride = imgdata.RowPitch; byte* destScan0 = (byte*)destData.Scan0; int destStride = destData.Stride; for (int y = 0; y < tempImage.Height; y++) { uint* srcRow = (uint*)(srcScan0 + y * srcStride); uint* destRow = (uint*)(destScan0 + y * destStride); for (int x = 0; x < tempImage.Width; x++) { *destRow++ = *srcRow++; } } } } finally { tempImage.UnlockBits(destData); } int width, height; float aspect = (float)tempImage.Width / (float)tempImage.Height; if (aspect > 1.0f) { width = (int)ThumbnailSize; height = (int)Math.Round(ThumbnailSize / aspect); } else { height = (int)ThumbnailSize; width = (int)Math.Round(ThumbnailSize * aspect); } img = GdiUtil.ResizeImage(tempImage, width, height); tempImage.Dispose(); imgdata.Dispose(); } } return img; } private const float ThumbnailSize = 96; #endregion [Import(AllowDefault = false)] private IGameEngineProxy m_gameEngine; } }
36.788462
121
0.440408
[ "Apache-2.0" ]
MasterScott/LevelEditor
LevelEditorNativeRendering/Resolvers/TextureThumbnailResolver.cs
3,726
C#
using HotChocolate.Types; namespace HotChocolate.Validation { public class ArgumentsType : ObjectType { public ArgumentsType() { } protected override void Configure(IObjectTypeDescriptor descriptor) { descriptor.Name("Arguments"); // multipleReqs(x: Int!, y: Int!): Int! descriptor.Field("multipleReqs") .Argument("x", t => t.Type<NonNullType<IntType>>()) .Argument("y", t => t.Type<NonNullType<IntType>>()) .Type<NonNullType<IntType>>() .Resolver(() => null); // booleanArgField(booleanArg: Boolean) : Boolean descriptor.Field("booleanArgField") .Argument("booleanArg", t => t.Type<BooleanType>()) .Type<BooleanType>() .Resolver(() => null); // floatArgField(floatArg: Float): Float descriptor.Field("floatArgField") .Argument("floatArg", t => t.Type<FloatType>()) .Type<FloatType>() .Resolver(() => null); // intArgField(intArg: Int): Int descriptor.Field("intArgField") .Argument("intArg", t => t.Type<IntType>()) .Type<NonNullType<IntType>>() .Resolver(() => null); // nonNullBooleanArgField(nonNullBooleanArg: Boolean!): Boolean! descriptor.Field("nonNullBooleanArgField") .Argument("nonNullBooleanArg", t => t.Type<NonNullType<BooleanType>>()) .Type<NonNullType<BooleanType>>() .Resolver(() => null); // booleanListArgField(booleanListArg: [Boolean]!) : [Boolean] descriptor.Field("multiplbooleanListArgFieldeReqs") .Argument("booleanListArg", t => t.Type<NonNullType<ListType<BooleanType>>>()) .Type<ListType<BooleanType>>() .Resolver(() => null); // optionalNonNullBooleanArgField(optionalBooleanArg: Boolean! = false) : Boolean! descriptor.Field("optionalNonNullBooleanArgField") .Argument("optionalBooleanArg", t => t.Type<NonNullType<BooleanType>>().DefaultValue(false)) .Argument("y", t => t.Type<NonNullType<IntType>>()) .Type<NonNullType<BooleanType>>() .Resolver(() => null); // booleanListArgField(booleanListArg: [Boolean]!) : [Boolean] descriptor.Field("nonNullBooleanListField") .Argument("nonNullBooleanListArg", t => t.Type<NonNullType<ListType<BooleanType>>>()) .Type<ListType<BooleanType>>() .Resolver(() => null); } } }
39.222222
94
0.53187
[ "MIT" ]
Coldplayer1995/GraphQLTest
src/Core/Validation.Tests/Types/ArgumentsType.cs
2,826
C#
using System.Collections.Generic; using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Domain { /// <summary> /// KoubeiTradeItemorderBuyModel Data Structure. /// </summary> public class KoubeiTradeItemorderBuyModel : AlipayObject { /// <summary> /// 业务产品 /// </summary> [JsonPropertyName("biz_product")] public string BizProduct { get; set; } /// <summary> /// 业务场景 /// </summary> [JsonPropertyName("biz_scene")] public string BizScene { get; set; } /// <summary> /// 买家支付宝ID /// </summary> [JsonPropertyName("buyer_id")] public string BuyerId { get; set; } /// <summary> /// 购买商品信息 /// </summary> [JsonPropertyName("item_order_details")] public List<ItemOrderDetail> ItemOrderDetails { get; set; } /// <summary> /// 商户订单号,64个字符以内、只能包含字母、数字、下划线;需保证在商户端不重复 /// </summary> [JsonPropertyName("out_order_no")] public string OutOrderNo { get; set; } /// <summary> /// 商户传入营销信息,具体值要和口碑约定,格式为json格式 /// </summary> [JsonPropertyName("promo_params")] public string PromoParams { get; set; } /// <summary> /// 门店ID /// </summary> [JsonPropertyName("shop_id")] public string ShopId { get; set; } /// <summary> /// 订单标题 /// </summary> [JsonPropertyName("subject")] public string Subject { get; set; } /// <summary> /// 该笔订单允许的最晚付款时间,逾期将关闭交易,取值范围:1m~30m(单位:分钟) 不传默认3m。 /// </summary> [JsonPropertyName("timeout")] public string Timeout { get; set; } /// <summary> /// 订单总金额,单位为元,精确到小数点后两位,必须等于费用之和 /// </summary> [JsonPropertyName("total_amount")] public string TotalAmount { get; set; } } }
26.847222
67
0.540093
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Domain/KoubeiTradeItemorderBuyModel.cs
2,233
C#
using System.Windows; using System.Windows.Input; namespace Gw2TinyWvwKillCounter.ViewAndViewModels { public partial class SettingsDialogView : Window { public SettingsDialogView() { InitializeComponent(); } private void DragWindowWithLeftMouseButton(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) DragMove(); } } }
23.842105
89
0.629139
[ "Apache-2.0" ]
Taschenbuch/Gw2TinyWvwKillCounter
Gw2TinyWvwKillCounter/ViewAndViewModels/SettingsDialogView.xaml.cs
455
C#
namespace ISDOCNet { [System.Diagnostics.DebuggerStepThroughAttribute()] public partial class CatalogueItemIdentification { #region Private fields private string _id; #endregion public string ID { get { return this._id; } set { this._id = value; } } } }
17.666667
55
0.462264
[ "MIT" ]
DaliVana/ISDOCNet
ISDOCNet/CatalogueItemIdentification.cs
424
C#
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace NicoNicoDownloader.Model { enum BatchDownloadProgressState { Begin, Complete, Failed } [XmlRootAttribute("DownloadMusic", IsNullable = false)] public class DownloadMusic { public string Version; [XmlArrayAttribute] public DownloadMusicItem[] items; public DownloadMusic() { this.Version = "1.0"; } } public class DownloadMusicItem { public string id; public bool IsFinished; public string music_name; public DownloadMusicItem() { this.IsFinished = false; } public DownloadMusicItem(string id,string name) : this() { this.id = id; this.music_name = name; } } class BatchDownloadModel { private DownloadMusic downloadMusic; private NicoNicoDownload nico; private CancellationTokenSource cancelToken = new CancellationTokenSource(); private BatchDownloadModel(NicoNicoDownload nico) { this.nico = nico; } public async static Task<BatchDownloadModel> LoginAsync(string email, string pass) { NicoNicoDownload nico = new NicoNicoDownload(); nico.TitleConverter = TitileConverterInfo.Build("format.txt", "bands.txt", "ignore.txt"); await nico.Login(email, pass); BatchDownloadModel _model = new BatchDownloadModel(nico); return _model; } public void LoadListFromFile(string filepath) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(DownloadMusic)); using (StreamReader sr = new StreamReader(filepath, Encoding.UTF8)) { this.downloadMusic = (DownloadMusic)xmlSerializer.Deserialize(sr); } } public void SaveListToFile(string filepath) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(DownloadMusic)); using (StreamWriter sw = new StreamWriter(filepath,false,Encoding.UTF8)) { xmlSerializer.Serialize(sw, this.downloadMusic); } } public bool IsAborted { get { return cancelToken.IsCancellationRequested; } } //id,state,message public Action<string,BatchDownloadProgressState,string> Progress; public async Task DownloadAsync() { foreach (var item in this.downloadMusic.items) { if (item.IsFinished == true) continue; Progress(item.id, BatchDownloadProgressState.Begin,null); try { await nico.GetMusicFile(item, cancelToken); if (cancelToken.IsCancellationRequested) { break; } else { Progress(item.id, BatchDownloadProgressState.Complete, null); Thread.Sleep(1000 * 10); } item.IsFinished = true; } catch (Exception ex) { Progress(item.id, BatchDownloadProgressState.Failed,ex.Message); } } } public void Cancel() { cancelToken.Cancel(); } } }
27.688889
101
0.546014
[ "MIT" ]
rirufa/NicoNicoDownload
Model/DownloadModel.cs
3,740
C#
using System; using System.Collections.Generic; using System.Text; namespace CarSimulation { class GeneticAlgorithGenomeBuilder : IBuilder { private readonly ICommand[] commands; private readonly float MutationChance; private readonly int HighestCommandID; private readonly Random rnd; /// <summary> /// /// </summary> /// <param name="oldGenome">old genome</param> /// <param name="mutationChance">chance of the mutation for this new genome (<c>0f</c> to <c>1f</c>)</param> /// <param name="highestCommandID">highest command id. Exclusive</param> public GeneticAlgorithGenomeBuilder(Genome oldGenome1, Genome oldGenome2, float mutationChance, int highestCommandID, Random rnd) { MutationChance = mutationChance; HighestCommandID = highestCommandID; //crossing Genome oldGenome = new Genome(oldGenome1.Commands); for (int i = 0; i < oldGenome.Commands.Length; i++) { if (i % 2 == 0) { oldGenome.Commands[i] = oldGenome1.Commands[i]; } else { oldGenome.Commands[i] = oldGenome2.Commands[i]; } } commands = new ICommand[oldGenome.Commands.Length]; oldGenome.Commands.CopyTo(commands, 0); this.rnd = rnd; } public IBuilder BuildCommandsList() { if (rnd.NextDouble() <= MutationChance) { for (int i = 0; i < rnd.Next(1, 6); i++) { int newCommand = rnd.Next(0, HighestCommandID); commands[rnd.Next(0, commands.Length)] = GenomeCreator.GetCommandFromOpCode(newCommand, 2f, 2f, 150, 2); } } return this; } public Genome Build() { Genome genome = new Genome(commands); return genome; } } }
34.433333
137
0.533882
[ "MIT" ]
TimofeyZaberejny/CarSimulation
CarSimulation/GeneticAlgorithGenomeBuilder.cs
2,068
C#
using System.Collections.Generic; using Baseline; using Microsoft.AspNetCore.Http; using Shouldly; using Xunit; namespace Alba.Testing { public class FormDataExtensionsTests { [Fact] public void round_trip_writing_and_parsing() { var form1 = new Dictionary<string, string> { ["a"] = "what?", ["b"] = "now?", ["c"] = "really?" }; var context = new DefaultHttpContext(); context.WriteFormData(form1); context.Request.Body.ReadAllText() .ShouldBe("a=what?&b=now?&c=really?"); } } }
20.212121
54
0.523238
[ "Apache-2.0" ]
JasperFx/Alba
src/Alba.Testing/FormDataExtensionsTests.cs
669
C#
using System; using Assman.Configuration; using Spark; namespace Assman.Spark { public class SparkJavascriptAssmanPlugin : IAssmanPlugin { public void Initialize(AssmanContext context) { var finder = CreateFinder(); context.AddFinder(finder); } private SparkResourceFinder CreateFinder() { var assemblies = AssmanConfiguration.Current.Assemblies.GetAssemblies(); var contentFetcher = CreateContentFetcher(); var actionFinder = CreateActionFinder(); return new SparkResourceFinder(assemblies, contentFetcher, actionFinder); } protected virtual ISparkJavascriptActionFinder CreateActionFinder() { return new AttributeBasedActionFinder(); } protected virtual ISparkResourceContentFetcher CreateContentFetcher() { var sparkSettings = GetSparkSettings(); return new SparkResourceContentFetcher(sparkSettings); } protected virtual ISparkSettings GetSparkSettings() { return new SparkSettings(); } } }
23.090909
77
0.731299
[ "BSD-3-Clause" ]
muslumbozan27/demirbas
src/Assman.Spark/SparkJavascriptAssmanPlugin.cs
1,016
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpReferenceHighlighting : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpReferenceHighlighting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpReferenceHighlighting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void Highlighting() { var markup = @" class {|definition:C|} { void M<T>({|reference:C|} c) where T : {|reference:C|} { {|reference:C|} c = new {|reference:C|}(); } }"; Test.Utilities.MarkupTestFile.GetSpans(markup, out var text, out IDictionary<string, ImmutableArray<TextSpan>> spans); VisualStudio.Editor.SetText(text); Verify("C", spans); // Verify tags disappear VerifyNone("void"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void WrittenReference() { var markup = @" class C { void M() { int {|definition:x|}; {|writtenreference:x|} = 3; } }"; Test.Utilities.MarkupTestFile.GetSpans(markup, out var text, out IDictionary<string, ImmutableArray<TextSpan>> spans); VisualStudio.Editor.SetText(text); Verify("x", spans); // Verify tags disappear VerifyNone("void"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void Navigation() { var text = @" class C { void M() { int x; x = 3; } }"; VisualStudio.Editor.SetText(text); VisualStudio.Editor.PlaceCaret("x"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.ExecuteCommand("Edit.NextHighlightedReference"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.Editor.Verify.CurrentLineText("x$$ = 3;", assertCaretPosition: true, trimWhitespace: true); } private void Verify(string marker, IDictionary<string, ImmutableArray<TextSpan>> spans) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.ReferenceHighlighting); AssertEx.SetEqual(spans["definition"], VisualStudio.Editor.GetTagSpans(DefinitionHighlightTag.TagId), message: "Testing 'definition'\r\n"); if (spans.ContainsKey("reference")) { AssertEx.SetEqual(spans["reference"], VisualStudio.Editor.GetTagSpans(ReferenceHighlightTag.TagId), message: "Testing 'reference'\r\n"); } if (spans.ContainsKey("writtenreference")) { AssertEx.SetEqual(spans["writtenreference"], VisualStudio.Editor.GetTagSpans(WrittenReferenceHighlightTag.TagId), message: "Testing 'writtenreference'\r\n"); } } private void VerifyNone(string marker) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.ReferenceHighlighting); Assert.Empty(VisualStudio.Editor.GetTagSpans(ReferenceHighlightTag.TagId)); Assert.Empty(VisualStudio.Editor.GetTagSpans(DefinitionHighlightTag.TagId)); } } }
37.679688
173
0.659755
[ "MIT" ]
06needhamt/roslyn
src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReferenceHighlighting.cs
4,825
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TypeRequestInfo.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.IoC { using System; /// <summary> /// Request information about a type. /// </summary> public class TypeRequestInfo { private int? _hash; private string _string; /// <summary> /// Initializes a new instance of the <see cref="TypeRequestInfo"/> class. /// </summary> /// <param name="type">The type.</param> /// <param name="tag">The tag.</param> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> public TypeRequestInfo(Type type, object tag = null) { Argument.IsNotNull("type", type); Type = type; Tag = tag; } /// <summary> /// Gets the type. /// </summary> /// <value>The type.</value> public Type Type { get; private set; } /// <summary> /// Gets the tag. /// </summary> /// <value>The tag.</value> public object Tag { get; private set; } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="firstObject">The first object.</param> /// <param name="secondObject">The second object.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(TypeRequestInfo firstObject, TypeRequestInfo secondObject) { if (ReferenceEquals(firstObject, secondObject)) { return true; } if (ReferenceEquals(null, firstObject)) { return false; } return firstObject.Equals(secondObject); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="firstObject">The first object.</param> /// <param name="secondObject">The second object.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(TypeRequestInfo firstObject, TypeRequestInfo secondObject) { return !(firstObject == secondObject); } /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="T:System.Object" /> to compare with the current <see cref="T:System.Object" />.</param> /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } var other = (TypeRequestInfo) obj; if (Type != other.Type) { return false; } if (!TagHelper.AreTagsEqual(Tag, other.Tag)) { return false; } return true; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { if (!_hash.HasValue) { #pragma warning disable HAA0101 // Array allocation for params parameter _hash = HashHelper.CombineHash(Type.GetHashCode(), (Tag is not null) ? Tag.GetHashCode() : 0); #pragma warning restore HAA0101 // Array allocation for params parameter } return _hash.Value; } /// <summary> /// Converts the type to a string. /// </summary> /// <returns>The string.</returns> public override string ToString() { if (_string is null) { _string = string.Format("{0} (tag = {1})", Type.FullName, ObjectToStringHelper.ToString(Tag)); } return _string; } } }
32.427586
140
0.498299
[ "MIT" ]
Catel/Catel
src/Catel.Core/IoC/TypeRequestInfo.cs
4,704
C#
using BaiduMapAPI.Models.Attributes; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace BaiduMapAPI.YingYan.V3.Analysis { /// <summary> /// 驾驶行为分析 /// <para>查询entity在指定时间段内的驾驶行为,返回以下分析结果:<br/> /// 1. 总体信息:起终点信息、里程、耗时、平均速度、最高速度<br/> /// 2. 异常信息:超速、急加速、急刹车、急转弯 /// </para> /// </summary> public class DrivingBehavior : Models.GetWithoutSNRequest<DrivingBehaviorResult> { /// <summary> /// 接口地址 /// </summary> public override string URL => "http://yingyan.baidu.com/api/v3/analysis/drivingbehavior"; /// <summary> /// service的ID(必填) /// <para>service 的唯一标识</para> /// <para>在轨迹管理台创建鹰眼服务时,系统返回的 service_id</para> /// </summary> [Display(Name = "service_id")] public int? ServiceID { get; set; } /// <summary> /// entity唯一标识(必填) /// <para>标识轨迹点所属的 entity</para> /// </summary> [Display(Name = "entity_name")] public string EntityName { get; set; } /// <summary> /// 开始时间(必填) /// </summary> [Display(Name = "start_time")] [UnixDateTimeConverter] public DateTime? StartTime { get; set; } /// <summary> /// 结束时间(必填) /// <para>结束时间不能大于当前时间,且起止时间区间不超过24小时。为提升响应速度,同时避免轨迹点过多造成请求超时(3s)失败,建议缩短每次请求的时间区间,将一天轨迹拆分成多段进行拼接</para> /// </summary> [Display(Name = "end_time")] [UnixDateTimeConverter] public DateTime? EndTime { get; set; } /// <summary> /// 固定限速值 /// <para>默认值:0</para> /// <para>取值规则:<br/> /// 0:根据百度地图道路限速数据计算超速点<br/> /// 其他数值:以设置的数值为阈值,轨迹点速度超过该值则认为是超速;</para> /// <para>示例: speeding_threshold=0,以道路限速数据计算 speeding_threshold=80,限速值为80km/h</para> /// </summary> [Display(Name = "speeding_threshold")] public double? SpeedingThreshold { get; set; } /// <summary> /// 急加速的加速度阈值 /// <para>单位:m/s^2</para> /// <para>默认值:1.67,仅支持正数</para> /// </summary> [Display(Name = "harsh_acceleration_threshold")] public double? HarshAccelerationThreshold { get; set; } /// <summary> /// 急减速的加速度阈值 /// <para>单位:m/s^2</para> /// <para>默认值:-1.67,仅支持负数</para> /// </summary> [Display(Name = "harsh_breaking_threshold")] public double? HarshBreakingThreshold { get; set; } /// <summary> /// 急转弯的向心加速度阈值 /// <para>单位:m/s^2</para> /// <para>默认值:5,仅支持正数</para> /// </summary> [Display(Name = "harsh_steering_threshold")] public double? HarshSteeringThreshold { get; set; } /// <summary> /// 纠偏选项 /// <para>可配置属性:need_mapmatch、transport_mode</para> /// </summary> [Display(Name = "process_option")] [FilterConverter(",", "=")] public Track.ProcessOption ProcessOption { get; set; } /// <summary> /// 返回的坐标类型 /// <para>默认值:bd09ll</para> /// <para>该字段用于控制返回结果中的坐标类型。可选值为:<br/> /// gcj02:国测局加密坐标<br/> /// bd09ll:百度经纬度坐标 /// </para> /// <para>该参数仅对国内(包含港、澳、台)轨迹有效,海外区域轨迹均返回 wgs84坐标系</para> /// </summary> [Display(Name = "coord_type_output")] [EnumName] public Models.Enums.CoordType? CoordTypeOutput { get; set; } } }
31.372727
111
0.549116
[ "MIT" ]
miracleQin/BaiduMapServerAPI.SDK
BaiduMapAPI.SDK/YingYan/V3/Analysis/DrivingBehavior.cs
4,367
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Azure.WebJobs.Script.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.WebJobs.Script.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Your function must contain a single public method, a public method named &apos;Run&apos;, or a public method matching the name specified in the &apos;entryPoint&apos; metadata property.. /// </summary> internal static string DotNetFunctionEntryPointRulesMessage { get { return ResourceManager.GetString("DotNetFunctionEntryPointRulesMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Completed downloading extension bundle from {0} to {1}. /// </summary> internal static string DownloadComplete { get { return ResourceManager.GetString("DownloadComplete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Downloading extension bundle from {0} to {1}. /// </summary> internal static string DownloadingZip { get { return ResourceManager.GetString("DownloadingZip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot delete an extension. Persistent file system not available in the current hosting environment. /// </summary> internal static string ErrorDeletingExtension { get { return ResourceManager.GetString("ErrorDeletingExtension", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error downloading zip content {0}. Status Code:{1}. Reason:{2}. /// </summary> internal static string ErrorDownloadingZip { get { return ResourceManager.GetString("ErrorDownloadingZip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error fetching version information for extension bundle {0}. /// </summary> internal static string ErrorFetchingVersionInfo { get { return ResourceManager.GetString("ErrorFetchingVersionInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot install an extension. Persistent file system not available in the current hosting environment. /// </summary> internal static string ErrorInstallingExtension { get { return ResourceManager.GetString("ErrorInstallingExtension", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Unable to find or download extension bundle. /// </summary> internal static string ErrorLoadingExtensionBundle { get { return ResourceManager.GetString("ErrorLoadingExtensionBundle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot delete extension when ExtensionBundles is configured.. /// </summary> internal static string ExtensionBundleBadRequestDelete { get { return ResourceManager.GetString("ExtensionBundleBadRequestDelete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cannot install extension when ExtensionBundles is configured.. /// </summary> internal static string ExtensionBundleBadRequestInstall { get { return ResourceManager.GetString("ExtensionBundleBadRequestInstall", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Binding metadata not found within the extension bundle or extension bundle is not configured for the function app.. /// </summary> internal static string ExtensionBundleBindingMetadataNotFound { get { return ResourceManager.GetString("ExtensionBundleBindingMetadataNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The value of id property in extensionBundle section of {0} file is invalid or missing. See https://aka.ms/functions-hostjson for more information. /// </summary> internal static string ExtensionBundleConfigMissingId { get { return ResourceManager.GetString("ExtensionBundleConfigMissingId", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The id and version property are missing in extensionBundle section of {0} file. See https://aka.ms/functions-hostjson for more information&quot;. /// </summary> internal static string ExtensionBundleConfigMissingMessage { get { return ResourceManager.GetString("ExtensionBundleConfigMissingMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The value of version property in extensionBundle section of {0} file is invalid or missing. See https://aka.ms/functions-hostjson for more information. /// </summary> internal static string ExtensionBundleConfigMissingVersion { get { return ResourceManager.GetString("ExtensionBundleConfigMissingVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Found a matching extension bundle at {0}. /// </summary> internal static string ExtensionBundleFound { get { return ResourceManager.GetString("ExtensionBundleFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Extension bundle configuration is not present in host.json. Cannot load content for file {0} content.. /// </summary> internal static string ExtensionBundleNotConfigured { get { return ResourceManager.GetString("ExtensionBundleNotConfigured", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Resources.{0} not found within the extension bundle or extension bundle is not configured for the function app.. /// </summary> internal static string ExtensionBundleResourcesLocaleNotFound { get { return ResourceManager.GetString("ExtensionBundleResourcesLocaleNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Resources metadata not found within the extension bundle or extension bundle is not configured for the function app.. /// </summary> internal static string ExtensionBundleResourcesNotFound { get { return ResourceManager.GetString("ExtensionBundleResourcesNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Templates not found within the extension bundle or extension bundle is not configured for the function app.. /// </summary> internal static string ExtensionBundleTemplatesNotFound { get { return ResourceManager.GetString("ExtensionBundleTemplatesNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Extracting extension bundle at {0}. /// </summary> internal static string ExtractingBundleZip { get { return ResourceManager.GetString("ExtractingBundleZip", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Fetching information on versions of extension bundle {0} available on {1}{2}. /// </summary> internal static string FetchingVersionInfo { get { return ResourceManager.GetString("FetchingVersionInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to File not found at {0}.. /// </summary> internal static string FileNotFound { get { return ResourceManager.GetString("FileNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Loading Extension bundle from {0}. /// </summary> internal static string LoadingExtensionBundle { get { return ResourceManager.GetString("LoadingExtensionBundle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Looking for extension bundle {0} at {1}. /// </summary> internal static string LocateExtensionBundle { get { return ResourceManager.GetString("LocateExtensionBundle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Bundle version matching the {0} was not found. /// </summary> internal static string MatchingBundleNotFound { get { return ResourceManager.GetString("MatchingBundleNotFound", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Zip extraction complete. /// </summary> internal static string ZipExtractionComplete { get { return ResourceManager.GetString("ZipExtractionComplete", resourceCulture); } } } }
43.238255
239
0.600621
[ "Apache-2.0", "MIT" ]
jijohn14/azure-functions-host
src/WebJobs.Script/Properties/Resources.Designer.cs
12,887
C#
using System; using System.Globalization; namespace SharpIrcBot.Plugins.Vitals.Nightscout { public static class NightscoutUtils { public const string DateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffzzz"; public static DateTimeOffset ParseTimestamp(string text) { // add colon to timezone text = text.Insert(text.Length - 2, ":"); // standard parse return DateTimeOffset.ParseExact(text, DateFormat, CultureInfo.InvariantCulture); } public static string TimestampToString(DateTimeOffset timestamp) { string text = timestamp.ToString(DateFormat, CultureInfo.InvariantCulture); // remove colon from timezone return text.Remove(text.Length - 3, 1); } } }
28.821429
93
0.629492
[ "MIT" ]
RavuAlHemio/SharpIrcBot
Plugins/Vitals/Nightscout/NightscoutUtils.cs
807
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace cronometro { public partial class Form1 : Form { int ss = 0; int mm = 0; int hh = 0; public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { ss++; lbss.Text = ss.ToString(); if (ss == 59) { mm++; lbmm.Text = mm.ToString(); ss = 0; } else if (mm == 59) { hh++; lbhh.Text = hh.ToString(); mm = 0; } else if (hh == 23) { hh = 0; } } private void button1_Click(object sender, EventArgs e) { timer1.Enabled = true; timer1.Start(); } private void button2_Click(object sender, EventArgs e) { timer1.Stop(); } private void button3_Click(object sender, EventArgs e) { timer1.Enabled = false; ss = 0; mm = 0; hh = 0; button2_Click(sender, e); limpiar(); //button1_Click(sender, e); } private void limpiar() { lbss.Text = "00"; lbmm.Text = "00"; lbhh.Text = "00"; } private void label3_Click(object sender, EventArgs e) { } private void label3_Click_1(object sender, EventArgs e) { } } }
20.735632
63
0.429047
[ "MIT" ]
arturo8484/ProyectoCronometro
cronometro/Form1.cs
1,806
C#
namespace MyCoolCarSystem.Results { public class ResultModel { public string FullName { get; set; } } }
17.714286
44
0.637097
[ "MIT" ]
georgidelchev/CSharp-Databases
02 - [Entity Framework Core]/11 - [Advanced Querying - Lab]/MyCoolCarSystem/Results/ResultModel.cs
126
C#
using System; using System.Runtime.InteropServices; using System.Security; namespace __Primitives__ { partial class WinAPI { partial class COM { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("56a86895-0ad4-11ce-b03a-0020af0ba770")] [SuppressUnmanagedCodeSecurity] public interface IBaseFilter { // IPersist void GetClassID(out Guid pClassID); // IMediaFilter void Stop(); void Pause(); void Run(Int64 tStart); void GetState(uint dwMilliSecsTimeout, out FILTER_STATE state); void SetSyncSource(IReferenceClock pClock); void GetSyncSource(out IReferenceClock pClock); // IBaseFilter void EnumPins(out IEnumPins ppEnum); void FindPin(string Id, out IPin ppPin); void QueryFilterInfo(out FILTER_INFO pInfo); void JoinFilterGraph(IFilterGraph pGraph, string pName); void QueryVendorInfo(out string pVendorInfo); } } } }
24.578947
67
0.729122
[ "Unlicense" ]
minagisyu/SmartAudioPlayerFx
SmartAudioPlayer Fx/__Primitives__/[Windows]/WinAPI/COM/IBaseFilter.cs
934
C#
namespace BackOffice.Infrastructure.EF.Configurations; public class ApproverConfiguration : IEntityTypeConfiguration<Approver> { public void Configure(EntityTypeBuilder<Approver> builder) { builder.ToTable("Approvers"); builder.HasKey(p => p.Id); builder.Property(p => p.Status).HasColumnName(nameof(Approver.Status).ToDatabaseFormat()); } }
27.285714
98
0.722513
[ "MIT" ]
beyondnetPeru/Beyondnet.Product.SkillMap
src/Services/BackOffice/BackOffice.Infrastructure.EF/Configurations/ApproverConfiguration.cs
384
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CorrectBrackets { class CheckBrackets { static string ValidateBrackets(string inputString) { bool isValid = true; int count = 0; for (int i = 0; i < inputString.Length; i++) { char currentChar = inputString[i]; if(currentChar == '(') { count++; } else if(currentChar == ')') { count--; } if(count < 0) { isValid = false; break; } } if (count != 0) { isValid = false; } if (isValid) { return "Correct"; } else { return "Incorrect"; } } static void Main(string[] args) { string input = Console.ReadLine(); Console.WriteLine(ValidateBrackets(input)); } } }
22.875
59
0.369243
[ "MIT" ]
SevdalinZhelyazkov/TelerikAcademy
CSharp-Part-2/StringAndTextProcessing/CorrectBrackets/CheckBrackets.cs
1,283
C#
namespace Vehicles.Models { public class Truck : Vehicle { private const double EXTRA_CONSUMPTION = 1.6; public Truck(double fuel, double consumption) : base(fuel, consumption) { this.Consumption += EXTRA_CONSUMPTION; } } }
21.071429
54
0.583051
[ "MIT" ]
VeselinBPavlov/csharp-oop-basics
14. Polymorphism - Exercise/Vehicles/Models/Truck.cs
297
C#
using Microsoft.Owin.Cors; using Newtonsoft.Json.Serialization; using Owin; using System.Net.Http.Formatting; using System.Web.Http; namespace Sales.API { public class Startup { public void Configuration(IAppBuilder appBuilder) { var config = new HttpConfiguration(); config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); config.Formatters .JsonFormatter .SerializerSettings .ContractResolver = new CamelCasePropertyNamesContractResolver(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); appBuilder.UseCors(CorsOptions.AllowAll); appBuilder.UseWebApi(config); } } }
26.75
81
0.598131
[ "MIT" ]
mauroservienti/microservices-done-right-demos
1-a-product/Sales.API/Startup.cs
965
C#
/* * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using FSO.Common; namespace FSO.LotView { /// <summary> /// Handles XNA content for the world. /// </summary> public class WorldContent { public static ContentManager ContentManager; public static void Init(GameServiceContainer serviceContainer, string rootDir) { ContentManager = new ContentManager(serviceContainer); ContentManager.RootDirectory = rootDir; } public static string EffectSuffix { get { return ((FSOEnvironment.SoftwareDepth)?"iOS":""); } } public static Effect _2DWorldBatchEffect { get{ return ContentManager.Load<Effect>("Effects/2DWorldBatch"+EffectSuffix); } } public static Effect GrassEffect { get { return ContentManager.Load<Effect>("Effects/GrassShader"+EffectSuffix); } } public static Texture2D GridTexture { get { return ContentManager.Load<Texture2D>("Textures/gridTexture"); } } } }
26
88
0.605769
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
francot514/FreeSims
SimsVille/World/WorldContent.cs
1,562
C#
using System; using System.Net.Http.Headers; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; using Coinbase.Exceptions; using Coinbase.Models; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Coinbase.Services { public class APIAuthenticationService: AuthenticationHandler<AuthenticationSchemeOptions> { private readonly IAuthenticationRepository _repository; public APIAuthenticationService(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IAuthenticationRepository repository) : base(options, logger, encoder, clock) { _repository = repository; } protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { //exclude anonymous endpoints from the authentication rule Endpoint endpoint = Context.GetEndpoint(); if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null) return AuthenticateResult.NoResult(); //implement the authentication code here if (!Request.Headers.ContainsKey("Authorization")) throw new UserErrorException("Authorization header missing!!!", 401); AuthenticationHeaderValue headers = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); string key = headers.Parameter; Authentication auth = await _repository.Authenticate(key); //replace the two variable value with the correct info from the api repository string nameIdentifierApiKey = auth.ApiKey; string userName = auth.UserName; //read more on claim //https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-6.0 /** * A claims-based identity is the set of claims. A claim is a statement that an entity * (a user or another application) makes about itself, it's just a claim. For example a * claim list can have the user’s name, user’s e-mail, user’s age, user's authorization for an action */ Claim[] claims = new[] { new Claim(ClaimTypes.NameIdentifier, nameIdentifierApiKey), new Claim(ClaimTypes.Name, userName) }; ClaimsIdentity identity = new ClaimsIdentity(claims, Scheme.Name); ClaimsPrincipal principal = new ClaimsPrincipal(identity); AuthenticationTicket ticket = new AuthenticationTicket(principal, Scheme.Name); return AuthenticateResult.Success(ticket); } protected override Task HandleChallengeAsync(AuthenticationProperties properties) { throw new UserErrorException("Unauthorized access", 401); } protected override Task HandleForbiddenAsync(AuthenticationProperties properties) { throw new UserErrorException("Forbidden access", 403); } } }
40.858824
115
0.631155
[ "MIT" ]
MAD-NTID/midterm---exam-kemoycampbell
Coinbase/Services/APIAuthenticationService.cs
3,481
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Requests a new activation code for a device configured at the System level. /// Returns a SuccessResponse or ErrorResponse. /// <see cref="SuccessResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:1037""}]")] public class SystemAccessDeviceGenerateActivationCodeRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest<BroadWorksConnector.Ocip.Models.C.SuccessResponse> { private string _deviceName; [XmlElement(ElementName = "deviceName", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:1037")] [MinLength(1)] [MaxLength(40)] public string DeviceName { get => _deviceName; set { DeviceNameSpecified = true; _deviceName = value; } } [XmlIgnore] protected bool DeviceNameSpecified { get; set; } } }
31.046512
162
0.649438
[ "MIT" ]
cwmiller/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemAccessDeviceGenerateActivationCodeRequest.cs
1,335
C#
// **************************************************************************** // <copyright file="MultiApplicationBarBehavior.cs" company="Pedro Lamas"> // Copyright © Pedro Lamas 2014 // </copyright> // **************************************************************************** // <author>Pedro Lamas</author> // <email>pedrolamas@gmail.com</email> // <project>Cimbalino.Toolkit</project> // <web>http://www.pedrolamas.com</web> // <license> // See license.txt in this solution or http://www.pedrolamas.com/license_MIT.txt // </license> // **************************************************************************** using System; using System.ComponentModel; using System.Windows; using System.Windows.Interactivity; using Microsoft.Phone.Controls; namespace Cimbalino.Toolkit.Behaviors { /// <summary> /// The behavior that creates a collection of bindable <see cref="Microsoft.Phone.Shell.ApplicationBar" /> controls. /// </summary> [System.Windows.Markup.ContentProperty("ApplicationBars")] public class MultiApplicationBarBehavior : Behavior<PhoneApplicationPage> { /// <summary> /// Initializes a new instance of the <see cref="MultiApplicationBarBehavior" /> class. /// </summary> public MultiApplicationBarBehavior() { ApplicationBars = new ApplicationBarCollection(); } /// <summary> /// Called after the behavior is attached to an AssociatedObject. /// </summary> /// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks> protected override void OnAttached() { AssociatedObject.LayoutUpdated += AssociatedObjectOnLayoutUpdated; base.OnAttached(); } /// <summary> /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred. /// </summary> /// <remarks> /// Override this to unhook functionality from the AssociatedObject. /// </remarks> protected override void OnDetaching() { AssociatedObject.LayoutUpdated -= AssociatedObjectOnLayoutUpdated; base.OnDetaching(); } /// <summary> /// Gets the <see cref="ApplicationBar"/> collection. /// </summary> /// <value>The <see cref="ApplicationBar"/> collection.</value> [Category("Common")] public ApplicationBarCollection ApplicationBars { get { return (ApplicationBarCollection)GetValue(ApplicationBarsProperty); } private set { SetValue(ApplicationBarsProperty, value); } } /// <summary> /// Identifier for the <see cref="ApplicationBars" /> dependency property. /// </summary> public static readonly DependencyProperty ApplicationBarsProperty = DependencyProperty.Register(nameof(ApplicationBars), typeof(ApplicationBarCollection), typeof(MultiApplicationBarBehavior), null); /// <summary> /// Gets or sets the index of the selected Application Bar. /// </summary> /// <value>the index of the selected Application Bar.</value> [Category("Common")] public int SelectedIndex { get { return (int)GetValue(SelectedIndexProperty); } set { SetValue(SelectedIndexProperty, value); } } /// <summary> /// Identifier for the <see cref="SelectedIndex" /> dependency property. /// </summary> public static readonly DependencyProperty SelectedIndexProperty = DependencyProperty.Register(nameof(SelectedIndex), typeof(int), typeof(MultiApplicationBarBehavior), new PropertyMetadata(-1, OnSelectedIndexChanged)); /// <summary> /// Called after the index of the selected Application Bar is changed. /// </summary> /// <param name="d">The <see cref="DependencyObject" />.</param> /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs" /> instance containing the event data.</param> private static void OnSelectedIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = (MultiApplicationBarBehavior)d; element.Update(); } /// <summary> /// Gets or sets a value indicating whether the Application Bar is visible. /// </summary> /// <value>true if the Application Bar is visible; otherwise, false.</value> [Category("Appearance")] public bool IsVisible { get { return (bool)GetValue(IsVisibleProperty); } set { SetValue(IsVisibleProperty, value); } } /// <summary> /// Identifier for the <see cref="IsVisible" /> dependency property. /// </summary> public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.Register(nameof(IsVisible), typeof(bool), typeof(MultiApplicationBarBehavior), new PropertyMetadata(true, OnIsVisibleChanged)); internal ApplicationBar SelectedItem { get { var selectedIndex = SelectedIndex; if (IsVisible && selectedIndex >= 0 && selectedIndex <= ApplicationBars.Count - 1) { return ApplicationBars[selectedIndex]; } else { return null; } } } /// <summary> /// Called after the visible state of the Application Bar is changed. /// </summary> /// <param name="d">The <see cref="DependencyObject" />.</param> /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs" /> instance containing the event data.</param> private static void OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var element = (MultiApplicationBarBehavior)d; element.Update(); } private void AssociatedObjectOnLayoutUpdated(object sender, EventArgs eventArgs) { AssociatedObject.LayoutUpdated -= AssociatedObjectOnLayoutUpdated; Update(); } private void Update() { if (DesignerProperties.IsInDesignTool || AssociatedObject == null) { return; } var applicationBar = SelectedItem; if (applicationBar == null) { AssociatedObject.ApplicationBar = null; } else { // The following is required to fix a compatibility issue with the Windows Phone Toolkit CustomMessageBox var internalApplicationBar = applicationBar.InternalApplicationBar; internalApplicationBar.IsVisible = applicationBar.IsVisible; AssociatedObject.ApplicationBar = internalApplicationBar; } } } }
38.288043
163
0.594322
[ "MIT" ]
Cimbalino/Cimbalino-Toolkit
src/Cimbalino.Toolkit (WP8)/Behaviors/MultiApplicationBarBehavior.cs
7,048
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17626 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Infrastructure.ExternalServices.ContosoInventoryService { [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ExternalServices.ContosoInventoryService.ContosoInventoryService")] public interface ContosoInventoryService { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ContosoInventoryService/InStock", ReplyAction="http://tempuri.org/ContosoInventoryService/InStockResponse")] bool InStock(int productId); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface ContosoInventoryServiceChannel : Infrastructure.ExternalServices.ContosoInventoryService.ContosoInventoryService, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class ContosoInventoryServiceClient : System.ServiceModel.ClientBase<Infrastructure.ExternalServices.ContosoInventoryService.ContosoInventoryService>, Infrastructure.ExternalServices.ContosoInventoryService.ContosoInventoryService { public ContosoInventoryServiceClient() { } public ContosoInventoryServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public ContosoInventoryServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ContosoInventoryServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ContosoInventoryServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public bool InStock(int productId) { return base.Channel.InStock(productId); } } }
49.5
252
0.67153
[ "MIT" ]
matthidinger/OnionArchitecture
src/Infrastructure/Service References/ExternalServices.ContosoInventoryService/Reference.cs
2,675
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Caching; using Foundatio.Extensions; using Foundatio.Logging; using Foundatio.Utility; using Nito.AsyncEx; namespace Foundatio.Metrics { public abstract class CacheBucketMetricsClientBase : IBufferedMetricsClient, IMetricsClientStats { private readonly ConcurrentQueue<MetricEntry> _queue = new ConcurrentQueue<MetricEntry>(); private readonly ConcurrentDictionary<string, AsyncManualResetEvent> _counterEvents = new ConcurrentDictionary<string, AsyncManualResetEvent>(); private readonly BucketSettings[] _buckets = { new BucketSettings { Size = TimeSpan.FromMinutes(5), Ttl = TimeSpan.FromHours(1) }, new BucketSettings { Size = TimeSpan.FromHours(1), Ttl = TimeSpan.FromDays(7) } }; private readonly string _prefix; private readonly Timer _flushTimer; private readonly bool _buffered; private readonly ICacheClient _cache; protected readonly ILogger _logger; public CacheBucketMetricsClientBase(ICacheClient cache, bool buffered = true, string prefix = null, ILoggerFactory loggerFactory = null) { _logger = loggerFactory.CreateLogger(GetType()); _cache = cache; _buffered = buffered; _prefix = !String.IsNullOrEmpty(prefix) ? (!prefix.EndsWith(":") ? prefix + ":" : prefix) : String.Empty; if (buffered) _flushTimer = new Timer(OnMetricsTimer, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); } public Task CounterAsync(string name, int value = 1) { _logger.Trace(() => $"Counter name={name} value={value} buffered={_buffered}"); var entry = new MetricEntry { Name = name, Type = MetricType.Counter, Counter = value }; if (!_buffered) return SubmitMetricAsync(entry); _queue.Enqueue(entry); return TaskHelper.Completed; } public Task GaugeAsync(string name, double value) { _logger.Trace(() => $"Gauge name={name} value={value} buffered={_buffered}"); var entry = new MetricEntry { Name = name, Type = MetricType.Gauge, Gauge = value }; if (!_buffered) return SubmitMetricAsync(entry); _queue.Enqueue(entry); return TaskHelper.Completed; } public Task TimerAsync(string name, int milliseconds) { _logger.Trace(() => $"Timer name={name} milliseconds={milliseconds} buffered={_buffered}"); var entry = new MetricEntry { Name = name, Type = MetricType.Timing, Timing = milliseconds }; if (!_buffered) return SubmitMetricAsync(entry); _queue.Enqueue(entry); return TaskHelper.Completed; } private void OnMetricsTimer(object state) { try { FlushAsync().GetAwaiter().GetResult(); } catch (Exception ex) { _logger.Error(ex, () => $"Error flushing metrics: {ex.Message}"); } } private bool _sendingMetrics = false; public async Task FlushAsync() { if (_sendingMetrics || _queue.IsEmpty) return; _logger.Trace("Flushing metrics: count={count}", _queue.Count); try { _sendingMetrics = true; var startTime = DateTime.UtcNow; var entries = new List<MetricEntry>(); MetricEntry entry; while (_queue.TryDequeue(out entry)) { entries.Add(entry); if (entry.EnqueuedDate > startTime) break; } if (entries.Count == 0) return; _logger.Trace("Dequeued {count} metrics", entries.Count); await SubmitMetricsAsync(entries).AnyContext(); } finally { _sendingMetrics = false; } } private Task SubmitMetricAsync(MetricEntry metric) { return SubmitMetricsAsync(new List<MetricEntry> { metric }); } private async Task SubmitMetricsAsync(List<MetricEntry> metrics) { foreach (var bucket in _buckets) { // counters var counters = metrics.Where(e => e.Type == MetricType.Counter) .GroupBy(e => new MetricKey(e.EnqueuedDate.Floor(bucket.Size), e.Name)) .Select(e => new { e.Key.Name, e.Key.Time, Count = e.Sum(c => c.Counter) }).ToList(); if (metrics.Count > 1) _logger.Trace(() => $"Aggregated {counters.Count} counters"); if (counters.Count > 0) await Run.WithRetriesAsync(() => Task.WhenAll(counters.Select(c => StoreCounterAsync(c.Name, c.Time, c.Count, bucket)))).AnyContext(); // gauges var gauges = metrics.Where(e => e.Type == MetricType.Gauge) .GroupBy(e => new MetricKey(e.EnqueuedDate.Floor(bucket.Size), e.Name)) .Select(e => new { e.Key.Name, Minute = e.Key.Time, Count = e.Count(), Total = e.Sum(c => c.Gauge), Last = e.Last().Gauge, Min = e.Min(c => c.Gauge), Max = e.Max(c => c.Gauge) }).ToList(); if (metrics.Count > 1) _logger.Trace(() => $"Aggregated {gauges.Count} gauges"); if (gauges.Count > 0) await Run.WithRetriesAsync(() => Task.WhenAll(gauges.Select(g => StoreGaugeAsync(g.Name, g.Minute, g.Count, g.Total, g.Last, g.Min, g.Max, bucket)))).AnyContext(); // timings var timings = metrics.Where(e => e.Type == MetricType.Timing) .GroupBy(e => new MetricKey(e.EnqueuedDate.Floor(bucket.Size), e.Name)) .Select(e => new { e.Key.Name, Minute = e.Key.Time, Count = e.Count(), Total = e.Sum(c => c.Timing), Min = e.Min(c => c.Timing), Max = e.Max(c => c.Timing) }).ToList(); if (metrics.Count > 1) _logger.Trace(() => $"Aggregated {timings.Count} timings"); if (timings.Count > 0) await Run.WithRetriesAsync(() => Task.WhenAll(timings.Select(t => StoreTimingAsync(t.Name, t.Minute, t.Count, t.Total, t.Max, t.Min, bucket)))).AnyContext(); } } private async Task StoreCounterAsync(string name, DateTime time, int value, BucketSettings settings) { _logger.Trace(() => $"Storing counter name={name} value={value} time={time}"); string key = GetBucketKey(MetricNames.Counter, name, time, settings.Size); await _cache.IncrementAsync(key, value, settings.Ttl).AnyContext(); AsyncManualResetEvent waitHandle; _counterEvents.TryGetValue(name, out waitHandle); waitHandle?.Set(); _logger.Trace(() => $"Done storing counter name={name}"); } private Task StoreGaugeAsync(string name, DateTime time, double value, BucketSettings settings) { return StoreGaugeAsync(name, time, 1, value, value, value, value, settings); } private async Task StoreGaugeAsync(string name, DateTime time, int count, double total, double last, double min, double max, BucketSettings settings) { _logger.Trace(() => $"Storing gauge name={name} count={count} total={total} last={last} min={min} max={max} time={time}"); string countKey = GetBucketKey(MetricNames.Timing, name, time, settings.Size, MetricNames.Count); await _cache.IncrementAsync(countKey, count, settings.Ttl).AnyContext(); string totalDurationKey = GetBucketKey(MetricNames.Timing, name, time, settings.Size, MetricNames.Total); await _cache.IncrementAsync(totalDurationKey, total, settings.Ttl).AnyContext(); string lastKey = GetBucketKey(MetricNames.Gauge, name, time, settings.Size, MetricNames.Last); await _cache.SetAsync(lastKey, last, settings.Ttl).AnyContext(); string minKey = GetBucketKey(MetricNames.Timing, name, time, settings.Size, MetricNames.Min); await _cache.SetIfLowerAsync(minKey, min, settings.Ttl).AnyContext(); string maxKey = GetBucketKey(MetricNames.Gauge, name, time, settings.Size, MetricNames.Max); await _cache.SetIfHigherAsync(maxKey, max, settings.Ttl).AnyContext(); _logger.Trace(() => $"Done storing gauge name={name}"); } private Task StoreTimingAsync(string name, DateTime time, int duration, BucketSettings settings) { return StoreTimingAsync(name, time, 1, duration, duration, duration, settings); } private async Task StoreTimingAsync(string name, DateTime time, int count, int totalDuration, int maxDuration, int minDuration, BucketSettings settings) { _logger.Trace(() => $"Storing timing name={name} count={count} total={totalDuration} min={minDuration} max={maxDuration} time={time}"); string countKey = GetBucketKey(MetricNames.Timing, name, time, settings.Size, MetricNames.Count); await _cache.IncrementAsync(countKey, count, settings.Ttl).AnyContext(); string totalDurationKey = GetBucketKey(MetricNames.Timing, name, time, settings.Size, MetricNames.Total); await _cache.IncrementAsync(totalDurationKey, totalDuration, settings.Ttl).AnyContext(); string maxKey = GetBucketKey(MetricNames.Timing, name, time, settings.Size, MetricNames.Max); await _cache.SetIfHigherAsync(maxKey, maxDuration, settings.Ttl).AnyContext(); string minKey = GetBucketKey(MetricNames.Timing, name, time, settings.Size, MetricNames.Min); await _cache.SetIfLowerAsync(minKey, minDuration, settings.Ttl).AnyContext(); _logger.Trace(() => $"Done storing timing name={name}"); } public Task<bool> WaitForCounterAsync(string statName, long count = 1, TimeSpan? timeout = null) { return WaitForCounterAsync(statName, () => TaskHelper.Completed, count, timeout.ToCancellationToken(TimeSpan.FromSeconds(10))); } public async Task<bool> WaitForCounterAsync(string statName, Func<Task> work, long count = 1, CancellationToken cancellationToken = default(CancellationToken)) { if (count <= 0) return true; DateTime start = DateTime.UtcNow; long startingCount = await this.GetCounterCountAsync(statName, start, start).AnyContext(); long expectedCount = startingCount + count; _logger.Trace("Wait: count={count} current={startingCount}", count, startingCount); if (work != null) await work().AnyContext(); long endingCount = await this.GetCounterCountAsync(statName, start, DateTime.UtcNow).AnyContext(); if (endingCount >= expectedCount) return true; // TODO: Should we update this to use monitors? long currentCount = 0; var resetEvent = _counterEvents.GetOrAdd(statName, s => new AsyncManualResetEvent(false)); do { try { await resetEvent.WaitAsync(cancellationToken).AnyContext(); } catch (OperationCanceledException) { } currentCount = await this.GetCounterCountAsync(statName, start, DateTime.UtcNow).AnyContext(); _logger.Trace("Got signal: count={currentCount} expected={expectedCount}", currentCount, expectedCount); resetEvent.Reset(); } while (cancellationToken.IsCancellationRequested == false && currentCount < expectedCount); currentCount = await this.GetCounterCountAsync(statName, start, DateTime.UtcNow).AnyContext(); _logger.Trace("Done waiting: count={currentCount} expected={expectedCount} success={isCancellationRequested}", currentCount, expectedCount, !cancellationToken.IsCancellationRequested); return !cancellationToken.IsCancellationRequested; } public async Task<CounterStatSummary> GetCounterStatsAsync(string name, DateTime? start = null, DateTime? end = null, int dataPoints = 20) { if (!start.HasValue) start = DateTime.UtcNow.AddHours(-4); if (!end.HasValue) end = DateTime.UtcNow; var interval = end.Value.Subtract(start.Value).TotalMinutes > 60 ? TimeSpan.FromHours(1) : TimeSpan.FromMinutes(5); var countBuckets = GetMetricBuckets(MetricNames.Counter, name, start.Value, end.Value, interval); var countResults = await _cache.GetAllAsync<int>(countBuckets.Select(k => k.Key)).AnyContext(); ICollection<CounterStat> stats = new List<CounterStat>(); for (int i = 0; i < countBuckets.Count; i++) { string countKey = countBuckets[i].Key; stats.Add(new CounterStat { Time = countBuckets[i].Time, Count = countResults[countKey].Value }); } stats = stats.ReduceTimeSeries(s => s.Time, (s, d) => new CounterStat { Time = d, Count = s.Sum(i => i.Count) }, dataPoints); return new CounterStatSummary(name, stats, start.Value, end.Value); } public async Task<GaugeStatSummary> GetGaugeStatsAsync(string name, DateTime? start = null, DateTime? end = null, int dataPoints = 20) { if (!start.HasValue) start = DateTime.UtcNow.AddHours(-4); if (!end.HasValue) end = DateTime.UtcNow; var interval = end.Value.Subtract(start.Value).TotalMinutes > 60 ? TimeSpan.FromHours(1) : TimeSpan.FromMinutes(5); var countBuckets = GetMetricBuckets(MetricNames.Gauge, name, start.Value, end.Value, interval, MetricNames.Count); var totalBuckets = GetMetricBuckets(MetricNames.Gauge, name, start.Value, end.Value, interval, MetricNames.Total); var lastBuckets = GetMetricBuckets(MetricNames.Gauge, name, start.Value, end.Value, interval, MetricNames.Last); var minBuckets = GetMetricBuckets(MetricNames.Gauge, name, start.Value, end.Value, interval, MetricNames.Min); var maxBuckets = GetMetricBuckets(MetricNames.Gauge, name, start.Value, end.Value, interval, MetricNames.Max); var countResults = await _cache.GetAllAsync<int>(countBuckets.Select(k => k.Key)).AnyContext(); var totalResults = await _cache.GetAllAsync<double>(totalBuckets.Select(k => k.Key)).AnyContext(); var lastResults = await _cache.GetAllAsync<double>(lastBuckets.Select(k => k.Key)).AnyContext(); var minResults = await _cache.GetAllAsync<double>(minBuckets.Select(k => k.Key)).AnyContext(); var maxResults = await _cache.GetAllAsync<double>(maxBuckets.Select(k => k.Key)).AnyContext(); ICollection<GaugeStat> stats = new List<GaugeStat>(); for (int i = 0; i < maxBuckets.Count; i++) { string countKey = countBuckets[i].Key; string totalKey = totalBuckets[i].Key; string minKey = minBuckets[i].Key; string maxKey = maxBuckets[i].Key; string lastKey = lastBuckets[i].Key; stats.Add(new GaugeStat { Time = maxBuckets[i].Time, Count = countResults[countKey].Value, Total = totalResults[totalKey].Value, Min = minResults[minKey].Value, Max = maxResults[maxKey].Value, Last = lastResults[lastKey].Value }); } stats = stats.ReduceTimeSeries(s => s.Time, (s, d) => new GaugeStat { Time = d, Count = s.Sum(i => i.Count), Total = s.Sum(i => i.Total), Min = s.Min(i => i.Min), Max = s.Max(i => i.Max), Last = s.Last().Last }, dataPoints); return new GaugeStatSummary(stats, start.Value, end.Value); } public async Task<TimingStatSummary> GetTimerStatsAsync(string name, DateTime? start = null, DateTime? end = null, int dataPoints = 20) { if (!start.HasValue) start = DateTime.UtcNow.AddHours(-4); if (!end.HasValue) end = DateTime.UtcNow; var interval = end.Value.Subtract(start.Value).TotalMinutes > 60 ? TimeSpan.FromHours(1) : TimeSpan.FromMinutes(5); var countBuckets = GetMetricBuckets(MetricNames.Timing, name, start.Value, end.Value, interval, MetricNames.Count); var durationBuckets = GetMetricBuckets(MetricNames.Timing, name, start.Value, end.Value, interval, MetricNames.Total); var minBuckets = GetMetricBuckets(MetricNames.Timing, name, start.Value, end.Value, interval, MetricNames.Min); var maxBuckets = GetMetricBuckets(MetricNames.Timing, name, start.Value, end.Value, interval, MetricNames.Max); var countResults = await _cache.GetAllAsync<int>(countBuckets.Select(k => k.Key)).AnyContext(); var durationResults = await _cache.GetAllAsync<int>(durationBuckets.Select(k => k.Key)).AnyContext(); var minResults = await _cache.GetAllAsync<int>(minBuckets.Select(k => k.Key)).AnyContext(); var maxResults = await _cache.GetAllAsync<int>(maxBuckets.Select(k => k.Key)).AnyContext(); ICollection<TimingStat> stats = new List<TimingStat>(); for (int i = 0; i < countBuckets.Count; i++) { string countKey = countBuckets[i].Key; string durationKey = durationBuckets[i].Key; string minKey = minBuckets[i].Key; string maxKey = maxBuckets[i].Key; stats.Add(new TimingStat { Time = countBuckets[i].Time, Count = countResults[countKey].Value, TotalDuration = durationResults[durationKey].Value, MinDuration = minResults[minKey].Value, MaxDuration = maxResults[maxKey].Value }); } stats = stats.ReduceTimeSeries(s => s.Time, (s, d) => new TimingStat { Time = d, Count = s.Sum(i => i.Count), MinDuration = s.Min(i => i.MinDuration), MaxDuration = s.Max(i => i.MaxDuration), TotalDuration = s.Sum(i => i.TotalDuration) }, dataPoints); return new TimingStatSummary(stats, start.Value, end.Value); } private string GetBucketKey(string metricType, string statName, DateTime? dateTime = null, TimeSpan? interval = null, string suffix = null) { if (interval == null) interval = _buckets[0].Size; if (dateTime == null) dateTime = DateTime.UtcNow; dateTime = dateTime.Value.Floor(interval.Value); suffix = !String.IsNullOrEmpty(suffix) ? ":" + suffix : String.Empty; return String.Concat(_prefix, "m:", metricType, ":", statName, ":", interval.Value.TotalMinutes, ":", dateTime.Value.ToString("yy-MM-dd-hh-mm"), suffix); } private List<MetricBucket> GetMetricBuckets(string metricType, string statName, DateTime start, DateTime end, TimeSpan? interval = null, string suffix = null) { if (interval == null) interval = _buckets[0].Size; start = start.Floor(interval.Value); end = end.Floor(interval.Value); DateTime current = start; var keys = new List<MetricBucket>(); while (current <= end) { keys.Add(new MetricBucket { Key = GetBucketKey(metricType, statName, current, interval, suffix), Time = current }); current = current.Add(interval.Value); } return keys; } public void Dispose() { _flushTimer?.Dispose(); FlushAsync().GetAwaiter().GetResult(); } private struct BucketSettings { public TimeSpan Size { get; set; } public TimeSpan Ttl { get; set; } } private class MetricEntry { public DateTime EnqueuedDate { get; } = DateTime.UtcNow; public string Name { get; set; } public MetricType Type { get; set; } public int Counter { get; set; } public double Gauge { get; set; } public int Timing { get; set; } } private enum MetricType { Counter, Gauge, Timing } private class MetricBucket { public string Key { get; set; } public DateTime Time { get; set; } } private class MetricNames { public const string Counter = "c"; public const string Gauge = "g"; public const string Timing = "t"; public const string Count = "cnt"; public const string Total = "tot"; public const string Max = "max"; public const string Min = "min"; public const string Last = "last"; } } }
49.080357
205
0.588139
[ "Apache-2.0" ]
trbenning/Foundatio
src/Core/Metrics/CacheBucketMetricsClientBase.cs
21,990
C#
using Hbms.Mes.IDAL; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Hbms.Mes.IBLL { public interface IBaseService<T> { IDbSession CurrentDbSession { get; } IBaseDal<T> CurrentDal { get; set; } T GetModel(Expression<Func<T, bool>> Where); IQueryable<T> GetModelList(Expression<Func<T, bool>> Where); IQueryable<T> GetModelListWithPaging<S>(out int TotalPage, int PageIndex, int PageSize, Expression<Func<T, bool>> Where, Expression<Func<T, S>> OrderBy, bool IsAsc); bool Insert(T Model); bool Update(T Model); bool Delete(T Model); } }
31.434783
173
0.684647
[ "Apache-2.0" ]
huangming771314520/Mes
Hbms.Mes.IBLL/IBaseService.cs
725
C#
using ColossalFramework.UI; using UnityEngine; namespace NoPillars { public static class UIUtil { public static void SetupTitle(string text, UIComponent parentPanel) { var title = parentPanel.AddUIComponent<UIPanel>(); title.size = new Vector2(parentPanel.width, 40); title.canFocus = true; title.isInteractive = true; title.relativePosition = Vector3.zero; var dragHandle = title.AddUIComponent<UIDragHandle>(); dragHandle.size = title.size; dragHandle.relativePosition = Vector3.zero; dragHandle.target = parentPanel; var windowName = dragHandle.AddUIComponent<UILabel>(); windowName.relativePosition = new Vector3(60, 13); windowName.text = text; } public static UIDropDown CreateDropDown(UIComponent parent) { UIDropDown dropDown = parent.AddUIComponent<UIDropDown>(); dropDown.size = new Vector2(90f, 30f); dropDown.listBackground = "GenericPanelLight"; dropDown.itemHeight = 30; dropDown.itemHover = "ListItemHover"; dropDown.itemHighlight = "ListItemHighlight"; dropDown.normalBgSprite = "ButtonMenu"; dropDown.disabledBgSprite = "ButtonMenuDisabled"; dropDown.hoveredBgSprite = "ButtonMenuHovered"; dropDown.focusedBgSprite = "ButtonMenu"; dropDown.listWidth = 90; dropDown.listHeight = 500; dropDown.foregroundSpriteMode = UIForegroundSpriteMode.Stretch; dropDown.popupColor = new Color32(45, 52, 61, 255); dropDown.popupTextColor = new Color32(170, 170, 170, 255); dropDown.zOrder = 1; dropDown.textScale = 0.8f; dropDown.verticalAlignment = UIVerticalAlignment.Middle; dropDown.horizontalAlignment = UIHorizontalAlignment.Left; dropDown.selectedIndex = 0; dropDown.textFieldPadding = new RectOffset(8, 0, 8, 0); dropDown.itemPadding = new RectOffset(14, 0, 8, 0); UIButton button = dropDown.AddUIComponent<UIButton>(); dropDown.triggerButton = button; button.text = ""; button.size = dropDown.size; button.relativePosition = new Vector3(0f, 0f); button.textVerticalAlignment = UIVerticalAlignment.Middle; button.textHorizontalAlignment = UIHorizontalAlignment.Left; button.normalFgSprite = "IconDownArrow"; button.hoveredFgSprite = "IconDownArrowHovered"; button.pressedFgSprite = "IconDownArrowPressed"; button.focusedFgSprite = "IconDownArrowFocused"; button.disabledFgSprite = "IconDownArrowDisabled"; button.foregroundSpriteMode = UIForegroundSpriteMode.Fill; button.horizontalAlignment = UIHorizontalAlignment.Right; button.verticalAlignment = UIVerticalAlignment.Middle; button.zOrder = 0; button.textScale = 0.8f; dropDown.eventSizeChanged += new PropertyChangedEventHandler<Vector2>((c, t) => { button.size = t; dropDown.listWidth = (int)t.x; }); return dropDown; } } }
43.272727
91
0.622449
[ "MIT" ]
bloodypenguin/Skylines-NoPillars
NoPillars/UIUtil.cs
3,334
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the firehose-2015-08-04.normal.json service model. */ using System; using System.Collections.Generic; using Amazon.Runtime; using Amazon.KinesisFirehose.Model; namespace Amazon.KinesisFirehose { /// <summary> /// Interface for accessing KinesisFirehose /// /// Amazon Kinesis Data Firehose API Reference /// <para> /// Amazon Kinesis Data Firehose is a fully managed service that delivers real-time streaming /// data to destinations such as Amazon Simple Storage Service (Amazon S3), Amazon Elasticsearch /// Service (Amazon ES), Amazon Redshift, and Splunk. /// </para> /// </summary> public partial interface IAmazonKinesisFirehose : IAmazonService, IDisposable { #region CreateDeliveryStream /// <summary> /// Initiates the asynchronous execution of the CreateDeliveryStream operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDeliveryStream operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/CreateDeliveryStream">REST API Reference for CreateDeliveryStream Operation</seealso> void CreateDeliveryStreamAsync(CreateDeliveryStreamRequest request, AmazonServiceCallback<CreateDeliveryStreamRequest, CreateDeliveryStreamResponse> callback, AsyncOptions options = null); #endregion #region DeleteDeliveryStream /// <summary> /// Deletes a delivery stream and its data. /// /// /// <para> /// You can delete a delivery stream only if it is in <code>ACTIVE</code> or <code>DELETING</code> /// state, and not in the <code>CREATING</code> state. While the deletion request is in /// process, the delivery stream is in the <code>DELETING</code> state. /// </para> /// /// <para> /// To check the state of a delivery stream, use <a>DescribeDeliveryStream</a>. /// </para> /// /// <para> /// While the delivery stream is <code>DELETING</code> state, the service might continue /// to accept the records, but it doesn't make any guarantees with respect to delivering /// the data. Therefore, as a best practice, you should first stop any applications that /// are sending records before deleting a delivery stream. /// </para> /// </summary> /// <param name="deliveryStreamName">The name of the delivery stream.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options"> /// A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property. /// </param> /// /// <returns>The response from the DeleteDeliveryStream service method, as returned by KinesisFirehose.</returns> /// <exception cref="Amazon.KinesisFirehose.Model.ResourceInUseException"> /// The resource is already in use and not available for this operation. /// </exception> /// <exception cref="Amazon.KinesisFirehose.Model.ResourceNotFoundException"> /// The specified resource could not be found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/DeleteDeliveryStream">REST API Reference for DeleteDeliveryStream Operation</seealso> void DeleteDeliveryStreamAsync(string deliveryStreamName, AmazonServiceCallback<DeleteDeliveryStreamRequest, DeleteDeliveryStreamResponse> callback, AsyncOptions options = null); /// <summary> /// Initiates the asynchronous execution of the DeleteDeliveryStream operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDeliveryStream operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/DeleteDeliveryStream">REST API Reference for DeleteDeliveryStream Operation</seealso> void DeleteDeliveryStreamAsync(DeleteDeliveryStreamRequest request, AmazonServiceCallback<DeleteDeliveryStreamRequest, DeleteDeliveryStreamResponse> callback, AsyncOptions options = null); #endregion #region DescribeDeliveryStream /// <summary> /// Initiates the asynchronous execution of the DescribeDeliveryStream operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryStream operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/DescribeDeliveryStream">REST API Reference for DescribeDeliveryStream Operation</seealso> void DescribeDeliveryStreamAsync(DescribeDeliveryStreamRequest request, AmazonServiceCallback<DescribeDeliveryStreamRequest, DescribeDeliveryStreamResponse> callback, AsyncOptions options = null); #endregion #region ListDeliveryStreams /// <summary> /// Initiates the asynchronous execution of the ListDeliveryStreams operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDeliveryStreams operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/ListDeliveryStreams">REST API Reference for ListDeliveryStreams Operation</seealso> void ListDeliveryStreamsAsync(ListDeliveryStreamsRequest request, AmazonServiceCallback<ListDeliveryStreamsRequest, ListDeliveryStreamsResponse> callback, AsyncOptions options = null); #endregion #region ListTagsForDeliveryStream /// <summary> /// Initiates the asynchronous execution of the ListTagsForDeliveryStream operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTagsForDeliveryStream operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/ListTagsForDeliveryStream">REST API Reference for ListTagsForDeliveryStream Operation</seealso> void ListTagsForDeliveryStreamAsync(ListTagsForDeliveryStreamRequest request, AmazonServiceCallback<ListTagsForDeliveryStreamRequest, ListTagsForDeliveryStreamResponse> callback, AsyncOptions options = null); #endregion #region PutRecord /// <summary> /// Writes a single data record into an Amazon Kinesis Data Firehose delivery stream. /// To write multiple data records into a delivery stream, use <a>PutRecordBatch</a>. /// Applications using these operations are referred to as producers. /// /// /// <para> /// By default, each delivery stream can take in up to 2,000 transactions per second, /// 5,000 records per second, or 5 MB per second. If you use <a>PutRecord</a> and <a>PutRecordBatch</a>, /// the limits are an aggregate across these two operations for each delivery stream. /// For more information about limits and how to request an increase, see <a href="https://docs.aws.amazon.com/firehose/latest/dev/limits.html">Amazon /// Kinesis Data Firehose Limits</a>. /// </para> /// /// <para> /// You must specify the name of the delivery stream and the data record when using <a>PutRecord</a>. /// The data record consists of a data blob that can be up to 1,000 KB in size, and any /// kind of data. For example, it can be a segment from a log file, geographic location /// data, website clickstream data, and so on. /// </para> /// /// <para> /// Kinesis Data Firehose buffers records before delivering them to the destination. To /// disambiguate the data blobs at the destination, a common solution is to use delimiters /// in the data, such as a newline (<code>\n</code>) or some other character unique within /// the data. This allows the consumer application to parse individual data items when /// reading the data from the destination. /// </para> /// /// <para> /// The <code>PutRecord</code> operation returns a <code>RecordId</code>, which is a unique /// string assigned to each record. Producer applications can use this ID for purposes /// such as auditability and investigation. /// </para> /// /// <para> /// If the <code>PutRecord</code> operation throws a <code>ServiceUnavailableException</code>, /// back off and retry. If the exception persists, it is possible that the throughput /// limits have been exceeded for the delivery stream. /// </para> /// /// <para> /// Data records sent to Kinesis Data Firehose are stored for 24 hours from the time they /// are added to a delivery stream as it tries to send the records to the destination. /// If the destination is unreachable for more than 24 hours, the data is no longer available. /// </para> /// <important> /// <para> /// Don't concatenate two or more base64 strings to form the data fields of your records. /// Instead, concatenate the raw data, then perform base64 encoding. /// </para> /// </important> /// </summary> /// <param name="deliveryStreamName">The name of the delivery stream.</param> /// <param name="record">The record.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options"> /// A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property. /// </param> /// /// <returns>The response from the PutRecord service method, as returned by KinesisFirehose.</returns> /// <exception cref="Amazon.KinesisFirehose.Model.InvalidArgumentException"> /// The specified input parameter has a value that is not valid. /// </exception> /// <exception cref="Amazon.KinesisFirehose.Model.ResourceNotFoundException"> /// The specified resource could not be found. /// </exception> /// <exception cref="Amazon.KinesisFirehose.Model.ServiceUnavailableException"> /// The service is unavailable. Back off and retry the operation. If you continue to see /// the exception, throughput limits for the delivery stream may have been exceeded. For /// more information about limits and how to request an increase, see <a href="https://docs.aws.amazon.com/firehose/latest/dev/limits.html">Amazon /// Kinesis Data Firehose Limits</a>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/PutRecord">REST API Reference for PutRecord Operation</seealso> void PutRecordAsync(string deliveryStreamName, Record record, AmazonServiceCallback<PutRecordRequest, PutRecordResponse> callback, AsyncOptions options = null); /// <summary> /// Initiates the asynchronous execution of the PutRecord operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutRecord operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/PutRecord">REST API Reference for PutRecord Operation</seealso> void PutRecordAsync(PutRecordRequest request, AmazonServiceCallback<PutRecordRequest, PutRecordResponse> callback, AsyncOptions options = null); #endregion #region PutRecordBatch /// <summary> /// Writes multiple data records into a delivery stream in a single call, which can achieve /// higher throughput per producer than when writing single records. To write single data /// records into a delivery stream, use <a>PutRecord</a>. Applications using these operations /// are referred to as producers. /// /// /// <para> /// By default, each delivery stream can take in up to 2,000 transactions per second, /// 5,000 records per second, or 5 MB per second. If you use <a>PutRecord</a> and <a>PutRecordBatch</a>, /// the limits are an aggregate across these two operations for each delivery stream. /// For more information about limits, see <a href="https://docs.aws.amazon.com/firehose/latest/dev/limits.html">Amazon /// Kinesis Data Firehose Limits</a>. /// </para> /// /// <para> /// Each <a>PutRecordBatch</a> request supports up to 500 records. Each record in the /// request can be as large as 1,000 KB (before 64-bit encoding), up to a limit of 4 MB /// for the entire request. These limits cannot be changed. /// </para> /// /// <para> /// You must specify the name of the delivery stream and the data record when using <a>PutRecord</a>. /// The data record consists of a data blob that can be up to 1,000 KB in size, and any /// kind of data. For example, it could be a segment from a log file, geographic location /// data, website clickstream data, and so on. /// </para> /// /// <para> /// Kinesis Data Firehose buffers records before delivering them to the destination. To /// disambiguate the data blobs at the destination, a common solution is to use delimiters /// in the data, such as a newline (<code>\n</code>) or some other character unique within /// the data. This allows the consumer application to parse individual data items when /// reading the data from the destination. /// </para> /// /// <para> /// The <a>PutRecordBatch</a> response includes a count of failed records, <code>FailedPutCount</code>, /// and an array of responses, <code>RequestResponses</code>. Even if the <a>PutRecordBatch</a> /// call succeeds, the value of <code>FailedPutCount</code> may be greater than 0, indicating /// that there are records for which the operation didn't succeed. Each entry in the <code>RequestResponses</code> /// array provides additional information about the processed record. It directly correlates /// with a record in the request array using the same ordering, from the top to the bottom. /// The response array always includes the same number of records as the request array. /// <code>RequestResponses</code> includes both successfully and unsuccessfully processed /// records. Kinesis Data Firehose tries to process all records in each <a>PutRecordBatch</a> /// request. A single record failure does not stop the processing of subsequent records. /// /// </para> /// /// <para> /// A successfully processed record includes a <code>RecordId</code> value, which is unique /// for the record. An unsuccessfully processed record includes <code>ErrorCode</code> /// and <code>ErrorMessage</code> values. <code>ErrorCode</code> reflects the type of /// error, and is one of the following values: <code>ServiceUnavailableException</code> /// or <code>InternalFailure</code>. <code>ErrorMessage</code> provides more detailed /// information about the error. /// </para> /// /// <para> /// If there is an internal server error or a timeout, the write might have completed /// or it might have failed. If <code>FailedPutCount</code> is greater than 0, retry the /// request, resending only those records that might have failed processing. This minimizes /// the possible duplicate records and also reduces the total bytes sent (and corresponding /// charges). We recommend that you handle any duplicates at the destination. /// </para> /// /// <para> /// If <a>PutRecordBatch</a> throws <code>ServiceUnavailableException</code>, back off /// and retry. If the exception persists, it is possible that the throughput limits have /// been exceeded for the delivery stream. /// </para> /// /// <para> /// Data records sent to Kinesis Data Firehose are stored for 24 hours from the time they /// are added to a delivery stream as it attempts to send the records to the destination. /// If the destination is unreachable for more than 24 hours, the data is no longer available. /// </para> /// <important> /// <para> /// Don't concatenate two or more base64 strings to form the data fields of your records. /// Instead, concatenate the raw data, then perform base64 encoding. /// </para> /// </important> /// </summary> /// <param name="deliveryStreamName">The name of the delivery stream.</param> /// <param name="records">One or more records.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options"> /// A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property. /// </param> /// /// <returns>The response from the PutRecordBatch service method, as returned by KinesisFirehose.</returns> /// <exception cref="Amazon.KinesisFirehose.Model.InvalidArgumentException"> /// The specified input parameter has a value that is not valid. /// </exception> /// <exception cref="Amazon.KinesisFirehose.Model.ResourceNotFoundException"> /// The specified resource could not be found. /// </exception> /// <exception cref="Amazon.KinesisFirehose.Model.ServiceUnavailableException"> /// The service is unavailable. Back off and retry the operation. If you continue to see /// the exception, throughput limits for the delivery stream may have been exceeded. For /// more information about limits and how to request an increase, see <a href="https://docs.aws.amazon.com/firehose/latest/dev/limits.html">Amazon /// Kinesis Data Firehose Limits</a>. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/PutRecordBatch">REST API Reference for PutRecordBatch Operation</seealso> void PutRecordBatchAsync(string deliveryStreamName, List<Record> records, AmazonServiceCallback<PutRecordBatchRequest, PutRecordBatchResponse> callback, AsyncOptions options = null); /// <summary> /// Initiates the asynchronous execution of the PutRecordBatch operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutRecordBatch operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/PutRecordBatch">REST API Reference for PutRecordBatch Operation</seealso> void PutRecordBatchAsync(PutRecordBatchRequest request, AmazonServiceCallback<PutRecordBatchRequest, PutRecordBatchResponse> callback, AsyncOptions options = null); #endregion #region StartDeliveryStreamEncryption /// <summary> /// Initiates the asynchronous execution of the StartDeliveryStreamEncryption operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartDeliveryStreamEncryption operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/StartDeliveryStreamEncryption">REST API Reference for StartDeliveryStreamEncryption Operation</seealso> void StartDeliveryStreamEncryptionAsync(StartDeliveryStreamEncryptionRequest request, AmazonServiceCallback<StartDeliveryStreamEncryptionRequest, StartDeliveryStreamEncryptionResponse> callback, AsyncOptions options = null); #endregion #region StopDeliveryStreamEncryption /// <summary> /// Initiates the asynchronous execution of the StopDeliveryStreamEncryption operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopDeliveryStreamEncryption operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/StopDeliveryStreamEncryption">REST API Reference for StopDeliveryStreamEncryption Operation</seealso> void StopDeliveryStreamEncryptionAsync(StopDeliveryStreamEncryptionRequest request, AmazonServiceCallback<StopDeliveryStreamEncryptionRequest, StopDeliveryStreamEncryptionResponse> callback, AsyncOptions options = null); #endregion #region TagDeliveryStream /// <summary> /// Initiates the asynchronous execution of the TagDeliveryStream operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TagDeliveryStream operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/TagDeliveryStream">REST API Reference for TagDeliveryStream Operation</seealso> void TagDeliveryStreamAsync(TagDeliveryStreamRequest request, AmazonServiceCallback<TagDeliveryStreamRequest, TagDeliveryStreamResponse> callback, AsyncOptions options = null); #endregion #region UntagDeliveryStream /// <summary> /// Initiates the asynchronous execution of the UntagDeliveryStream operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UntagDeliveryStream operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/UntagDeliveryStream">REST API Reference for UntagDeliveryStream Operation</seealso> void UntagDeliveryStreamAsync(UntagDeliveryStreamRequest request, AmazonServiceCallback<UntagDeliveryStreamRequest, UntagDeliveryStreamResponse> callback, AsyncOptions options = null); #endregion #region UpdateDestination /// <summary> /// Initiates the asynchronous execution of the UpdateDestination operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateDestination operation on AmazonKinesisFirehoseClient.</param> /// <param name="callback">An Action delegate that is invoked when the operation completes.</param> /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/UpdateDestination">REST API Reference for UpdateDestination Operation</seealso> void UpdateDestinationAsync(UpdateDestinationRequest request, AmazonServiceCallback<UpdateDestinationRequest, UpdateDestinationResponse> callback, AsyncOptions options = null); #endregion } }
60.384289
232
0.6812
[ "Apache-2.0" ]
TallyUpTeam/aws-sdk-net
sdk/src/Services/KinesisFirehose/Generated/_unity/IAmazonKinesisFirehose.cs
28,441
C#
 /* File Generated by NetTiers templates [www.nettiers.com] Important: Do not modify this file. Edit the file Nettiers.AdventureWorks.Entities.ContactCreditCard.cs instead. */ #region Using directives using System; using System.Data; using System.Collections; using System.Diagnostics; using System.Web.Services.Protocols; using Nettiers.AdventureWorks.Entities; using Nettiers.AdventureWorks.Data.Bases; #endregion namespace Nettiers.AdventureWorks.Data.WebServiceClient { ///<summary> /// This class is the webservice client implementation that exposes CRUD methods for Nettiers.AdventureWorks.Entities.ContactCreditCard objects. ///</summary> public abstract partial class WsContactCreditCardProviderBase : ContactCreditCardProviderBase { #region Declarations /// <summary> /// the Url of the webservice. /// </summary> private string url; #endregion Declarations #region Constructors /// <summary> /// Creates a new <see cref="WsContactCreditCardProviderBase"/> instance. /// Uses connection string to connect to datasource. /// </summary> public WsContactCreditCardProviderBase() { } /// <summary> /// Creates a new <see cref="WsContactCreditCardProviderBase"/> instance. /// Uses connection string to connect to datasource. /// </summary> /// <param name="url">The url to the nettiers webservice.</param> public WsContactCreditCardProviderBase(string url) { this.Url = url; } #endregion Constructors #region Url ///<summary> /// Current URL for webservice endpoint. ///</summary> public string Url { get {return url;} set {url = value;} } #endregion #region Convertion utility /// <summary> /// Convert a collection from the ws proxy to a nettiers collection. /// </summary> public static Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> Convert(WsProxy.ContactCreditCard[] items) { Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> outItems = new Nettiers.AdventureWorks.Entities.TList<ContactCreditCard>(); foreach(WsProxy.ContactCreditCard item in items) { outItems.Add(Convert(item)); } return outItems; } /// <summary> /// Convert a nettiers collection to the ws proxy collection. /// </summary> public static Nettiers.AdventureWorks.Entities.ContactCreditCard Convert(WsProxy.ContactCreditCard item) { Nettiers.AdventureWorks.Entities.ContactCreditCard outItem = item == null ? null : new Nettiers.AdventureWorks.Entities.ContactCreditCard(); Convert(outItem, item); return outItem; } /// <summary> /// Convert a nettiers collection to the ws proxy collection. /// </summary> public static Nettiers.AdventureWorks.Entities.ContactCreditCard Convert(Nettiers.AdventureWorks.Entities.ContactCreditCard outItem , WsProxy.ContactCreditCard item) { if (item != null && outItem != null) { outItem.ContactId = item.ContactId; outItem.CreditCardId = item.CreditCardId; outItem.ModifiedDate = item.ModifiedDate; outItem.OriginalContactId = item.ContactId; outItem.OriginalCreditCardId = item.CreditCardId; outItem.AcceptChanges(); } return outItem; } /// <summary> /// Convert a nettiers entity to the ws proxy entity. /// </summary> public static WsProxy.ContactCreditCard Convert(Nettiers.AdventureWorks.Entities.ContactCreditCard item) { WsProxy.ContactCreditCard outItem = new WsProxy.ContactCreditCard(); outItem.ContactId = item.ContactId; outItem.CreditCardId = item.CreditCardId; outItem.ModifiedDate = item.ModifiedDate; outItem.OriginalContactId = item.OriginalContactId; outItem.OriginalCreditCardId = item.OriginalCreditCardId; return outItem; } /// <summary> /// Convert a collection from to a nettiers collection to a the ws proxy collection. /// </summary> public static WsProxy.ContactCreditCard[] Convert(Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> items) { WsProxy.ContactCreditCard[] outItems = new WsProxy.ContactCreditCard[items.Count]; int count = 0; foreach (Nettiers.AdventureWorks.Entities.ContactCreditCard item in items) { outItems[count++] = Convert(item); } return outItems; } #endregion #region Get from Many To Many Relationship Functions #endregion #region Delete Methods /// <summary> /// Deletes a row from the DataSource. /// </summary> /// <param name="_contactId">Customer identification number. Foreign key to Contact.ContactID.. Primary Key.</param> /// <param name="_creditCardId">Credit card identification number. Foreign key to CreditCard.CreditCardID.. Primary Key.</param> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <remarks>Deletes based on primary key(s).</remarks> /// <returns>Returns true if operation suceeded.</returns> public override bool Delete(TransactionManager transactionManager, System.Int32 _contactId, System.Int32 _creditCardId) { try { // call the proxy WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; bool result = proxy.ContactCreditCardProvider_Delete(_contactId, _creditCardId); return result; } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } #endregion Delete Methods #region Find Methods /// <summary> /// Returns rows meeting the whereclause condition from the DataSource. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pagelen">Number of rows to return.</param> /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param> /// <param name="count">Number of rows in the DataSource.</param> /// <remarks>Operators must be capitalized (OR, AND)</remarks> /// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.ContactCreditCard objects.</returns> public override Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> Find(TransactionManager transactionManager, string whereClause, int start, int pagelen, out int count) { try { WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; WsProxy.ContactCreditCard[] items = proxy.ContactCreditCardProvider_Find(whereClause, start, pagelen, out count); return Convert(items); } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } #endregion Find Methods #region GetAll Methods /// <summary> /// Gets All rows from the DataSource. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.ContactCreditCard objects.</returns> public override Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> GetAll(TransactionManager transactionManager, int start, int pageLength, out int count) { try { WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; WsProxy.ContactCreditCard[] items = proxy.ContactCreditCardProvider_GetAll(start, pageLength, out count); return Convert(items); } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } #endregion GetAll Methods #region GetPaged Methods /// <summary> /// Gets a page of rows from the DataSource. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param> /// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="count">Number of rows in the DataSource.</param> /// <remarks></remarks> /// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.ContactCreditCard objects.</returns> public override Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> GetPaged(TransactionManager transactionManager, string whereClause, string orderBy, int start, int pageLength, out int count) { try { whereClause = whereClause ?? string.Empty; orderBy = orderBy ?? string.Empty; WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; WsProxy.ContactCreditCard[] items = proxy.ContactCreditCardProvider_GetPaged(whereClause, orderBy, start, pageLength, out count); // Create a collection and fill it with the dataset return Convert(items); } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } #endregion GetPaged Methods #region Get By Foreign Key Functions /// <summary> /// Gets rows from the datasource based on the FK_ContactCreditCard_Contact_ContactID key. /// FK_ContactCreditCard_Contact_ContactID Description: Foreign key constraint referencing Contact.ContactID. /// </summary> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_contactId">Customer identification number. Foreign key to Contact.ContactID.</param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.ContactCreditCard objects.</returns> public override Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> GetByContactId(TransactionManager transactionManager, System.Int32 _contactId, int start, int pageLength, out int count) { try { WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; WsProxy.ContactCreditCard[] items = proxy.ContactCreditCardProvider_GetByContactId(_contactId, start, pageLength, out count); return Convert(items); } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } /// <summary> /// Gets rows from the datasource based on the FK_ContactCreditCard_CreditCard_CreditCardID key. /// FK_ContactCreditCard_CreditCard_CreditCardID Description: Foreign key constraint referencing CreditCard.CreditCardID. /// </summary> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="_creditCardId">Credit card identification number. Foreign key to CreditCard.CreditCardID.</param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns a typed collection of Nettiers.AdventureWorks.Entities.ContactCreditCard objects.</returns> public override Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> GetByCreditCardId(TransactionManager transactionManager, System.Int32 _creditCardId, int start, int pageLength, out int count) { try { WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; WsProxy.ContactCreditCard[] items = proxy.ContactCreditCardProvider_GetByCreditCardId(_creditCardId, start, pageLength, out count); return Convert(items); } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } #endregion #region Get By Index Functions /// <summary> /// Gets rows from the datasource based on the PK_ContactCreditCard_ContactID_CreditCardID index. /// </summary> /// <param name="start">Row number at which to start reading.</param> /// <param name="pageLength">Number of rows to return.</param> /// <param name="_contactId">Customer identification number. Foreign key to Contact.ContactID.</param> /// <param name="_creditCardId">Credit card identification number. Foreign key to CreditCard.CreditCardID.</param> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="count">out parameter to get total records for query</param> /// <remarks></remarks> /// <returns>Returns an instance of the <see cref="Nettiers.AdventureWorks.Entities.ContactCreditCard"/> class.</returns> public override Nettiers.AdventureWorks.Entities.ContactCreditCard GetByContactIdCreditCardId(TransactionManager transactionManager, System.Int32 _contactId, System.Int32 _creditCardId, int start, int pageLength, out int count) { try { WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; WsProxy.ContactCreditCard items = proxy.ContactCreditCardProvider_GetByContactIdCreditCardId(_contactId, _creditCardId, start, pageLength, out count); return Convert(items); } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } #endregion Get By Index Functions #region Insert Methods /// <summary> /// Inserts a Nettiers.AdventureWorks.Entities.ContactCreditCard object into the datasource using a transaction. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="entity">Nettiers.AdventureWorks.Entities.ContactCreditCard object to insert.</param> /// <remarks></remarks> /// <returns>Returns true if operation is successful.</returns> public override bool Insert(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.ContactCreditCard entity) { WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; try { WsProxy.ContactCreditCard result = proxy.ContactCreditCardProvider_Insert(Convert(entity)); Convert(entity, result); return true; } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } /// <summary> /// Lets you efficiently bulk many entity to the database. /// </summary> /// <param name="transactionManager">NOTE: The transaction manager should be null for the web service client implementation.</param> /// <param name="entityList">The entities.</param> /// <remarks> /// After inserting into the datasource, the Nettiers.AdventureWorks.Entities.ContactCreditCard object will be updated /// to refelect any changes made by the datasource. (ie: identity or computed columns) /// </remarks> public override void BulkInsert(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.TList<ContactCreditCard> entityList) { WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; try { proxy.ContactCreditCardProvider_BulkInsert(Convert(entityList)); } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } #endregion Insert Methods #region Update Methods /// <summary> /// Update an existing row in the datasource. /// </summary> /// <param name="transactionManager"><see cref="TransactionManager"/> object</param> /// <param name="entity">Nettiers.AdventureWorks.Entities.ContactCreditCard object to update.</param> /// <remarks></remarks> /// <returns>Returns true if operation is successful.</returns> public override bool Update(TransactionManager transactionManager, Nettiers.AdventureWorks.Entities.ContactCreditCard entity) { WsProxy.AdventureWorksServices proxy = new WsProxy.AdventureWorksServices(); proxy.Url = Url; try { WsProxy.ContactCreditCard result = proxy.ContactCreditCardProvider_Update(Convert(entity)); Convert(entity, result); entity.AcceptChanges(); return true; } catch(SoapException soex) { System.Diagnostics.Debug.WriteLine(soex); throw soex; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw ex; } } #endregion Update Methods #region Custom Methods #endregion }//end class } // end namespace
35.452975
230
0.695956
[ "MIT" ]
aqua88hn/netTiers
Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Data.WebServiceClient/WsContactCreditCardProviderBase.generated.cs
18,473
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DicomDice.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DicomDice.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.453125
175
0.612729
[ "MIT" ]
modiCAS/DICOMDice
DicomDice/Properties/Resources.Designer.cs
2,783
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DataStructures { /// <summary> /// <para>This data structure represents a collection of disjoint sets and is optimized for adding /// singletons (expanding the collection of elements), taking the (destructive) union of two /// disjoint sets, and determining which set an element belongs to.</para> /// </summary> /// <typeparam name="T">The type of the elements.</typeparam> /// <remarks> /// <para>Note to self: This is the disjoint-set data structure covered in AD2 and CLRS /// representing each set as a tree and the entire collection of disjoint sets as a forest of /// trees. More specifically, this implementation uses the heuristics union by rank and path /// compression on FindSet.</para> /// <para>This implementation differs from that covered by CLRS in that the elements are not /// assumed to be integers 0 to n-1. Instead, this implementation allows elements of any type /// by using a hash table (actually, a <see cref="Dictionary"/>).</para> /// <para>The methods are named as in CLRS, which uses names not really fitting for C#.</para> /// </remarks> public class DisjointSets<T> { /// <summary> /// Maps an element to its corresponding node. /// </summary> private Dictionary<T, DisjointSetsNode<T>> dict = new Dictionary<T, DisjointSetsNode<T>>(); /// <summary> /// Gets the number of sets in the collection. /// </summary> public int NumberOfSets { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="DisjointSets{T}"/> class representing an /// empty collection of sets. /// </summary> public DisjointSets() : this(new HashSet<T>()) { } /// <summary> /// Initializes a new instance of the <see cref="DisjointSets{T}"/> class representing a /// collection of singletons. /// </summary> /// <param name="elements">The elements of the singletons.</param> /// <exception cref="ArgumentNullException"><paramref name="elements"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException">The enumerable contains duplicates.</exception> /// TODO: Call the sets constructor overload for consistency? public DisjointSets(IEnumerable<T> elements) { if (elements == null) { throw new ArgumentNullException(nameof(elements)); } NumberOfSets = 0; foreach (var element in elements) { try { MakeSet(element); } catch (ArgumentException ex) { throw new ArgumentException($"The enumerable contains more than one instance of {element}.", nameof(elements), ex); } } } public DisjointSets(IEnumerable<ISet<T>> sets) { if (sets == null) { throw new ArgumentNullException(nameof(sets)); } foreach (var set in sets) { if (set == null) throw new ArgumentException("The enumerable contains a null value.", nameof(sets)); try { MakeBigSet(set); } catch (ArgumentException ex) { throw new ArgumentException("The sets are not disjoint.", ex); } } } public DisjointSets(DisjointSets<T> otherDisjointSets) : this(otherDisjointSets?.GetSets() ?? throw new ArgumentNullException(nameof(otherDisjointSets))) { } /// <summary> /// Inserts a singleton into the collection of disjoint sets. /// </summary> /// <param name="x">The element of the singleton to insert.</param> /// <exception cref="ArgumentException"><paramref name="x"/> is already exists in the collection of disjoint sets.</exception> public void MakeSet(T x) { if (dict.ContainsKey(x)) { throw new ArgumentException($"The element {x} already exists in the collection of disjoint sets.", nameof(x)); } var node = new DisjointSetsNode<T>(x); dict[x] = node; NumberOfSets++; } /// <summary> /// Returns the representative from the unique set containing a given element. /// </summary> /// <param name="x">The element for whose set to find a representative.</param> /// <returns>The representative for the set containing <paramref name="x"/>.</returns> /// <remarks>The same representative is returned if the <see cref="DisjointSets{T}"/> /// collection is not modified between calls.</remarks> /// <exception cref="ArgumentException"><paramref name="x"/> does not exist in the collection of disjoint sets.</exception> public T FindSet(T x) { if (!dict.ContainsKey(x)) { throw new ArgumentException($"The element {x} does not exist in the collection of disjoint sets", nameof(x)); } return InternalFindSet(x).Element; } /// <summary> /// Returns the representative <em>node</em> from the unique set containing a given element. /// </summary> /// <param name="x"></param> /// <returns></returns> /// <remarks>This method assumes that <paramref name="x"/> is present in the collection of disjoint sets.</remarks> private DisjointSetsNode<T> InternalFindSet(T x) { var findPath = new List<DisjointSetsNode<T>>(); // For path compression var node = dict[x]; while (!node.IsRoot) { findPath.Add(node); node = node.Parent; } var root = node; foreach (var nonrootNode in findPath) { nonrootNode.Parent = root; } return root; } /// <summary> /// Unites two disjoint sets. /// </summary> /// <param name="x">An element of the first set.</param> /// <param name="y">An element of the second set.</param> /// <remarks>Performs path compression.</remarks> /// <exception cref="ArgumentException"><paramref name="x"/> or <paramref name="y"/> does /// not exist in the collection of disjoint sets, or <paramref name="x"/> and <paramref name="y"/> /// are members of the same set.</exception> public void Union(T x, T y) { if (!dict.ContainsKey(x)) { throw new ArgumentException($"The element {x} does not exist in the collection of disjoint sets", nameof(x)); } if (!dict.ContainsKey(y)) { throw new ArgumentException($"The element {y} does not exist in the collection of disjoint sets", nameof(y)); } var xNode = InternalFindSet(x); var yNode = InternalFindSet(y); if (xNode == yNode) { throw new ArgumentException($"The elements {x} and {y} belong to the same set."); } Link(xNode, yNode); NumberOfSets--; } /// <summary> /// Unites two disjoint sets given the root elements of the sets. /// </summary> /// <param name="xNode">The root of (the tree representing) the first set.</param> /// <param name="yNode">The root of (the tree representing) the second set.</param> /// <remarks><paramref name="xNode"/> and <paramref name="yNode"/> are assumed to /// correspond to elements of different sets.</remarks> private void Link(DisjointSetsNode<T> xNode, DisjointSetsNode<T> yNode) { DisjointSetsNode<T> parentNode, childNode; if (xNode.Rank > yNode.Rank) { childNode = yNode; parentNode = xNode; } else { childNode = xNode; parentNode = yNode; } childNode.Parent = parentNode; if (childNode.Rank == parentNode.Rank) { parentNode.Rank += 1; } // Swap nexts var tempNode = parentNode.Next; parentNode.Next = childNode.Next; childNode.Next = tempNode; } /// <summary> /// Returns the unique set containing a given element. /// </summary> /// <param name="x">The element whose set to return.</param> /// <returns>The set containing <paramref name="x"/>.</returns> /// <remarks>This is essentially the implementation of Print-Set in CLRS hinted to in exercise 21.3-4.</remarks> /// <exception cref="ArgumentException"><paramref name="x"/> does not exist in the collection of disjoint sets.</exception> public ISet<T> GetSet(T x) { if (!dict.ContainsKey(x)) { throw new ArgumentException($"The element {x} does not exist in the collection of disjoint sets", nameof(x)); } var startNode = dict[x]; var set = new HashSet<T>(); var node = startNode; do { set.Add(node.Element); } while ((node = node.Next) != startNode); return set; } /// <summary> /// Indicates whether any of the disjoint sets contain a specified element. /// </summary> /// <param name="x">The element whose existence to determine.</param> /// <returns><see langword="true"/> if <paramref name="x"/> is present; <see langword="false"/> otherwise.</returns> public bool Contains(T x) { return dict.ContainsKey(x); } /// <summary> /// Returns this collection of disjoint sets as a set of sets. /// </summary> /// <returns>This collection of disjoint sets as a set of sets.</returns> /// <remarks>This implementation is naïve.</remarks> public ISet<ISet<T>> GetSets() { var setOfSets = new HashSet<ISet<T>>(); foreach (var x in dict.Keys.Select(x => FindSet(x)).Distinct()) { var set = GetSet(x); setOfSets.Add(set); } return setOfSets; } public void MakeBigSet(IEnumerable<T> xs) { var enumerator = xs.GetEnumerator(); if (!enumerator.MoveNext()) return; var x0 = enumerator.Current; MakeSet(x0); while (enumerator.MoveNext()) { var x = enumerator.Current; MakeSet(x); Union(x, x0); } } public override string ToString() { var builder = new StringBuilder("{"); bool deleteTrailingComma = false; foreach (var set in GetSets()) { builder.Append("{"); builder.Append(String.Join(", ", set)); builder.Append("}, "); deleteTrailingComma = true; } if (deleteTrailingComma) builder.Length -= 2; builder.Append("}"); return builder.ToString(); } } }
38.327869
161
0.544739
[ "MIT" ]
Samuel-Q/DataStructures
DataStructures/DisjointSets.cs
11,693
C#
using DevelApp.JsonSchemaBuilder.JsonSchemaParts; using DevelApp.Utility.Model; namespace DevelApp.JsonSchemaBuilder { public class NoValidationJsonSchema : AbstractJsonSchema { public NoValidationJsonSchema() { } public override string Description { get { return "Represents an empty schema with disabled validation"; } } public override NamespaceString Module { get { return "Default"; } } protected override JSBSchema BuildJsonSchema() { return new JSBSchema(Name, Description); } } }
21.088235
77
0.548117
[ "MIT" ]
DevelApp-dk/JsonSchemaBuilder
JsonSchemaBuilder/NoValidationJsonSchema.cs
719
C#
using System.IO; namespace Ncodi.CodeAnalysis.Symbols { public abstract class Symbol { private protected Symbol(string name) { Name = name; } public abstract SymbolKind Kind { get; } public string Name { get; } public void WriteTo(TextWriter writer) { SymbolPrinter.WriteTo(this, writer); } public override string ToString() { using (var writer = new StringWriter()) { WriteTo(writer); return writer.ToString(); } } } }
19.935484
51
0.508091
[ "Apache-2.0" ]
AzizVirus/Ncodi
src/Ncodi/CodeAnalysis/Symbols/Symbol.cs
620
C#
using UnityEngine; namespace Asteroids { [AddComponentMenu("ASTEROIDS/Renderer Off Screen")] public class RendererOffScreen : RendererBehaviour { public override void OnBecameInvisible () { transform.gameObject.SetActive (false); transform.localPosition = Vector2.zero; transform.localRotation = Quaternion.identity; } } }
22.866667
52
0.763848
[ "MIT" ]
joaokucera/unity-asteroids
src/Assets/Asteroids/Scripts/Renderers/RendererOffScreen.cs
345
C#
using Phonebook.Models; using Phonebook.ViewModels; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Phonebook.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddContactPage : ContentPage { public AddContactPage(ObservableCollection<Contacts> contactsList) { InitializeComponent(); BindingContext = new AddContactViewModel(contactsList); } public AddContactPage(ObservableCollection<Contacts> contactsList, Contacts selected) { InitializeComponent(); BindingContext = new AddContactViewModel(contactsList, selected); } } }
24.9
87
0.800535
[ "MIT" ]
Betoso99/Address_Book
Phonebook/Phonebook/Views/AddContactPage.xaml.cs
749
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Abp.Modules; using Abp.Reflection.Extensions; using Blog_Test_Petros_Ohanyan.Configuration; namespace Blog_Test_Petros_Ohanyan.Web.Host.Startup { [DependsOn( typeof(Blog_Test_Petros_OhanyanWebCoreModule))] public class Blog_Test_Petros_OhanyanWebHostModule: AbpModule { private readonly IWebHostEnvironment _env; private readonly IConfigurationRoot _appConfiguration; public Blog_Test_Petros_OhanyanWebHostModule(IWebHostEnvironment env) { _env = env; _appConfiguration = env.GetAppConfiguration(); } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(Blog_Test_Petros_OhanyanWebHostModule).GetAssembly()); } } }
30.571429
113
0.733645
[ "MIT" ]
PetrosOhanyanCore/Blog_V1
src/Blog_Test_Petros_Ohanyan.Web.Host/Startup/Blog_Test_Petros_OhanyanWebHostModule.cs
858
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Obelisk.Agi.Bootstrappers.Structuremap")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Obelisk.Agi.Bootstrappers.Structuremap")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("511ed134-24da-45ce-87af-447be8a020a6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
39.162162
84
0.750173
[ "MIT" ]
troytowson/obeliskagi.bootstrappers.structuremap-csharp
src/Obelisk.Agi.Bootstrappers.Structuremap/Properties/AssemblyInfo.cs
1,452
C#
namespace Research.Data { /// <summary> /// Represents a generic attribute /// </summary> public partial class GenericAttribute : BaseEntity { /// <summary> /// Gets or sets the entity identifier /// </summary> public int EntityId { get; set; } /// <summary> /// Gets or sets the key group /// </summary> public string KeyGroup { get; set; } /// <summary> /// Gets or sets the key /// </summary> public string Key { get; set; } /// <summary> /// Gets or sets the value /// </summary> public string Value { get; set; } /// <summary> /// Gets or sets the store identifier /// </summary> public int StoreId { get; set; } } }
24.058824
54
0.492665
[ "MIT" ]
Sakchai/ResearchProject
Research.Data/Entity/GenericAttribute.cs
818
C#
/* * Copyright (c) Contributors, http://whitecore-sim.org/, http://aurora-sim.org, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the WhiteCore-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace WhiteCore.Framework.Services { /// <summary> /// This gets the HTTP based Map Service set up /// </summary> public interface IMapService { /// <summary> /// Get the URL to the HTTP based Map Service /// </summary> /// <returns></returns> string MapServiceURL { get; } /// <summary> /// Get the URL to the HTTP based Map Service API /// </summary> /// <returns></returns> string MapServiceAPIURL { get; } } }
47.851064
107
0.684749
[ "BSD-3-Clause" ]
WhiteCoreSim/WhiteCore-Dev
WhiteCore/Framework/Services/IMapService.cs
2,249
C#
using System; namespace SharpGlyph { public class Interpreter { public event Action<int> Debug; public bool IsDebug = false; public int ppem = 24; public InterpreterStack stack; public InterpreterFuncs funcs; public int[] storage; public CvtTable cvt; public GraphicsState state; public Point2D[] debugPoints; public Point2D[] origin; public Point2D[][] points; protected InterpreterStream stream; protected GetInfoResult getInfoResult; //protected MaxpTable maxp; public ushort maxStackElements; public ushort maxTwilightPoints; public ushort maxFunctionDefs; public static string Decode(byte[] data) { return InstructionsDecoder.Decode(data); } public Interpreter(Font font) { funcs = new InterpreterFuncs(); stack = new InterpreterStack(); stream = new InterpreterStream(); state = new GraphicsState(); getInfoResult = new GetInfoResult(); //points = new Point2D[2][]; if (font != null) { MaxpTable maxp = font.Tables.maxp; cvt = font.Tables.cvt; storage = new int[maxp.maxStorage]; maxStackElements = maxp.maxStackElements; maxTwilightPoints = maxp.maxTwilightPoints; maxFunctionDefs = maxp.maxFunctionDefs; } else { cvt = new CvtTable(); cvt.data = new int[64]; storage = new int[64]; maxStackElements = 1024; } #if DEBUG Console.WriteLine("maxStackElements: " + maxStackElements); Console.WriteLine("maxFunctionDefs: " + maxFunctionDefs); #endif } public Glyph Interpret(byte[] data, Glyph glyph = null, bool isCVT = false) { if (data == null || data.Length <= 0) { return glyph; } stream.Push(data); if (IsDebug == false) { stack.Init(maxStackElements); Array.Clear(storage, 0, storage.Length); } origin = null; points = new Point2D[2][]; if (IsDebug == false) { if (glyph != null) { glyph = glyph.Clone(); SimpleGlyph simpleGlyph = glyph.simpleGlyph; if (simpleGlyph != null) { short[] xCoordinates = simpleGlyph.xCoordinates; short[] yCoordinates = simpleGlyph.yCoordinates; int length = xCoordinates.Length; origin = new Point2D[length + 4]; points[0] = new Point2D[maxTwilightPoints]; points[1] = new Point2D[length + 4]; for (int i = 0; i < length; i++) { int x = xCoordinates[i]; int y = yCoordinates[i]; origin[i] = new Point2D(x, y); if (i < maxTwilightPoints) { points[0][i] = new Point2D(x, y); } points[1][i] = new Point2D(x, y); } for (int i = length; i < length + 4; i++) { origin[i] = new Point2D(0, 0); points[1][i] = new Point2D(0, 0); if (i < maxTwilightPoints) { points[0][i] = new Point2D(0, 0); } } } } else { //origin = new Point2D[4]; //points[0] = new Point2D[4]; //points[1] = new Point2D[4]; //* origin = new Point2D[4]; points[0] = new Point2D[maxTwilightPoints]; points[1] = new Point2D[4]; for (int i = 0; i < 4; i++) { origin[i] = new Point2D(0, 0); points[1][i] = new Point2D(0, 0); if (i < maxTwilightPoints) { points[0][i] = new Point2D(0, 0); } } //*/ } } else { if (debugPoints != null) { origin = new Point2D[debugPoints.Length]; points[0] = new Point2D[debugPoints.Length]; points[1] = new Point2D[debugPoints.Length]; for (int i = 0; i < debugPoints.Length; i++) { Point2D p = debugPoints[i]; origin[i] = p.Clone(); points[0][i] = p.Clone(); points[1][i] = p.Clone(); } } } while (true) { if (stream.HasNext() == false) { stream.Pop(); if (stream.Depth <= 0) { break; } //continue; } byte opcode = stream.Next(); //if (glyph != null) { // Console.WriteLine("{0:X}", opcode); //} switch (opcode) { //----------------------------------------- // Pushing data onto the interpreter stack // case 0x40: // NPUSHB[ ] (PUSH N Bytes) { int n = stream.Next(); stack.PushBytes(stream, n); } break; case 0x41: // NPUSHW[ ] (PUSH N Words) { int n = stream.Next(); stack.PushWords(stream, n); } break; case 0xB0: // PUSHB[abc] (PUSH Bytes) stack.Push(stream.Next()); break; case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: stack.PushBytes(stream, (opcode & 7) + 1); break; case 0xB8: // PUSHW[abc] (PUSH Words) stack.Push(stream.NextWord()); break; case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: stack.PushWords(stream, (opcode & 7) + 1); break; //----------------------------------------- // Managing the Storage Area // case 0x43: // RS[ ] (Read Store) { int n = stack.Pop(); stack.Push(storage[n]); } break; case 0x42: // WS[ ] (Write Store) { int v = stack.Pop(); int l = stack.Pop(); storage[l] = v; } break; //----------------------------------------- // Managing the Control Value Table // case 0x44: // WCVTP[ ] (Write Control Value Table in Pixel units) { int v = stack.Pop(); int l = stack.Pop(); cvt.data[l] = v; } break; case 0x70: // WCVTF[ ] (Write Control Value Table in FUnits) { int n = stack.Pop(); int l = stack.Pop(); cvt.data[l] = n / 64; } break; case 0x45: // RCVT[ ] (Read Control Value Table) { int location = stack.Pop(); stack.Push(cvt.data[location]); } break; //----------------------------------------- // Managing the Graphics State // case 0x00: // SVTCA[a] (Set freedom and projection Vectors To Coordinate Axis) state.projection_vector = GraphicsState.YAxis; state.freedom_vector = GraphicsState.YAxis; break; case 0x01: // SVTCA[a] state.projection_vector = 0; state.freedom_vector = 0; break; case 0x02: // SPVTCA[a] (Set Projection_Vector To Coordinate Axis) state.projection_vector = GraphicsState.YAxis; break; case 0x03: // SPVTCA[a] state.projection_vector = 0; break; case 0x04: // SFVTCA[a] (Set Freedom_Vector to Coordinate Axis) state.freedom_vector = GraphicsState.YAxis; break; case 0x05: // SFVTCA[a] state.freedom_vector = 0; break; case 0x06: // SPVTL[a] (Set Projection_Vector To Line) { int p1 = stack.Pop(); int p2 = stack.Pop(); state.SetProjectionVector( points[state.zp2][p1], points[state.zp1][p2] ); } break; case 0x07: // SPVTL[a] { int p1 = stack.Pop(); int p2 = stack.Pop(); state.SetProjectionVectorY( points[state.zp2][p1], points[state.zp1][p2] ); } break; case 0x08: // SFVTL[a] (Set Freedom_Vector To Line) { int p1 = stack.Pop(); int p2 = stack.Pop(); state.SetFreedomVector( points[state.zp2][p1], points[state.zp1][p2] ); } break; case 0x09: // SFVTL[a] { int p1 = stack.Pop(); int p2 = stack.Pop(); state.SetFreedomVectorY( points[state.zp2][p1], points[state.zp1][p2] ); } break; case 0x0E: // SFVTPV[ ] (Set Freedom_Vector To Projection Vector) state.freedom_vector = state.projection_vector; break; case 0x86: // SDPVTL[a] (Set Dual Projection_Vector To Line) { int p1 = stack.Pop(); int p2 = stack.Pop(); state.SetProjectionVector( points[state.zp2][p1], points[state.zp1][p2] ); state.SetDualProjectionVectors( origin[p1], origin[p2] ); } break; case 0x87: // SDPVTL[a] { int p1 = stack.Pop(); int p2 = stack.Pop(); state.SetProjectionVectorY( points[state.zp2][p1], points[state.zp1][p2] ); state.SetDualProjectionVectorsY( origin[p1], origin[p2] ); } break; case 0x0A: // SPVFS[ ] (Set Projection_Vector From Stack) state.projection_vector = stack.PopVector(); break; case 0x0B: // SFVFS[ ] (Set Freedom_Vector From Stack) state.freedom_vector = stack.PopVector(); break; case 0x0C: // GPV[ ] (Get Projection_Vector) stack.PushVector(state.projection_vector); break; case 0x0D: // GFV[ ] (Get Freedom_Vector) stack.PushVector(state.freedom_vector); break; case 0x10: // SRP0[ ] (Set Reference Point 0) state.rp0 = stack.Pop(); break; case 0x11: // SRP1[ ] (Set Reference Point 1) state.rp1 = stack.Pop(); break; case 0x12: // SRP2[ ] (Set Reference Point 2) state.rp2 = stack.Pop(); break; case 0x13: // SZP0[ ] (Set Zone Pointer 0) state.zp0 = stack.Pop(); break; case 0x14: // SZP1[ ] (Set Zone Pointer 1) state.zp1 = stack.Pop(); break; case 0x15: // SZP2[ ] (Set Zone Pointer 2) state.zp2 = stack.Pop(); break; case 0x16: // SZPS[ ] (Set Zone PointerS) state.zp0 = state.zp1 = state.zp2 = stack.Pop(); break; case 0x19: // RTHG[ ] (Round To Half Grid) state.round_state = RoundState.HalfGrid; break; case 0x18: // RTG[ ] (Round To Grid) state.round_state = RoundState.Grid; break; case 0x3D: // RTDG[ ] (Round To Double Grid) state.round_state = RoundState.DoubleGrid; break; case 0x7D: // RDTG[ ] (Round Down To Grid) state.round_state = RoundState.DownToGrid; break; case 0x7C: // RUTG[ ] (Round Up To Grid) state.round_state = RoundState.UpToGrid; break; case 0x7A: // ROFF[ ] (Round OFF) state.round_state = RoundState.Off; break; case 0x76: // SROUND[ ] (Super ROUND) stack.Pop(); break; case 0x77: // S45ROUND[ ] (Super ROUND 45 degrees) stack.Pop(); break; case 0x17: // SLOOP[ ] (Set LOOP variable) state.loop = stack.Pop(); break; case 0x1A: // SMD[ ] (Set Minimum_Distance) state.minimum_distance = stack.Pop(); break; case 0x8E: // INSTCTRL (INSTRuction execution ConTRoL) { int s = stack.Pop(); int value = stack.Pop(); if (isCVT) { } } break; case 0x85: // SCANCTRL[ ] (SCAN conversion ConTRoL) { int n = stack.Pop(); } break; case 0x8D: // SCANTYPE[ ] (SCANTYPE) { int n = stack.Pop(); } break; case 0x1D: // SCVTCI[ ] (Set Control Value Table Cut In) state.control_value_cut_in = stack.Pop(); break; case 0x1E: // SSWCI[ ] (Set Single_Width_Cut_In) state.singe_width_cut_in = stack.Pop(); break; case 0x1F: // SSW[ ] (Set Single-width) state.single_width_value = stack.Pop(); break; case 0x4D: // FLIPON[ ] (Set the auto_flip Boolean to ON) state.auto_flip = true; break; case 0x4E: // FLIPOFF[ ] (Set the auto_flip Boolean to OFF) state.auto_flip = false; break; case 0x7E: // SANGW[ ] (Set Angle_Weight) stack.Pop(); break; case 0x5E: // SDB[ ] (Set Delta_Base in the graphics state) state.delta_base = stack.Pop(); break; case 0x5F: // SDS[ ] (Set Delta_Shift in the graphics state) state.delta_shift = stack.Pop(); break; //----------------------------------------- // Reading and writing data // case 0x46: // GC[a] (Get Coordinate projected onto the projection_vector) { int p = stack.Pop(); //if (p >= points[state.zp2].Length) { // break; //} stack.Push( GC( points[state.zp2][p], state.projection_vector ) ); } break; case 0x47: // GC[a] stack.Push( GC( origin[stack.Pop()], state.projection_vector ) ); break; case 0x48: // SCFS[ ] (Sets Coordinate From the Stack using projection_vector and freedom_vector) { int value = stack.Pop(); int p = stack.Pop(); //if (p < 0 || p >= points[state.zp2].Length) { // break; //} SCFS( points[state.zp2][p], value, state.freedom_vector, state.projection_vector ); } break; // MD[a](Measure Distance) case 0x49: case 0x4A: { int p1 = stack.Pop(); int p2 = stack.Pop(); /* if (p1 >= points[state.zp1].Length) { break; } if (p2 >= points[state.zp0].Length) { break; } */ stack.Push( MD( points[state.zp1][p1], points[state.zp0][p2], (opcode & 1) > 0, state ) ); } break; case 0x4B: // MPPEM[ ] (Measure Pixels Per EM) stack.Push( MPPEM(state.projection_vector) ); break; case 0x4C: // MPS[ ] (Measure Point Size) stack.Push( MPS() ); break; //----------------------------------------- // Managing outlines // case 0x80: // FLIPPT[ ] (FLIP PoinT) { int loop = state.loop; for (int i = 0; i < loop; i++) { int p = stack.Pop(); FLIPPT(glyph, p); } state.loop = 1; } break; case 0x81: // FLIPRGON[ ] (FLIP RanGe ON) { int high = stack.Pop(); int low = stack.Pop(); FLIPRGON(glyph, high, low); } break; case 0x82: // FLIPRGOFF[ ] (FLIP RanGe OFF) { int high = stack.Pop(); int low = stack.Pop(); FLIPRGOFF(glyph, high, low); } break; case 0x32: // SHP[a] (SHift Point by the last point) { int loop = state.loop; for (int i = 0; i < loop; i++) { int p = stack.Pop(); SHP( points[state.zp1][state.rp2], origin[state.rp2], points[state.zp2][p], state.projection_vector, state.freedom_vector ); } state.loop = 1; } break; case 0x33: // SHP[a] { int loop = state.loop; for (int i = 0; i < loop; i++) { int p = stack.Pop(); SHP( points[state.zp0][state.rp1], origin[state.rp1], points[state.zp2][p], state.projection_vector, state.freedom_vector ); } state.loop = 1; } break; // SHC[a] (SHift Contour by the last point) case 0x34: case 0x35: { int c = stack.Pop(); SHC( glyph, points, origin, state, c, (opcode & 1) > 0 ); } break; case 0x36: // SHZ[a] (SHift Zone by the last pt) { int e = stack.Pop(); } break; case 0x37: // SHZ[a] { int e = stack.Pop(); } break; case 0x38: // SHPIX[ ] (SHift point by a PIXel amount) { float amount = stack.PopF26Dot6(); int loop = state.loop; for (int i = 0; i < loop; i++) { int p = stack.Pop(); Point2D point = points[state.zp2][p]; point.x += Cos(state.freedom_vector) * amount; point.y += Sin(state.freedom_vector) * amount; } state.loop = 1; } break; // MSIRP[a] (Move Stack Indirect Relative Point) case 0x3A: case 0x3B: { float d = stack.PopF26Dot6(); int p = stack.Pop(); //if (p >= points[state.zp1].Length) { // break; //} MSIRP( ref points[state.zp0][state.rp0], ref points[state.zp1][p], d, p, (opcode & 1) > 0, state ); } break; // MDAP[a] (Move Direct Absolute Point) case 0x2E: case 0x2F: { int p = stack.Pop(); MDAP( points[state.zp0][p], p, (opcode & 1) > 0, state ); } break; // MIAP[a] (Move Indirect Absolute Point) case 0x3E: case 0x3F: { int n = stack.Pop(); int p = stack.Pop(); /* MIAP( ref points[state.zp0][p], cvt.data[n], p, (opcode & 1) > 0, state ); //*/ } break; // MDRP[abcde] (Move Direct Relative Point) case 0xC0: case 0xC1: case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: { int p = stack.Pop(); MDRP( points[state.zp0][state.rp0], origin[state.rp0], points[state.zp1][p], state, p, (opcode & 0x10) > 0, (opcode & 0x08) > 0, (opcode & 0x04) > 0, opcode & 3 ); } break; // MIRP[abcde] (Move Indirect Relative Point) case 0xE0: case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xED: case 0xEE: case 0xEF: case 0xF0: case 0xF1: case 0xF2: case 0xF3: case 0xF4: case 0xF5: case 0xF6: case 0xF7: case 0xF8: case 0xF9: case 0xFA: case 0xFB: case 0xFC: case 0xFD: case 0xFE: case 0xFF: { int n = stack.Pop(); int p = stack.Pop(); /* Console.WriteLine("stream.Depth: {0}", stream.Depth); Console.WriteLine("stream.Position: {0}", stream.Position); Console.WriteLine("state.zp0: {0}", state.zp0); Console.WriteLine("state.zp1: {0}", state.zp1); Console.WriteLine("state.rp0: {0}", state.rp0); //*/ /* if (state.rp0 >= points[state.zp0].Length) { break; } if (p >= points[state.zp1].Length) { break; } //*/ MIRP( points[state.zp0][state.rp0], points[state.zp1][p], state, p, cvt.data[n], (opcode & 0x10) > 0, (opcode & 0x08) > 0, (opcode & 0x04) > 0, opcode & 3 ); //*/ } break; case 0x3C: // ALIGNRP[ ] (ALIGN Relative Point) { int loop = state.loop; for (int i = 0; i < loop; i++) { int p = stack.Pop(); //if (p >= points[state.zp1].Length) { // continue; //} ALIGNRP( points[state.zp1][p], points[state.zp0][state.rp0], state.freedom_vector, state.projection_vector ); } state.loop = 1; } break; case 0x0F: // ISECT[ ] (moves point p to the InterSECTion of two lines) { int b1 = stack.Pop(); int b0 = stack.Pop(); int a1 = stack.Pop(); int a0 = stack.Pop(); int p = stack.Pop(); ISECT( ref points[state.zp2][p], ref points[state.zp1][a0], ref points[state.zp1][a1], ref points[state.zp0][b0], ref points[state.zp0][b1] ); } break; case 0x27: // ALIGNPTS[ ] (ALIGN Points) { int p1 = stack.Pop(); int p2 = stack.Pop(); ALIGNPTS( points[state.zp1][p1], points[state.zp0][p2], state.freedom_vector, state.projection_vector ); } break; case 0x39: // IP[ ] (Interpolate Point by the last relative stretch) { int loop = state.loop; for (int i = 0; i < loop; i++) { int p = stack.Pop(); IP( points, origin, state, p ); } state.loop = 1; } break; case 0x29: // UTP[ ] (UnTouch Point) { int p = stack.Pop(); } break; case 0x30: // IUP[a] (Interpolate Untouched Points through the outline) IUPY(glyph, origin, points[state.zp2]); break; case 0x31: // IUP[a] IUPX(glyph, origin, points[state.zp2]); break; //----------------------------------------- // Managing exceptions // case 0x5D: // DELTAP1[ ] (DELTA exception P1) { //Console.WriteLine("delta_base: {0}", state.delta_base); //Console.WriteLine("delta_shift: {0}", state.delta_shift); int[] steps = { -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8 }; int n = stack.Pop(); for (int i = 0; i < n; i++) { int p = stack.Pop(); uint arg = (uint)stack.Pop(); int ppem1 = state.delta_base + (int)(arg >> 4); if (ppem < ppem1) { int delta = steps[arg & 0xF] * state.delta_shift; points[state.zp0][p].x += Cos(state.projection_vector) * delta; points[state.zp0][p].y += Sin(state.projection_vector) * delta; } } } break; case 0x71: // DELTAP2[ ] (DELTA exception P2) { int[] steps = { -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8 }; int n = stack.Pop(); for (int i = 0; i < n; i++) { int p = stack.Pop(); uint arg = (uint)stack.Pop(); int ppem1 = state.delta_base + 16 + (int)(arg >> 4); if (ppem < ppem1) { int delta = steps[arg & 0xF] * state.delta_shift; points[state.zp0][p].x += Cos(state.projection_vector) * delta; points[state.zp0][p].y += Sin(state.projection_vector) * delta; } } } break; case 0x72: // DELTAP3[ ] (DELTA exception P3) { int[] steps = { -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8 }; int n = stack.Pop(); for (int i = 0; i < n; i++) { int p = stack.Pop(); uint arg = (uint)stack.Pop(); int ppem1 = state.delta_base + 32 + (int)(arg >> 4); if (ppem < ppem1) { int delta = steps[arg & 0xF] * state.delta_shift; points[state.zp0][p].x += Cos(state.projection_vector) * delta; points[state.zp0][p].y += Sin(state.projection_vector) * delta; } } } break; case 0x73: // DELTAC1[ ] (DELTA exception C1) { int[] steps = { -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8 }; int n = stack.Pop(); for (int i = 0; i < n; i++) { int c = stack.Pop(); uint arg = (uint)stack.Pop(); int ppem1 = state.delta_base + (int)(arg >> 4); if (ppem < ppem1) { int delta = steps[arg & 0xF] * state.delta_shift; cvt.data[c] = (cvt.data[c] + delta); } } } break; case 0x74: // DELTAC2[ ] (DELTA exception C2) { int[] steps = { -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8 }; int n = stack.Pop(); for (int i = 0; i < n; i++) { int c = stack.Pop(); uint arg = (uint)stack.Pop(); int ppem1 = state.delta_base + 16 + (int)(arg >> 4); if (ppem < ppem1) { int delta = steps[arg & 0xF] * state.delta_shift; cvt.data[c] = (cvt.data[c] + delta); } } } break; case 0x75: // DELTAC3[ ] (DELTA exception C3) { int[] steps = { -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8 }; int n = stack.Pop(); for (int i = 0; i < n; i++) { int c = stack.Pop(); uint arg = (uint)stack.Pop(); int ppem1 = state.delta_base + 32 + (int)(arg >> 4); if (ppem < ppem1) { int delta = steps[arg & 0xF] * state.delta_shift; cvt.data[c] = (cvt.data[c] + delta); } } } break; //----------------------------------------- // Managing the stack // case 0x20: // DUP[ ] (Duplicate top stack element) stack.Dup(); break; case 0x21: // POP[ ] (POP top stack element) stack.Pop(); break; case 0x22: // CLEAR[ ] (Clear the entire stack) stack.Reset(); break; case 0x23: // SWAP[ ] (SWAP the top two elements on the stack) stack.Swap(); break; case 0x24: // DEPTH[ ] (Returns the DEPTH of the stack) stack.PushDepth(); break; case 0x25: // CINDEX[ ] (Copy the INDEXed element to the top of the stack) { int k = stack.Pop(); if (k <= 0) { throw new InvalidOperationException( "CINDEX: argument must be positive number" ); } stack.PushCopy(k); } break; case 0x26: // MINDEX[ ] (Move the INDEXed element to the top of the stack) { int k = stack.Pop(); if (k <= 0) { throw new InvalidOperationException( "MINDEX: argument must be positive number" ); } stack.MoveToTop(k); } break; case 0x8A: // ROLL[ ] (ROLL the top three stack elements) stack.Roll(); break; //----------------------------------------- // Managing the flow of control // case 0x58: // IF[ ] (IF test) stream.IF(stack.Pop()); break; case 0x1B: // ELSE[ ] (ELSE) stream.ELSE(); break; case 0x59: // EIF[ ] (End IF) break; case 0x78: // JROT[ ] (Jump Relative On True) { int e = stack.Pop(); int offset = stack.Pop(); stream.JROT(e, offset); } break; case 0x1C: // JMPR (JuMP) { int offset = stack.Pop(); stream.JMPR(offset); } break; case 0x79: // JROF[ ] (Jump Relative On False) { int e = stack.Pop(); int offset = stack.Pop(); stream.JROF(e, offset); } break; //----------------------------------------- // Logical functions // case 0x50: // LT[ ] (Less Than) stack.LT(); break; case 0x51: // LTEQ[ ] (Less Than or Equal) stack.LTEQ(); break; case 0x52: // GT[ ] (Greater Than) stack.GT(); break; case 0x53: // GTEQ[ ] (Greater Than or Equal) stack.GTEQ(); break; case 0x54: // EQ[ ] (EQual) stack.EQ(); break; case 0x55: // NEQ[ ] (Not EQual) stack.NEQ(); break; case 0x56: // ODD[ ] (ODD) stack.Odd(state.round_state); break; case 0x57: // EVEN[ ] (EVEN) stack.Even(state.round_state); break; case 0x5A: // AND[ ] (logical AND) stack.And(); break; case 0x5B: // OR[ ] (logical OR) stack.Or(); break; case 0x5C: // NOT[ ] (logical NOT) stack.Not(); break; //----------------------------------------- // Arithmetic and math instructions // case 0x60: // ADD[ ] (ADD) stack.Add(); break; case 0x61: // SUB[ ] (SUBtract) stack.Sub(); break; case 0x62: // DIV[ ] (DIVide) stack.Div(); break; case 0x63: // MUL[ ] (MULtiply) stack.Mul(); break; case 0x64: // ABS[ ] (ABSolute value) stack.Abs(); break; case 0x65: // NEG[ ] (NEGate) stack.Neg(); break; case 0x66: // FLOOR[ ] (FLOOR) stack.Floor(); break; case 0x67: // CEILING[ ] (CEILING) stack.Ceil(); break; case 0X8B: // MAX[ ] (MAXimum of top two stack elements) stack.Max(); break; case 0X8C: // MIN[ ] (MINimum of top two stack elements) stack.Min(); break; //------------------------------------------------ // Compensating for the engine characteristics // // ROUND[ab] (ROUND value) case 0x68: case 0x69: case 0x6A: case 0x6B: stack.Round(state, (byte)(opcode & 3)); break; // NROUND[ab] (No ROUNDing of value) case 0x6C: case 0x6D: case 0x6E: case 0x6F: stack.Round(state, (byte)(opcode & 3)); break; //------------------------------------------------ // Defining and using functions and instructions // case 0x2C: // FDEF[ ] (Function DEFinition) { int f = stack.Pop(); //Console.WriteLine("FDEF: {0}", f); funcs.FDEF(f, stream.GetFunc()); } break; case 0x2D: // ENDF[ ] (END Function definition) break; case 0x2B: // CALL[ ] (CALL function) { int f = stack.Pop(); if (f < 0 || f >= maxFunctionDefs) { break; } byte[] fdata = funcs.CALL(f); //if (fdata != null) { stream.Push(fdata); //} } break; case 0x2A: // LOOPCALL[ ] (LOOP and CALL function) { int f = stack.Pop(); int count = stack.Pop(); stream.Push( funcs.CALL(f), count ); } break; case 0x89: // IDEF[ ] (Instruction DEFinition) { int code = stack.Pop(); funcs.IDEF((byte)code, stream.GetFunc()); } break; //------------------------------------------------ // Debugging // case 0x4F: // DEBUG[ ] (DEBUG call) { int number = stack.Pop(); if (Debug != null) { Debug(number); } } break; //------------------------------------------------ // Miscellaneous instructions // case 0x88: // GETINFO[ ] (GET INFOrmation) { GetInfoSelector selector = (GetInfoSelector)stack.Pop(); if (selector.HasFlag(GetInfoSelector.Version)) { getInfoResult.SetVersion(40); } else { getInfoResult.ClearVersion(); } stack.Push((int)getInfoResult); } break; case 0x91: // GETVARIATION[ ] (GET VARIATION) stack.Push(0); stack.Push(0); break; case 0x7F: // AA[ ] stack.Pop(); break; default: { byte[] inst = funcs.ICALL(opcode); if (inst != null) { stream.Push(inst); break; } throw new InvalidOperationException( string.Format("Opcode 0x{0:X2} is not supported.", opcode) ); } } } if (IsDebug == false) { stream.Clear(); state.Reset(); if (glyph != null) { SimpleGlyph simpleGlyph = glyph.simpleGlyph; if (simpleGlyph != null) { for (int i = 0; i < points.Length; i++) { Point2D point = points[1][i]; simpleGlyph.xCoordinates[i] = (short)point.x; simpleGlyph.yCoordinates[i] = (short)point.y; } } } } return glyph; } protected float Sin(float value) { return (float)Math.Sin(value); } protected float Cos(float value) { return (float)Math.Cos(value); } protected float Floor(float value) { return (float)Math.Floor(value); } protected float Sqrt(float value) { return (float)Math.Sqrt(value); } protected int GC(Point2D p, float projectionVector) { float length = p.GetLength(projectionVector); return (int)(length * 64); } protected void SCFS(Point2D p, int value, float freedomVector, float projectionVector) { float fv = value; fv /= 64; Point2D v = new Point2D(fv, fv); float d = v.GetLength(projectionVector); p.x += d * Cos(freedomVector); p.y += d * Sin(freedomVector); } protected int MD(Point2D p1, Point2D p2, bool a, GraphicsState state) { float d; if (a == false) { d = p1.GetDistance(p2, state.projection_vector); } else { Point2D pp1 = p1.Clone(); Point2D pp2 = p2.Clone(); pp1.x = Round(p1.x, state.round_state); pp1.y = Round(p1.y, state.round_state); pp2.x = Round(p2.x, state.round_state); pp2.y = Round(p2.y, state.round_state); d = pp1.GetDistance(pp2, state.projection_vector); } return (int)(d * 64); } protected int MPPEM(float projectionVector) { Point2D em = new Point2D(ppem, ppem); Console.WriteLine("MPPEM: {0}, {1}, {2}", ppem, projectionVector, em.GetLength(projectionVector)); return (int)(em.GetLength(projectionVector) * 64); } protected int MPS() { return (96 * 64 * ppem / 72); } protected void FLIPPT(Glyph glyph, int p) { if (glyph == null) { return; } SimpleGlyphFlags[] flags = glyph.simpleGlyph.flags; if ((flags[p] & SimpleGlyphFlags.ON_CURVE_POINT) > 0) { flags[p] &= (SimpleGlyphFlags)0xFE; } else { flags[p] |= SimpleGlyphFlags.ON_CURVE_POINT; } // TODO: touched } protected void FLIPRGON(Glyph glyph, int high, int low) { if (glyph == null) { return; } SimpleGlyphFlags[] flags = glyph.simpleGlyph.flags; for (int i = low; i <= high; i++) { flags[i] |= SimpleGlyphFlags.ON_CURVE_POINT; } // TODO: touched } protected void FLIPRGOFF(Glyph glyph, int high, int low) { if (glyph == null) { return; } SimpleGlyphFlags[] flags = glyph.simpleGlyph.flags; for (int i = low; i <= high; i++) { flags[i] &= (SimpleGlyphFlags)0xFE; } // TODO: touched } protected void SHP(Point2D rp, Point2D rpo, Point2D p, float projectionVector, float freedomVector) { float d = rpo.GetDistance(rp, projectionVector); p.x += d * Cos(freedomVector); p.y += d * Sin(freedomVector); } protected void SHC(Glyph glyph, Point2D[][] points, Point2D[] origin, GraphicsState state, int c, bool a) { Point2D[] ps = null; int rp = -1; //int zone = 0; if (a) { ps = points[state.zp0]; rp = (int)state.rp1; //zone = state.zp0; } else { ps = points[state.zp1]; rp = (int)state.rp2; //zone = state.zp1; } Point2D p2 = ps[rp]; Point2D p1 = origin[rp]; float dx = (p2.x - p1.x) * Cos(state.projection_vector); float dy = (p2.y - p1.y) * Sin(state.projection_vector); float d = Sqrt(dx * dx + dy + dy); if (d <= 0) { return; } ushort[] endPtsOfContours = glyph.simpleGlyph.endPtsOfContours; int start = 0; int end = endPtsOfContours[c]; if (c > 0) { start = endPtsOfContours[c - 1]; } dx += d * Cos(state.freedom_vector); dy += d * Sin(state.freedom_vector); for (int i = start; i < end; i++) { if (i == rp) { continue; } ps[i].x += dx; ps[i].y += dy; } } protected void MSIRP(ref Point2D rp, ref Point2D p0, float d, int p, bool a, GraphicsState state) { float dx = p0.x - rp.x; float dy = p0.y - rp.y; float di = Sqrt(dx * dx + dy * dy); dx *= d / di; dy *= d / di; p0.x += dx * Cos(state.freedom_vector); p0.y += dy * Sin(state.freedom_vector); state.rp1 = state.rp0; state.rp2 = p; if (a) { state.rp0 = p; } } protected void MDAP(Point2D p0, int p, bool a, GraphicsState state) { if (a) { p0.x = Round(p0.x, state.round_state); p0.y = Round(p0.y, state.round_state); } else { // TODO: fix } state.rp0 = p; state.rp1 = p; } protected void MIAP(ref Point2D p0, int n, int p, bool a, GraphicsState state) { float f = (float)n / 64; p0.x = f * Cos(state.projection_vector); p0.y = f * Sin(state.projection_vector); if (a) { // TODO: control_value_cut_in p0.x = Round(p0.x, state.round_state); p0.y = Round(p0.y, state.round_state); } state.rp0 = p; state.rp1 = p; } protected void MDRP(Point2D rp0, Point2D rpo0, Point2D p, GraphicsState state, int pi, bool a, bool b, bool c, int de) { float dx = rp0.x - rpo0.x; float dy = rp0.y - rpo0.y; float d = Sqrt(dx * dx + dy * dy); float minimumDistance = (float)state.minimum_distance / 64; float cutIn = (float)state.control_value_cut_in / 64; if (b) { if (d >= minimumDistance) { } } if (c) { //n = Round(n, state.round_state); d = Round(d, state.round_state); } //d = (((float)n) / 64) / d; dx *= d; dy *= d; if (d >= cutIn) { p.x += dx * Cos(state.freedom_vector); p.y += dy * Sin(state.freedom_vector); } state.rp1 = state.rp0; state.rp2 = pi; if (a) { state.rp0 = pi; } } protected void MIRP(Point2D rp0, Point2D p, GraphicsState state, int pi, int n, bool a, bool b, bool c, int de) { float dx = p.x - rp0.x; float dy = p.y - rp0.y; float d = Sqrt(dx * dx + dy * dy); float minimumDistance = (float)state.minimum_distance / 64; float cutIn = (float)state.control_value_cut_in / 64; if (b) { if (d >= minimumDistance) { } } if (c) { n = (int)Round((uint)n, state.round_state); d = Round(d, state.round_state); } d = (((float)n) / 64) / d; dx *= d; dy *= d; if (d >= cutIn) { p.x += dx * Cos(state.freedom_vector); p.y += dy * Sin(state.freedom_vector); } state.rp1 = state.rp0; state.rp2 = pi; if (a) { state.rp0 = pi; } } protected void ALIGNRP(Point2D p1, Point2D rp, float freedomVector, float projectionVector) { float d = p1.GetDistance(rp, projectionVector); p1.x += d * Cos(freedomVector); p1.y += d * Sin(freedomVector); } protected void ISECT(ref Point2D p, ref Point2D a0, ref Point2D a1, ref Point2D b0, ref Point2D b1) { float d = (a1.x - a0.x) * (b1.y - b0.y) - (a1.y - a0.y) * (b1.x - b0.x); if (d.Equals(0f)) { // TODO: fix return; } float dx = b0.x - a0.x; float dy = b0.y - a0.y; float r = ((b1.y - b0.y) * dx - (b1.x - b0.x) * dy) / d; p.x = a0.x + r * (a1.x - a0.x); p.y = a0.y + r * (a1.y - a0.y); } protected void ALIGNPTS(Point2D p1, Point2D p2, float freedomVector, float projectionVector) { float d = p1.GetDistance(p2, projectionVector); float dx = d * Cos(freedomVector) * 0.5f; float dy = d * Sin(freedomVector) * 0.5f; p1.x += dx; p1.y += dy; p2.x -= dx; p2.y -= dy; } protected float Distance(Point2D p0, Point2D p1, GraphicsState state) { float x = (p1.x - p0.x) * Cos(state.projection_vector); float y = (p1.y - p0.y) * Sin(state.projection_vector); float sign = x < 0 || y < 0 ? -1 : 1; return sign * Sqrt(x * x + y * y); } protected float Distance2(Point2D p0, Point2D p1, GraphicsState state) { float x = (p1.x - p0.x) * Cos(state.projection_vector); float y = (p1.y - p0.y) * Sin(state.projection_vector); return Sqrt(x * x + y * y); } protected Point2D Intersect(Point2D a, Point2D b, Point2D c, Point2D d) { float bn = (b.x - a.x) * (d.y - c.y) - (b.y - a.y) * (d.x - c.x); if (Math.Abs(bn) < float.Epsilon) { return Point2D.Empty; } Point2D ac = new Point2D(c.x - a.x, c.y - a.y); float dr = ((d.y - c.y) * ac.x - (d.x - c.x) * ac.y) / bn; return new Point2D( a.x + dr * (b.x - a.x), a.y + dr * (b.y - a.y) ); } protected void IP(Point2D[][] points, Point2D[] origin, GraphicsState state, int p) { /* Point2D p1 = points[state.zp2][p]; float d0 = Distance2(origin[p], origin[state.rp1], state); float d1 = Distance2(origin[p], origin[state.rp2], state); Point2D rp1 = points[state.zp0][state.rp1]; Point2D rp2 = points[state.zp1][state.rp2]; float drp = Distance2(rp1, rp2, state); rp1.X += Cos(state.projection_vector) * drp * d0 / (d0 + d1); rp1.Y += Sin(state.projection_vector) * drp * d0 / (d0 + d1); rp2.X -= Cos(state.projection_vector) * drp * d1 / (d0 + d1); rp2.Y -= Sin(state.projection_vector) * drp * d1 / (d0 + d1); Point2D p2 = p1; p2.X += Cos(state.freedom_vector) * 10; p2.Y += Sin(state.freedom_vector) * 10; Console.WriteLine("###### p1:{0}, p2:{1}, drp:{2}", p1, p2, drp); p1 = Intersect(rp1, rp2, p1, p2); //p1.X += drp * d0 / (d0 + d1) * fvx; //p1.Y += drp * d0 / (d0 + d1) * fvy; if (p1.IsEmpty) { return; } points[state.zp2][p] = p1; float d2 = Distance2(p1, points[state.zp0][state.rp1], state); float d3 = Distance2(p1, points[state.zp1][state.rp2], state); Console.WriteLine("###### p1:{0}", p1); Console.WriteLine("##### p:{0}, rp1:{1}, rp1':{2}", origin[p], origin[state.rp1], points[state.zp0][state.rp1]); Console.WriteLine("##### p:{0}, rp2:{1}, rp2':{2}", origin[p], origin[state.rp2], points[state.zp1][state.rp2]); Console.WriteLine("#### d0:{0}, d1:{1}, d2:{2}, d3:{3}", d0, d1, d2, d3); //Console.WriteLine("#### d0 / d2:{0}, d1 / d3:{1}", d0 / d2, d1 / d3); Console.WriteLine("#### d0 / d1:{0}, d2 / d3:{1}", d0 / d1, d2 / d3); Console.WriteLine(); //*/ } protected void IUPX(Glyph glyph, Point2D[] origin, Point2D[] points) { if (glyph == null) { return; } ushort[] endPtsOfContours = glyph.simpleGlyph.endPtsOfContours; int contours = endPtsOfContours.Length; int start = 0; for (int contour = 0; contour < contours; contour++) { int end = endPtsOfContours[contour]; for (int i = start; i < end; i++) { if (!origin[i].x.Equals(points[i].x)) { continue; } int p = i - 1; int n = i + 1; if (p < start) { p = end - 1; } if (n >= end) { n = 0; } float op = origin[p].x, on = origin[n].x; float pp = points[p].x, pn = points[n].x; if (!op.Equals(pp) && !on.Equals(pn)) { float dp = pp - op; float np = pn - on; points[i].x += (np + dp) / 2; continue; } if (!op.Equals(pp)) { points[i].x += pp - op; continue; } if (!on.Equals(pn)) { points[i].x += pn - on; } } start = end; } } protected void IUPY(Glyph glyph, Point2D[] origin, Point2D[] points) { if (glyph == null) { return; } ushort[] endPtsOfContours = glyph.simpleGlyph.endPtsOfContours; int contours = endPtsOfContours.Length; int start = 0; for (int contour = 0; contour < contours; contour++) { int end = endPtsOfContours[contour]; for (int i = start; i < end; i++) { if (!origin[i].y.Equals(points[i].y)) { continue; } int p = i - 1; int n = i + 1; if (p < start) { p = end - 1; } if (n >= end) { n = 0; } float op = origin[p].y, on = origin[n].y; float pp = points[p].y, pn = points[n].y; if (!op.Equals(pp) && !on.Equals(pn)) { float dp = pp - op; float np = pn - on; points[i].y += (np + dp) / 2; continue; } if (!op.Equals(pp)) { points[i].y += pp - op; continue; } if (!on.Equals(pn)) { points[i].y += pn - on; } } start = end; } } protected float Round(float value, RoundState roundState) { return (float)Round((uint)(value * 64), roundState) / 64; } protected uint Round(uint f26d6, RoundState roundState) { if (roundState == RoundState.Off) { return f26d6; } switch (roundState) { case RoundState.HalfGrid: f26d6 &= 0xFFFFFFC0; f26d6 |= 0x20; break; case RoundState.Grid: if ((f26d6 & 0x20) > 0) { f26d6 &= 0xFFFFFFC0; f26d6 += 0x40; } else { f26d6 &= 0xFFFFFFC0; } break; case RoundState.DoubleGrid: f26d6 &= 0xFFFFFFE0; break; case RoundState.DownToGrid: f26d6 &= 0xFFFFFFC0; break; case RoundState.UpToGrid: if ((f26d6 & 0x3F) > 0) { f26d6 &= 0xFFFFFFC0; f26d6 += 0x40; } else { f26d6 &= 0xFFFFFFC0; } break; } return f26d6; } } }
27.300126
122
0.518638
[ "MIT" ]
hikipuro/SharpGlyph
SharpGlyph/SharpGlyph/Instructions/Interpreter.cs
43,300
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Internal { [AllowAnonymous] [IdentityDefaultUI(typeof(ResetPasswordModel<>))] public abstract class ResetPasswordModel : PageModel { [BindProperty] public InputModel Input { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] public string Code { get; set; } } public virtual IActionResult OnGet(string code = null) => throw new NotImplementedException(); public virtual Task<IActionResult> OnPostAsync() => throw new NotImplementedException(); } internal class ResetPasswordModel<TUser> : ResetPasswordModel where TUser : class { private readonly UserManager<TUser> _userManager; public ResetPasswordModel(UserManager<TUser> userManager) { _userManager = userManager; } public override IActionResult OnGet(string code = null) { if (code == null) { return BadRequest("A code must be supplied for password reset."); } else { Input = new InputModel { Code = code }; return Page(); } } public override async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToPage("./ResetPasswordConfirmation"); } var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password); if (result.Succeeded) { return RedirectToPage("./ResetPasswordConfirmation"); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return Page(); } } }
31.59596
129
0.578325
[ "Apache-2.0" ]
Asesjix/Identity
src/UI/Areas/Identity/Pages/V4/Account/ResetPassword.cshtml.cs
3,128
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.Extensions.Logging; using Roslyn.Utilities; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace BuildValidator { public class BuildConstructor { private readonly ILogger _logger; public BuildConstructor(ILogger logger) { _logger = logger; } public (Compilation? compilation, bool isError) CreateCompilation( CompilationOptionsReader compilationOptionsReader, string fileName, ImmutableArray<ResolvedSource> sources, ImmutableArray<MetadataReference> metadataReferences) { // We try to handle assemblies missing compilation options gracefully by skipping them. // However, if an assembly has some bad combination of data, for example if it contains // compilation options but not metadata references, then we throw an exception. if (!compilationOptionsReader.TryGetMetadataCompilationOptions(out var pdbCompilationOptions) || pdbCompilationOptions.Length == 0) { _logger.LogInformation($"{fileName} did not contain compilation options in its PDB"); return (compilation: null, isError: false); } if (pdbCompilationOptions.TryGetUniqueOption("language", out var language)) { var diagnosticBag = DiagnosticBag.GetInstance(); var compilation = language switch { LanguageNames.CSharp => CreateCSharpCompilation(fileName, compilationOptionsReader, sources, metadataReferences), LanguageNames.VisualBasic => CreateVisualBasicCompilation(fileName, compilationOptionsReader, sources, metadataReferences, diagnosticBag), _ => throw new InvalidDataException($"{language} is not a known language") }; var diagnostics = diagnosticBag.ToReadOnlyAndFree(); var hadError = false; foreach (var diagnostic in diagnostics) { if (diagnostic.Severity == DiagnosticSeverity.Error) { _logger.LogError(diagnostic.ToString()); hadError = true; } else { _logger.LogWarning(diagnostic.ToString()); } } compilation = hadError ? null : compilation; return (compilation, isError: compilation is null); } throw new InvalidDataException("Did not find language in compilation options"); } private Compilation CreateCSharpCompilation( string fileName, CompilationOptionsReader optionsReader, ImmutableArray<ResolvedSource> sources, ImmutableArray<MetadataReference> metadataReferences) { var (compilationOptions, parseOptions) = CreateCSharpCompilationOptions(optionsReader, fileName); return CSharpCompilation.Create( Path.GetFileNameWithoutExtension(fileName), syntaxTrees: sources.Select(s => CSharpSyntaxTree.ParseText(s.SourceText, options: parseOptions, path: s.SourceFileInfo.SourceFilePath)).ToImmutableArray(), references: metadataReferences, options: compilationOptions); } private (CSharpCompilationOptions, CSharpParseOptions) CreateCSharpCompilationOptions(CompilationOptionsReader optionsReader, string fileName) { using var scope = _logger.BeginScope("Options"); var pdbCompilationOptions = optionsReader.GetMetadataCompilationOptions(); var langVersionString = pdbCompilationOptions.GetUniqueOption(CompilationOptionNames.LanguageVersion); pdbCompilationOptions.TryGetUniqueOption(CompilationOptionNames.Optimization, out var optimization); pdbCompilationOptions.TryGetUniqueOption(CompilationOptionNames.Platform, out var platform); // TODO: Check portability policy if needed // pdbCompilationOptions.TryGetValue("portability-policy", out var portabilityPolicyString); pdbCompilationOptions.TryGetUniqueOption(_logger, CompilationOptionNames.Define, out var define); pdbCompilationOptions.TryGetUniqueOption(_logger, CompilationOptionNames.Checked, out var checkedString); pdbCompilationOptions.TryGetUniqueOption(_logger, CompilationOptionNames.Nullable, out var nullable); pdbCompilationOptions.TryGetUniqueOption(_logger, CompilationOptionNames.Unsafe, out var unsafeString); CS.LanguageVersionFacts.TryParse(langVersionString, out var langVersion); var preprocessorSymbols = define == null ? ImmutableArray<string>.Empty : define.Split(',').ToImmutableArray(); var parseOptions = CSharpParseOptions.Default.WithLanguageVersion(langVersion) .WithPreprocessorSymbols(preprocessorSymbols); var (optimizationLevel, plus) = GetOptimizationLevel(optimization); var nullableOptions = nullable is null ? NullableContextOptions.Disable : (NullableContextOptions)Enum.Parse(typeof(NullableContextOptions), nullable); var compilationOptions = new CSharpCompilationOptions( optionsReader.GetOutputKind(), reportSuppressedDiagnostics: false, moduleName: fileName, mainTypeName: optionsReader.GetMainTypeName(), scriptClassName: null, usings: null, optimizationLevel, !string.IsNullOrEmpty(checkedString) && bool.Parse(checkedString), !string.IsNullOrEmpty(unsafeString) && bool.Parse(unsafeString), cryptoKeyContainer: null, cryptoKeyFile: null, cryptoPublicKey: optionsReader.GetPublicKey()?.ToImmutableArray() ?? default, delaySign: null, GetPlatform(platform), // presence of diagnostics is expected to not affect emit. ReportDiagnostic.Suppress, warningLevel: 4, specificDiagnosticOptions: null, concurrentBuild: true, deterministic: true, xmlReferenceResolver: null, sourceReferenceResolver: null, metadataReferenceResolver: null, assemblyIdentityComparer: null, strongNameProvider: null, publicSign: false, metadataImportOptions: MetadataImportOptions.Public, nullableContextOptions: nullableOptions); compilationOptions.DebugPlusMode = plus; return (compilationOptions, parseOptions); } private static (OptimizationLevel, bool) GetOptimizationLevel(string? optimizationLevel) => optimizationLevel switch { null or "debug" => (OptimizationLevel.Debug, false), "debug-plus" => (OptimizationLevel.Debug, true), "release" => (OptimizationLevel.Release, false), _ => throw new InvalidDataException($"Optimization \"{optimizationLevel}\" level not recognized") }; private static Platform GetPlatform(string? platform) => platform is null ? Platform.AnyCpu : (Platform)Enum.Parse(typeof(Platform), platform); private Compilation CreateVisualBasicCompilation( string fileName, CompilationOptionsReader optionsReader, ImmutableArray<ResolvedSource> sources, ImmutableArray<MetadataReference> metadataReferences, DiagnosticBag diagnosticBag) { var compilationOptions = CreateVisualBasicCompilationOptions(optionsReader, fileName, diagnosticBag); return VisualBasicCompilation.Create( Path.GetFileNameWithoutExtension(fileName), syntaxTrees: sources.Select(s => VisualBasicSyntaxTree.ParseText(s.SourceText, options: compilationOptions.ParseOptions, path: s.SourceFileInfo.SourceFilePath)).ToImmutableArray(), references: metadataReferences, options: compilationOptions); } private static VisualBasicCompilationOptions CreateVisualBasicCompilationOptions(CompilationOptionsReader optionsReader, string fileName, DiagnosticBag diagnosticBag) { var pdbCompilationOptions = optionsReader.GetMetadataCompilationOptions(); var langVersionString = pdbCompilationOptions.GetUniqueOption(CompilationOptionNames.LanguageVersion); pdbCompilationOptions.TryGetUniqueOption(CompilationOptionNames.Optimization, out var optimization); pdbCompilationOptions.TryGetUniqueOption(CompilationOptionNames.Platform, out var platform); pdbCompilationOptions.TryGetUniqueOption(CompilationOptionNames.GlobalNamespaces, out var globalNamespacesString); IEnumerable<GlobalImport>? globalImports = null; if (!string.IsNullOrEmpty(globalNamespacesString)) { globalImports = GlobalImport.Parse(globalNamespacesString.Split(';')); } VB.LanguageVersion langVersion = default; VB.LanguageVersionFacts.TryParse(langVersionString, ref langVersion); IReadOnlyDictionary<string, object>? preprocessorSymbols = null; if (OptionToString(CompilationOptionNames.Define) is string defineString) { preprocessorSymbols = VisualBasicCommandLineParser.ParseConditionalCompilationSymbols(defineString, out var diagnostics); if (diagnostics is object) { diagnosticBag.AddRange(diagnostics); } } var parseOptions = VisualBasicParseOptions .Default .WithLanguageVersion(langVersion) .WithPreprocessorSymbols(preprocessorSymbols.ToImmutableArrayOrEmpty()); var (optimizationLevel, plus) = GetOptimizationLevel(optimization); var isChecked = OptionToBool(CompilationOptionNames.Checked) ?? true; var embedVBRuntime = OptionToBool(CompilationOptionNames.EmbedRuntime) ?? false; var rootNamespace = OptionToString(CompilationOptionNames.RootNamespace); var compilationOptions = new VisualBasicCompilationOptions( optionsReader.GetOutputKind(), moduleName: fileName, mainTypeName: optionsReader.GetMainTypeName(), scriptClassName: "Script", globalImports: globalImports, rootNamespace: rootNamespace, optionStrict: OptionToEnum<OptionStrict>(CompilationOptionNames.OptionStrict) ?? OptionStrict.Off, optionInfer: OptionToBool(CompilationOptionNames.OptionInfer) ?? false, optionExplicit: OptionToBool(CompilationOptionNames.OptionExplicit) ?? false, optionCompareText: OptionToBool(CompilationOptionNames.OptionCompareText) ?? false, parseOptions: parseOptions, embedVbCoreRuntime: embedVBRuntime, optimizationLevel: optimizationLevel, checkOverflow: isChecked, cryptoKeyContainer: null, cryptoKeyFile: null, cryptoPublicKey: optionsReader.GetPublicKey()?.ToImmutableArray() ?? default, delaySign: null, platform: GetPlatform(platform), generalDiagnosticOption: ReportDiagnostic.Default, specificDiagnosticOptions: null, concurrentBuild: true, deterministic: true, xmlReferenceResolver: null, sourceReferenceResolver: null, metadataReferenceResolver: null, assemblyIdentityComparer: null, strongNameProvider: null, publicSign: false, reportSuppressedDiagnostics: false, metadataImportOptions: MetadataImportOptions.Public); compilationOptions.DebugPlusMode = plus; return compilationOptions; string? OptionToString(string option) => pdbCompilationOptions.TryGetUniqueOption(option, out var value) ? value : null; bool? OptionToBool(string option) => pdbCompilationOptions.TryGetUniqueOption(option, out var value) ? ToBool(value) : null; T? OptionToEnum<T>(string option) where T : struct => pdbCompilationOptions.TryGetUniqueOption(option, out var value) ? ToEnum<T>(value) : null; static bool? ToBool(string value) => bool.TryParse(value, out var boolValue) ? boolValue : null; static T? ToEnum<T>(string value) where T : struct => Enum.TryParse<T>(value, out var enumValue) ? enumValue : null; } public static unsafe EmitResult Emit( Stream rebuildPeStream, FileInfo originalBinaryPath, CompilationOptionsReader optionsReader, Compilation producedCompilation, ILogger logger, CancellationToken cancellationToken) { var peHeader = optionsReader.PeReader.PEHeaders.PEHeader!; var win32Resources = optionsReader.PeReader.GetSectionData(peHeader.ResourceTableDirectory.RelativeVirtualAddress); using var win32ResourceStream = new UnmanagedMemoryStream(win32Resources.Pointer, win32Resources.Length); var sourceLink = optionsReader.GetSourceLinkUTF8(); var embeddedTexts = producedCompilation.SyntaxTrees .Select(st => (path: st.FilePath, text: st.GetText())) .Where(pair => pair.text.CanBeEmbedded) .Select(pair => EmbeddedText.FromSource(pair.path, pair.text)) .ToImmutableArray(); var debugEntryPoint = getDebugEntryPoint(); var emitResult = producedCompilation.Emit( peStream: rebuildPeStream, pdbStream: null, xmlDocumentationStream: null, win32Resources: win32ResourceStream, useRawWin32Resources: true, manifestResources: optionsReader.GetManifestResources(), options: new EmitOptions( debugInformationFormat: DebugInformationFormat.Embedded, highEntropyVirtualAddressSpace: (peHeader.DllCharacteristics & DllCharacteristics.HighEntropyVirtualAddressSpace) != 0, subsystemVersion: SubsystemVersion.Create(peHeader.MajorSubsystemVersion, peHeader.MinorSubsystemVersion)), debugEntryPoint: debugEntryPoint, metadataPEStream: null, pdbOptionsBlobReader: optionsReader.GetMetadataCompilationOptionsBlobReader(), sourceLinkStream: sourceLink != null ? new MemoryStream(sourceLink) : null, embeddedTexts: embeddedTexts, cancellationToken: cancellationToken); return emitResult; IMethodSymbol? getDebugEntryPoint() { if (optionsReader.GetMainTypeName() is { } mainTypeName && optionsReader.GetMainMethodName() is { } mainMethodName) { var typeSymbol = producedCompilation.GetTypeByMetadataName(mainTypeName); if (typeSymbol is object) { var methodSymbols = typeSymbol .GetMembers(mainMethodName) .OfType<IMethodSymbol>(); return methodSymbols.FirstOrDefault(); } } return null; } } } }
49.180758
196
0.644733
[ "MIT" ]
digitalcoyote/roslyn
src/Compilers/Core/Rebuild/BuildConstructor.cs
16,871
C#
using System; namespace DxHumanModel.Inputs { public class Metabolism { public Metabolism() { } } }
12.454545
29
0.547445
[ "MIT" ]
Mygi/DxHumanModel
DxHumanModel/Inputs/Metabolism.cs
139
C#
using System.Threading.Tasks; namespace Esquio.Abstractions { /// <summary> /// Base contract for <see cref="IScopedEvaluationHolder"/> used for store feature evaluation results on the same execution scope. /// This reduce the numbers of evaluations and ensure result consistency on the same scope (http request on asp.net core etc). /// By default, a NO evaluation holder is used and scoped evaluation results are never stored and reused on <see cref="IFeatureService"/>. /// </summary> public interface IScopedEvaluationHolder { /// <summary> /// Try to get a previous feature evaluation from the session store. /// </summary> /// <param name="featureName">The feature name.</param> /// <param name="enabled">The feature and product evaluation result.</param> /// <returns>A <see cref="Task{bool}"/> that complete when finished, yielding True if session contain a previous evaluation result, else False.</returns> Task<bool> TryGetAsync(string featureName, out bool enabled); /// <summary> /// Set evaluation result into this session store. /// </summary> /// <param name="featureName">The feature name.</param> /// <returns>A <see cref="Task"/> that complete when finished.</returns> Task SetAsync(string featureName, bool enabled); } internal sealed class NoScopedEvaluationHolder : IScopedEvaluationHolder { public Task SetAsync(string featureName, bool enabled) { return Task.CompletedTask; } public Task<bool> TryGetAsync(string featureName, out bool enabled) { enabled = false; return Task.FromResult(false); } } }
42.093023
162
0.637017
[ "Apache-2.0" ]
andrew-flatters-bliss/Esquio
src/Esquio/Abstractions/IScopedEvaluationHolder.cs
1,812
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace JD.TodoAPIXamarin.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
21.326087
56
0.536188
[ "MIT" ]
IT-Evan/JD.TodoAPIXamarin
JD.TodoAPIXamarin/Controllers/ValuesController.cs
983
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Xenko.Core.Assets.Compiler; using Xenko.Core.BuildEngine; using Xenko.Core; using Xenko.Core.Mathematics; using Xenko.Core.Serialization; using Xenko.Rendering; using Xenko.Graphics.Data; using Xenko.Physics; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xenko.Core.Assets; using Xenko.Core.Assets.Analysis; using Xenko.Core.Serialization.Contents; using Xenko.Assets.Textures; using VHACDSharp; using Buffer = Xenko.Graphics.Buffer; namespace Xenko.Assets.Physics { [AssetCompiler(typeof(ColliderShapeAsset), typeof(AssetCompilationContext))] internal class ColliderShapeAssetCompiler : AssetCompilerBase { static ColliderShapeAssetCompiler() { NativeLibrary.PreloadLibrary("VHACD.dll"); } public override IEnumerable<BuildDependencyInfo> GetInputTypes(AssetItem assetItem) { foreach (var type in AssetRegistry.GetAssetTypes(typeof(Model))) { yield return new BuildDependencyInfo(type, typeof(AssetCompilationContext), BuildDependencyType.CompileContent); } foreach (var type in AssetRegistry.GetAssetTypes(typeof(Skeleton))) { yield return new BuildDependencyInfo(type, typeof(AssetCompilationContext), BuildDependencyType.CompileContent); } } public override IEnumerable<Type> GetInputTypesToExclude(AssetItem assetItem) { foreach(var type in AssetRegistry.GetAssetTypes(typeof(Material))) { yield return type; } yield return typeof(TextureAsset); } protected override void Prepare(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result) { var asset = (ColliderShapeAsset)assetItem.Asset; result.BuildSteps = new AssetBuildStep(assetItem); result.BuildSteps.Add(new ColliderShapeCombineCommand(targetUrlInStorage, asset, assetItem.Package)); } public class ColliderShapeCombineCommand : AssetCommand<ColliderShapeAsset> { public ColliderShapeCombineCommand(string url, ColliderShapeAsset parameters, IAssetFinder assetFinder) : base(url, parameters, assetFinder) { } protected override Task<ResultStatus> DoCommandOverride(ICommandContext commandContext) { var assetManager = new ContentManager(MicrothreadLocalDatabases.ProviderService); // Cloned list of collider shapes var descriptions = Parameters.ColliderShapes.ToList(); var validShapes = Parameters.ColliderShapes.Where(x => x != null && (x.GetType() != typeof(ConvexHullColliderShapeDesc) || ((ConvexHullColliderShapeDesc)x).Model != null)).ToList(); //pre process special types foreach (var convexHullDesc in (from shape in validShapes let type = shape.GetType() where type == typeof(ConvexHullColliderShapeDesc) select shape) .Cast<ConvexHullColliderShapeDesc>()) { // Clone the convex hull shape description so the fields that should not be serialized can be cleared (Model in this case) ConvexHullColliderShapeDesc convexHullDescClone = new ConvexHullColliderShapeDesc { Scaling = convexHullDesc.Scaling, LocalOffset = convexHullDesc.LocalOffset, LocalRotation = convexHullDesc.LocalRotation, Depth = convexHullDesc.Depth, PosSampling = convexHullDesc.PosSampling, AngleSampling = convexHullDesc.AngleSampling, PosRefine = convexHullDesc.PosRefine, AngleRefine = convexHullDesc.AngleRefine, Alpha = convexHullDesc.Alpha, Threshold = convexHullDesc.Threshold, }; // Replace shape in final result with cloned description int replaceIndex = descriptions.IndexOf(convexHullDesc); descriptions[replaceIndex] = convexHullDescClone; var loadSettings = new ContentManagerLoaderSettings { ContentFilter = ContentManagerLoaderSettings.NewContentFilterByType(typeof(Mesh), typeof(Skeleton)) }; var modelAsset = assetManager.Load<Model>(AttachedReferenceManager.GetUrl(convexHullDesc.Model), loadSettings); if (modelAsset == null) continue; convexHullDescClone.ConvexHulls = new List<List<List<Vector3>>>(); convexHullDescClone.ConvexHullsIndices = new List<List<List<uint>>>(); commandContext.Logger.Info("Processing convex hull generation, this might take a while!"); var nodeTransforms = new List<Matrix>(); //pre-compute all node transforms, assuming nodes are ordered... see ModelViewHierarchyUpdater if (modelAsset.Skeleton == null) { Matrix baseMatrix; Matrix.Transformation(ref convexHullDescClone.Scaling, ref convexHullDescClone.LocalRotation, ref convexHullDescClone.LocalOffset, out baseMatrix); nodeTransforms.Add(baseMatrix); } else { var nodesLength = modelAsset.Skeleton.Nodes.Length; for (var i = 0; i < nodesLength; i++) { Matrix localMatrix; Matrix.Transformation( ref modelAsset.Skeleton.Nodes[i].Transform.Scale, ref modelAsset.Skeleton.Nodes[i].Transform.Rotation, ref modelAsset.Skeleton.Nodes[i].Transform.Position, out localMatrix); Matrix worldMatrix; if (modelAsset.Skeleton.Nodes[i].ParentIndex != -1) { var nodeTransform = nodeTransforms[modelAsset.Skeleton.Nodes[i].ParentIndex]; Matrix.Multiply(ref localMatrix, ref nodeTransform, out worldMatrix); } else { worldMatrix = localMatrix; } if (i == 0) { Matrix baseMatrix; Matrix.Transformation(ref convexHullDescClone.Scaling, ref convexHullDescClone.LocalRotation, ref convexHullDescClone.LocalOffset, out baseMatrix); nodeTransforms.Add(baseMatrix*worldMatrix); } else { nodeTransforms.Add(worldMatrix); } } } for (var i = 0; i < nodeTransforms.Count; i++) { var i1 = i; if (modelAsset.Meshes.All(x => x.NodeIndex != i1)) continue; // no geometry in the node var combinedVerts = new List<float>(); var combinedIndices = new List<uint>(); var hullsList = new List<List<Vector3>>(); convexHullDescClone.ConvexHulls.Add(hullsList); var indicesList = new List<List<uint>>(); convexHullDescClone.ConvexHullsIndices.Add(indicesList); foreach (var meshData in modelAsset.Meshes.Where(x => x.NodeIndex == i1)) { var indexOffset = (uint)combinedVerts.Count / 3; var stride = meshData.Draw.VertexBuffers[0].Declaration.VertexStride; var vertexBufferRef = AttachedReferenceManager.GetAttachedReference(meshData.Draw.VertexBuffers[0].Buffer); byte[] vertexData; if (vertexBufferRef.Data != null) { vertexData = ((BufferData)vertexBufferRef.Data).Content; } else if (!string.IsNullOrEmpty(vertexBufferRef.Url)) { var dataAsset = assetManager.Load<Buffer>(vertexBufferRef.Url); vertexData = dataAsset.GetSerializationData().Content; } else { continue; } var vertexIndex = meshData.Draw.VertexBuffers[0].Offset; for (var v = 0; v < meshData.Draw.VertexBuffers[0].Count; v++) { var posMatrix = Matrix.Translation(new Vector3(BitConverter.ToSingle(vertexData, vertexIndex + 0), BitConverter.ToSingle(vertexData, vertexIndex + 4), BitConverter.ToSingle(vertexData, vertexIndex + 8))); Matrix rotatedMatrix; var nodeTransform = nodeTransforms[i]; Matrix.Multiply(ref posMatrix, ref nodeTransform, out rotatedMatrix); combinedVerts.Add(rotatedMatrix.TranslationVector.X); combinedVerts.Add(rotatedMatrix.TranslationVector.Y); combinedVerts.Add(rotatedMatrix.TranslationVector.Z); vertexIndex += stride; } var indexBufferRef = AttachedReferenceManager.GetAttachedReference(meshData.Draw.IndexBuffer.Buffer); byte[] indexData; if (indexBufferRef.Data != null) { indexData = ((BufferData)indexBufferRef.Data).Content; } else if (!string.IsNullOrEmpty(indexBufferRef.Url)) { var dataAsset = assetManager.Load<Buffer>(indexBufferRef.Url); indexData = dataAsset.GetSerializationData().Content; } else { throw new Exception("Failed to find index buffer while building a convex hull."); } var indexIndex = meshData.Draw.IndexBuffer.Offset; for (var v = 0; v < meshData.Draw.IndexBuffer.Count; v++) { if (meshData.Draw.IndexBuffer.Is32Bit) { combinedIndices.Add(BitConverter.ToUInt32(indexData, indexIndex) + indexOffset); indexIndex += 4; } else { combinedIndices.Add(BitConverter.ToUInt16(indexData, indexIndex) + indexOffset); indexIndex += 2; } } } var decompositionDesc = new ConvexHullMesh.DecompositionDesc { VertexCount = (uint)combinedVerts.Count / 3, IndicesCount = (uint)combinedIndices.Count, Vertexes = combinedVerts.ToArray(), Indices = combinedIndices.ToArray(), Depth = convexHullDesc.Depth, PosSampling = convexHullDesc.PosSampling, PosRefine = convexHullDesc.PosRefine, AngleSampling = convexHullDesc.AngleSampling, AngleRefine = convexHullDesc.AngleRefine, Alpha = convexHullDesc.Alpha, Threshold = convexHullDesc.Threshold, SimpleHull = convexHullDesc.SimpleWrap }; var convexHullMesh = new ConvexHullMesh(); convexHullMesh.Generate(decompositionDesc); var count = convexHullMesh.Count; commandContext.Logger.Info("Node generated " + count + " convex hulls"); var vertexCountHull = 0; for (uint h = 0; h < count; h++) { float[] points; convexHullMesh.CopyPoints(h, out points); var pointList = new List<Vector3>(); for (var v = 0; v < points.Length; v += 3) { var vert = new Vector3(points[v + 0], points[v + 1], points[v + 2]); pointList.Add(vert); vertexCountHull++; } hullsList.Add(pointList); uint[] indices; convexHullMesh.CopyIndices(h, out indices); for (var t = 0; t < indices.Length; t += 3) { Core.Utilities.Swap(ref indices[t], ref indices[t + 2]); } var indexList = new List<uint>(indices); indicesList.Add(indexList); } convexHullMesh.Dispose(); commandContext.Logger.Info("For a total of " + vertexCountHull + " vertexes"); } } var runtimeShape = new PhysicsColliderShape(descriptions); assetManager.Save(Url, runtimeShape); return Task.FromResult(ResultStatus.Successful); } } } }
48.146497
236
0.498412
[ "MIT" ]
Aminator/xenko
sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs
15,118
C#
// PropDefinitionKey using ClubPenguin.Core.StaticGameData; using ClubPenguin.Props; using System; [Serializable] public class PropDefinitionKey : TypedStaticGameDataKey<PropDefinition, int> { }
19.6
76
0.826531
[ "MIT" ]
smdx24/CPI-Source-Code
ClubPenguin.Props/PropDefinitionKey.cs
196
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public static class DelayHelper { public static Coroutine DelayAction(this MonoBehaviour monobehaviour, Action action, float delayDuration) { return monobehaviour.StartCoroutine(DelayActionRoutine(action, delayDuration)); } private static IEnumerator DelayActionRoutine(Action action, float delayDuration) { yield return new WaitForSeconds(delayDuration); action(); } }
26.7
110
0.724719
[ "MIT" ]
pauldubb/Project02
Assets/Scripts/DelayHelper.cs
536
C#
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Collections.Generic; using System.Linq; using Cube.Mixin.Collections; using Cube.Mixin.Iteration; using Cube.Mixin.Syntax; using NUnit.Framework; namespace Cube.Tests.Mixin { /* --------------------------------------------------------------------- */ /// /// EnumerableTest /// /// <summary> /// Tests extended methods of the IEnumerable(T) class. /// </summary> /// /* --------------------------------------------------------------------- */ [TestFixture] class EnumerableTest { #region Tests #region GetOrEmpty /* ----------------------------------------------------------------- */ /// /// GetOrEmpty /// /// <summary> /// Tests of the GetOrDefault extended method. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void GetOrEmpty() { var sum = 0; var src = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; src.GetOrEmpty().Each(i => sum += i); Assert.That(sum, Is.EqualTo(55)); } /* ----------------------------------------------------------------- */ /// /// GetOrEmpty_Null /// /// <summary> /// Tests of the GetOrDefault extended method with the null object. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void GetOrEmpty_Null() { var sum = 0; var src = default(List<int>); src.GetOrEmpty().Each(i => sum += i); Assert.That(sum, Is.EqualTo(0)); } #endregion #region FirstIndexOf /* ----------------------------------------------------------------- */ /// /// FirstIndexOf /// /// <summary> /// Tests the FirstIndexOf method at the specified condition. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void FirstIndexOf() { var src = 50.Make(i => i * 2); Assert.That(src.FirstIndex(i => i < 20), Is.EqualTo(0)); } /* ----------------------------------------------------------------- */ /// /// FirstIndexOf_Empty /// /// <summary> /// Tests the FirstIndexOf method against the empty List(T) object. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void FirstIndexOf_Empty() { var src = Enumerable.Empty<int>(); Assert.That(src.FirstIndex(i => i < 20), Is.EqualTo(-1)); } /* ----------------------------------------------------------------- */ /// /// FirstIndexOf_Default /// /// <summary> /// Tests the FirstIndexOf method against the default of List(T). /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void FirstIndexOf_Default() { var src = default(List<int>); Assert.That(src.FirstIndex(i => i < 20), Is.EqualTo(-1)); } /* ----------------------------------------------------------------- */ /// /// FirstIndexOf_NeverMatch /// /// <summary> /// Tests the FirstIndexOf method with the never-matched predicate. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void FirstIndexOf_NeverMatch() { var src = Enumerable.Range(1, 10); Assert.That(src.FirstIndex(i => i > 100), Is.EqualTo(-1)); } #endregion #region LastIndexOf /* ----------------------------------------------------------------- */ /// /// LastIndexOf /// /// <summary> /// Tests the LastIndexOf method at the specified condition. /// </summary> /// /* ----------------------------------------------------------------- */ [TestCase(10, ExpectedResult = 9)] [TestCase( 1, ExpectedResult = 0)] [TestCase( 0, ExpectedResult = -1)] public int LastIndexOf(int count) => Enumerable.Range(0, count).LastIndex(); /* ----------------------------------------------------------------- */ /// /// LastIndexOf /// /// <summary> /// Tests the LastIndexOf method at the specified condition. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void LastIndexOf() { var src = 50.Make(i => i * 2); Assert.That(src.LastIndex(i => i < 20), Is.EqualTo(9)); } /* ----------------------------------------------------------------- */ /// /// LastIndexOf_Default /// /// <summary> /// Tests the LastIndexOf method against the default of List(T). /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void LastIndexOf_Default() { var src = default(List<int>); Assert.That(src.LastIndex(), Is.EqualTo(-1)); } /* ----------------------------------------------------------------- */ /// /// LastIndexOf_NeverMatch /// /// <summary> /// Tests the LastIndexOf method with the never-matched predicate. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void LastIndexOf_NeverMatch() { var src = Enumerable.Range(1, 10); Assert.That(src.LastIndex(i => i > 100), Is.EqualTo(-1)); } /* ----------------------------------------------------------------- */ /// /// Clamp /// /// <summary> /// Tests the Clamp method at the specified condition. /// </summary> /// /* ----------------------------------------------------------------- */ [TestCase(10, 5, ExpectedResult = 5)] [TestCase(10, 20, ExpectedResult = 9)] [TestCase(10, -1, ExpectedResult = 0)] [TestCase( 0, 10, ExpectedResult = 0)] [TestCase( 0, -1, ExpectedResult = 0)] public int Clamp(int count, int index) => Enumerable.Range(0, count).Clamp(index); /* ----------------------------------------------------------------- */ /// /// Clamp_Default /// /// <summary> /// Tests the Clamp method against the default of List(T). /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Clamp_Default() { var src = default(List<int>); Assert.That(src.Clamp(100), Is.EqualTo(0)); } #endregion #region Compact /* ----------------------------------------------------------------- */ /// /// Compact /// /// <summary> /// Tests the Compact extended method. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Compact() { var src = new[] { "Hello", "world!", string.Empty, null }; Assert.That(src.Length, Is.EqualTo(4)); Assert.That(src.Compact().Count(), Is.EqualTo(3)); } /* ----------------------------------------------------------------- */ /// /// Compact_ValueType /// /// <summary> /// Tests the Compact extended method with the value type collection. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Compact_ValueType() { var src = new[] { 3, 1, 4, 1, 5 }; Assert.That(src.Length, Is.EqualTo(5)); Assert.That(src.Compact().Count(), Is.EqualTo(5)); } /* ----------------------------------------------------------------- */ /// /// Compact_Empty /// /// <summary> /// Tests of the Compact extended method with the empty collection. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Compact_Empty() { var src = Enumerable.Empty<int>(); Assert.That(src.Count(), Is.EqualTo(0)); Assert.That(src.Compact().Count(), Is.EqualTo(0)); } #endregion #region Concat /* ----------------------------------------------------------------- */ /// /// Concat /// /// <summary> /// Test the Concat extended method. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Concat() { var src = 10.Make(i => i); Assert.That(src.Concat(10, 20).Count(), Is.EqualTo(12)); Assert.That(src.Concat(30).Count(), Is.EqualTo(11)); Assert.That(src.Concat().Count(), Is.EqualTo(10)); } #endregion #region Join /* ----------------------------------------------------------------- */ /// /// Join /// /// <summary> /// Tests the Join extended method. /// </summary> /// /* ----------------------------------------------------------------- */ [TestCase(0, ExpectedResult = "")] [TestCase(1, ExpectedResult = "k0=v0")] [TestCase(2, ExpectedResult = "k0=v0&k1=v1")] [TestCase(3, ExpectedResult = "k0=v0&k1=v1&k2=v2")] public string Join(int n) => Enumerable.Range(0, n).Join("&", i => $"k{i}=v{i}"); #endregion #region Flatten /* ----------------------------------------------------------------- */ /// /// Flatten /// /// <summary> /// Tests the Flatten extended method. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Flatten() { var src = new[] { new Tree { Name = "1st" }, new Tree { Name = "2nd", Children = new[] { new Tree { Name = "2nd-1st", Children = new[] { new Tree { Name = "2nd-1st-1st" } }, }, new Tree { Name = "2nd-2nd" }, new Tree { Name = "2nd-3rd", Children = new[] { new Tree { Name = "2nd-3rd-1st" }, new Tree { Name = "2nd-3rd-2nd" }, }, }, }, }, new Tree { Name = "3rd" }, }; var dest = src.Flatten(e => e.Children).ToList(); Assert.That(dest.Count, Is.EqualTo(9)); Assert.That(dest[0].Name, Is.EqualTo("1st")); Assert.That(dest[1].Name, Is.EqualTo("2nd")); Assert.That(dest[2].Name, Is.EqualTo("3rd")); Assert.That(dest[3].Name, Is.EqualTo("2nd-1st")); Assert.That(dest[4].Name, Is.EqualTo("2nd-2nd")); Assert.That(dest[5].Name, Is.EqualTo("2nd-3rd")); Assert.That(dest[6].Name, Is.EqualTo("2nd-1st-1st")); Assert.That(dest[7].Name, Is.EqualTo("2nd-3rd-1st")); Assert.That(dest[8].Name, Is.EqualTo("2nd-3rd-2nd")); } /* ----------------------------------------------------------------- */ /// /// Flatten_Empty /// /// <summary> /// Tests the Flatten extended method with the empty array. /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Flatten_Empty() { var src = Enumerable.Empty<Tree>(); Assert.That(src.Flatten(e => e.Children).Count(), Is.EqualTo(0)); } #endregion #endregion #region Others /* ----------------------------------------------------------------- */ /// /// Tree /// /// <summary> /// Represents the tree structure. /// </summary> /// /* ----------------------------------------------------------------- */ class Tree { public string Name { get; set; } public IEnumerable<Tree> Children { get; set; } } #endregion } }
32.648402
90
0.343776
[ "Apache-2.0" ]
cube-soft/Cube.Core
Tests/Core/Sources/Mixin/EnumerableTest.cs
14,302
C#
using Quasar.Server.Networking; using Quasar.Server.Utilities; using System; using System.Globalization; using System.Net.Sockets; using System.Windows.Forms; using Quasar.Server.Models; namespace Quasar.Server.Forms { public partial class FrmSettings : Form { private readonly QuasarServer _listenServer; public FrmSettings(QuasarServer listenServer) { this._listenServer = listenServer; InitializeComponent(); ToggleListenerSettings(!listenServer.Listening); ShowPassword(false); } private void FrmSettings_Load(object sender, EventArgs e) { ncPort.Value = Settings.ListenPort; chkIPv6Support.Checked = Settings.IPv6Support; chkAutoListen.Checked = Settings.AutoListen; chkPopup.Checked = Settings.ShowPopup; chkUseUpnp.Checked = Settings.UseUPnP; chkShowTooltip.Checked = Settings.ShowToolTip; chkNoIPIntegration.Checked = Settings.EnableNoIPUpdater; txtNoIPHost.Text = Settings.NoIPHost; txtNoIPUser.Text = Settings.NoIPUsername; txtNoIPPass.Text = Settings.NoIPPassword; } private ushort GetPortSafe() { var portValue = ncPort.Value.ToString(CultureInfo.InvariantCulture); ushort port; return (!ushort.TryParse(portValue, out port)) ? (ushort)0 : port; } private void btnListen_Click(object sender, EventArgs e) { ushort port = GetPortSafe(); if (port == 0) { MessageBox.Show("Please enter a valid port > 0.", "Please enter a valid port", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (btnListen.Text == "Start listening" && !_listenServer.Listening) { try { if(chkNoIPIntegration.Checked) NoIpUpdater.Start(); _listenServer.Listen(port, chkIPv6Support.Checked, chkUseUpnp.Checked); ToggleListenerSettings(false); } catch (SocketException ex) { if (ex.ErrorCode == 10048) { MessageBox.Show(this, "The port is already in use.", "Socket Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show(this, $"An unexpected socket error occurred: {ex.Message}\n\nError Code: {ex.ErrorCode}\n\n", "Unexpected Socket Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } _listenServer.Disconnect(); } catch (Exception) { _listenServer.Disconnect(); } } else if (btnListen.Text == "Stop listening" && _listenServer.Listening) { _listenServer.Disconnect(); ToggleListenerSettings(true); } } private void btnSave_Click(object sender, EventArgs e) { ushort port = GetPortSafe(); if (port == 0) { MessageBox.Show("Please enter a valid port > 0.", "Please enter a valid port", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } Settings.ListenPort = port; Settings.IPv6Support = chkIPv6Support.Checked; Settings.AutoListen = chkAutoListen.Checked; Settings.ShowPopup = chkPopup.Checked; Settings.UseUPnP = chkUseUpnp.Checked; Settings.ShowToolTip = chkShowTooltip.Checked; Settings.EnableNoIPUpdater = chkNoIPIntegration.Checked; Settings.NoIPHost = txtNoIPHost.Text; Settings.NoIPUsername = txtNoIPUser.Text; Settings.NoIPPassword = txtNoIPPass.Text; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { if (MessageBox.Show("Discard your changes?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) this.Close(); } private void chkNoIPIntegration_CheckedChanged(object sender, EventArgs e) { NoIPControlHandler(chkNoIPIntegration.Checked); } private void ToggleListenerSettings(bool enabled) { btnListen.Text = enabled ? "Start listening" : "Stop listening"; ncPort.Enabled = enabled; chkIPv6Support.Enabled = enabled; chkUseUpnp.Enabled = enabled; } private void NoIPControlHandler(bool enable) { lblHost.Enabled = enable; lblUser.Enabled = enable; lblPass.Enabled = enable; txtNoIPHost.Enabled = enable; txtNoIPUser.Enabled = enable; txtNoIPPass.Enabled = enable; chkShowPassword.Enabled = enable; } private void ShowPassword(bool show = true) { txtNoIPPass.PasswordChar = (show) ? (char)0 : (char)'●'; } private void chkShowPassword_CheckedChanged(object sender, EventArgs e) { ShowPassword(chkShowPassword.Checked); } } }
35.038217
205
0.561534
[ "Apache-2.0", "MIT" ]
2-young-2-simple/QuasarRAT
Quasar.Server/Forms/FrmSettings.cs
5,505
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Serialization; using System.Text; //Thanks to supersonicclay //From https://github.com/supersonicclay/csharp-date/blob/master/CSharpDate/Date.cs namespace Signum.Utilities { [Serializable, TypeConverter(typeof(DateTypeConverter))] public struct Date : IComparable, IFormattable, ISerializable, IComparable<Date>, IEquatable<Date> { private DateTime _dt; public static readonly Date MaxValue = new Date(DateTime.MaxValue); public static readonly Date MinValue = new Date(DateTime.MinValue); public Date(int year, int month, int day) { this._dt = new DateTime(year, month, day); } public Date(DateTime dateTime) { this._dt = dateTime.AddTicks(-dateTime.Ticks % TimeSpan.TicksPerDay); } private Date(SerializationInfo info, StreamingContext context) { this._dt = DateTime.FromFileTime(info.GetInt64("ticks")); } public static TimeSpan operator -(Date d1, Date d2) { return d1._dt - d2._dt; } public static DateTime operator -(Date d, TimeSpan t) { return d._dt - t; } public static bool operator !=(Date d1, Date d2) { return d1._dt != d2._dt; } public static DateTime operator +(Date d, TimeSpan t) { return d._dt + t; } public static bool operator <(Date d1, Date d2) { return d1._dt < d2._dt; } public static bool operator <=(Date d1, Date d2) { return d1._dt <= d2._dt; } public static bool operator ==(Date d1, Date d2) { return d1._dt == d2._dt; } public static bool operator >(Date d1, Date d2) { return d1._dt > d2._dt; } public static bool operator >=(Date d1, Date d2) { return d1._dt >= d2._dt; } public static implicit operator DateTime(Date d) { return d._dt; } public static explicit operator Date(DateTime d) { return new Date(d); } public int Day { get { return this._dt.Day; } } public DayOfWeek DayOfWeek { get { return this._dt.DayOfWeek; } } public int DayOfYear { get { return this._dt.DayOfYear; } } public int Month { get { return this._dt.Month; } } public static Date Today { get { return new Date(DateTime.Today); } } public int Year { get { return this._dt.Year; } } public long Ticks { get { return this._dt.Ticks; } } public Date AddDays(int value) { return new Date(this._dt.AddDays(value)); } public Date AddMonths(int months) { return new Date(this._dt.AddMonths(months)); } public Date AddYears(int value) { return new Date(this._dt.AddYears(value)); } public static int Compare(Date d1, Date d2) { return d1.CompareTo(d2); } public int CompareTo(Date value) { return this._dt.CompareTo(value._dt); } public int CompareTo(object? value) { return this._dt.CompareTo(value); } public static int DaysInMonth(int year, int month) { return DateTime.DaysInMonth(year, month); } public bool Equals(Date value) { return this._dt.Equals(value._dt); } public override bool Equals(object? value) { return value is Date && this._dt.Equals(((Date)value)._dt); } public override int GetHashCode() { return this._dt.GetHashCode(); } public static bool Equals(Date d1, Date d2) { return d1._dt.Equals(d2._dt); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("ticks", this._dt.Ticks); } public static bool IsLeapYear(int year) { return DateTime.IsLeapYear(year); } public static Date Parse(string s) { return new Date(DateTime.Parse(s)); } public static Date Parse(string s, IFormatProvider provider) { return new Date(DateTime.Parse(s, provider)); } public static Date Parse(string s, IFormatProvider provider, DateTimeStyles style) { return new Date(DateTime.Parse(s, provider, style)); } public static Date ParseExact(string s, string format, IFormatProvider provider) { return new Date(DateTime.ParseExact(s, ConvertFormat(format), provider)); } public static Date ParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style) { return new Date(DateTime.ParseExact(s, ConvertFormat(format), provider, style)); } public static Date ParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style) { return new Date(DateTime.ParseExact(s, formats, provider, style)); } public DateTime Add(TimeSpan value) { return this + value; } public TimeSpan Subtract(Date value) { return this - value; } public DateTime Subtract(TimeSpan value) { return this - value; } public string ToLongString() { return this._dt.ToLongDateString(); } public string ToShortString() { return this._dt.ToShortDateString(); } public override string ToString() { return this.ToShortString(); } public string ToString(IFormatProvider provider) => ToString(null, provider); public string ToString(string format) => ToString(format, CultureInfo.CurrentCulture); public string ToString(string? format, IFormatProvider? provider) { return this._dt.ToString(ConvertFormat(format), provider); } [return: NotNullIfNotNull("format")] private static string? ConvertFormat(string? format) { if (format == "O" || format == "o" || format == "s") { format = "yyyy-MM-dd"; } return format; } public static bool TryParse(string s, out Date result) { DateTime d; bool success = DateTime.TryParse(s, out d); result = new Date(d); return success; } public static bool TryParse(string s, IFormatProvider provider, DateTimeStyles style, out Date result) { DateTime d; bool success = DateTime.TryParse(s, provider, style, out d); result = new Date(d); return success; } public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out Date result) { if (format == "O" || format == "o" || format == "s") { format = "yyyy-MM-dd"; } DateTime d; bool success = DateTime.TryParseExact(s, format, provider, style, out d); result = new Date(d); return success; } public static bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out Date result) { DateTime d; bool success = DateTime.TryParseExact(s, formats, provider, style, out d); result = new Date(d); return success; } } public class DateTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } public override object? ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return string.IsNullOrEmpty((string)value) ? (Date?)null : (Date?)Date.ParseExact((string)value, "o", CultureInfo.InvariantCulture); } public override object? ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { var date = (Date?)value; return date == null ? null : date.Value.ToString("o"); } } }
27.658192
145
0.52058
[ "MIT" ]
AlejandroCano/framework
Signum.Utilities/Date.cs
9,791
C#
using CommunicationService.Core.Domains; using CommunicationService.Core.Interfaces.Repositories; using System; using System.Linq; using System.Threading.Tasks; namespace CommunicationService.Core.Services { public class PurgeService : IPurgeService { private readonly ILinkRepository _linkRepository; public PurgeService(ILinkRepository linkRepository) { _linkRepository = linkRepository; } public async Task PurgeExpiredLinks() { var links = await _linkRepository.GetExpiredLinksAsync(); if(links!=null && links.Count()>0) { foreach (Links l in links) { await _linkRepository.DeleteLink(l.id); } } } } }
24.484848
69
0.607673
[ "MIT" ]
HelpMyStreet/communication-service
CommunicationService/CommunicationService.Core/Services/PurgeService.cs
810
C#
using System; using System.Threading; using HidSharp; using LightHouse.Lib; using Serilog; namespace LightHouse.Delcom.SignalLight { public class SignalLightController : IControlSignalLight, IDisposable { private readonly ILogger _logger; private const int VendorId = 0x0fc5; private const int ProductId = 0xb080; private HidStream _stream; private const int Green = 254; private const int Red = 253; private const int Orange = 251; private const int Off = 255; private const int BuzzerOn = 1; private const int BuzzerOff = 0; private const int EightBytesFlag = 101; private const int SixteenBytesFlag = 102; private const int SolidCommand = 2; private const int FlashCommand = 20; private const int BuzzCommand = 70; public bool IsConnected { get; set; } public SignalLightController(ILogger logger) { _logger = logger; _logger.Information($"Getting HID device with vendor id: {VendorId} and product id: {ProductId}"); DeviceList.Local.Changed += ConnectedDevicesChanged; Connect(); } private void ConnectedDevicesChanged(object sender, DeviceListChangedEventArgs e) { Connect(); } private void Connect() { if (DeviceList.Local.TryGetHidDevice(out var signalLight, VendorId, ProductId)) { OpenStream(signalLight); } else { IsConnected = false; } } private void OpenStream(HidDevice signalLight) { try { _logger.Information("Signal Light device found!"); _logger.Information("Opening device"); _stream = signalLight.Open(); _logger.Information("Stream open"); IsConnected = true; } catch (Exception e) { IsConnected = false; _logger.Fatal($"Signal Light device threw an exception with message {e.Message}"); } } public void TurnOnColor(SignalLightColor color, byte brightness = 5, bool flash = false) { TurnOffColor(); SetBrightness(brightness); switch (color) { case SignalLightColor.Green: WriteToDevice(new byte[] { EightBytesFlag, SolidCommand, Green }); if (flash) WriteToDevice(new byte[] { EightBytesFlag, FlashCommand, 0, 1 }); break; case SignalLightColor.Red: WriteToDevice(new byte[] { EightBytesFlag, SolidCommand, Red }); if (flash) WriteToDevice(new byte[] { EightBytesFlag, FlashCommand, 0, 2 }); break; case SignalLightColor.Orange: WriteToDevice(new byte[] { EightBytesFlag, SolidCommand, Orange }); if (flash) WriteToDevice(new byte[] { EightBytesFlag, FlashCommand, 0, 4 }); break; default: throw new ArgumentOutOfRangeException(nameof(color), color, null); } TurnOffBuzzer(); } public void TurnOnBuzzer(byte frequency, byte repeatCount, byte onTime, byte offTime) { var writeData = new byte[] { SixteenBytesFlag, BuzzCommand, BuzzerOn, frequency, 0, 0, 0, 0, repeatCount, onTime, offTime }; WriteToDevice(writeData); } public void TurnOffBuzzer() { WriteToDevice(new byte[] { SixteenBytesFlag, BuzzCommand, BuzzerOff }); } public void TurnOffColor() { WriteToDevice(new byte[] { EightBytesFlag, SolidCommand, Off }); WriteToDevice(new byte[] { EightBytesFlag, FlashCommand, Off }); } public void TurnOffAll() { TurnOffColor(); TurnOffBuzzer(); } public void SetBrightness(byte brightness) { if (brightness < 1) brightness = 1; if (brightness > 100) brightness = 100; WriteToDevice(new byte[] { EightBytesFlag, 34, 0, brightness }); WriteToDevice(new byte[] { EightBytesFlag, 34, 1, brightness }); WriteToDevice(new byte[] { EightBytesFlag, 34, 2, brightness }); } public void Test(byte brightness) { TurnOnColor(SignalLightColor.Red, brightness); Thread.Sleep(400); TurnOnColor(SignalLightColor.Orange, brightness); Thread.Sleep(400); TurnOnColor(SignalLightColor.Green, brightness); Thread.Sleep(400); TurnOnColor(SignalLightColor.Red, brightness); Thread.Sleep(400); TurnOnColor(SignalLightColor.Orange, brightness); Thread.Sleep(400); TurnOnColor(SignalLightColor.Green, brightness); Thread.Sleep(400); TurnOnColor(SignalLightColor.Red, brightness); Thread.Sleep(400); TurnOnColor(SignalLightColor.Orange, brightness); Thread.Sleep(400); TurnOnColor(SignalLightColor.Green, brightness); Thread.Sleep(400); TurnOffAll(); } public void Dispose() { _logger.Information("Turning off Signal Light lights and buzzer"); TurnOffAll(); _logger.Information("Disposing Signal Light of stream"); _stream?.Dispose(); } private void WriteToDevice(byte[] values) { if (IsConnected) { try { if (values[0] == EightBytesFlag) { _stream?.SetFeature(values.PadRight()); } else if (values[0] == SixteenBytesFlag) { _stream?.SetFeature(values.PadRight(16)); } } catch (Exception) { _logger.Fatal("Could not write bytes to Signal Light stream!"); } } } } }
32.720812
136
0.531182
[ "MIT" ]
josdeweger/LightHouse
src/LightHouse.Delcom.SignalLight/SignalLightController.cs
6,448
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Tem.V20210701.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class IngressRuleValue : AbstractModel { /// <summary> /// Overall rule configuration /// </summary> [JsonProperty("Paths")] public IngressRulePath[] Paths{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamArrayObj(map, prefix + "Paths.", this.Paths); } } }
29.681818
81
0.657734
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Tem/V20210701/Models/IngressRuleValue.cs
1,306
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ProblemSolver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ProblemSolver")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7b181902-1601-4588-a079-e0252bcd85df")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.810811
84
0.745533
[ "MIT" ]
Patplays852/ProjectEuler
ProblemSolver/ProblemSolver/Properties/AssemblyInfo.cs
1,402
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information #region Usings using System.Collections; using System.Web.UI; #endregion namespace DotNetNuke.UI.WebControls { /// <summary>A collection of PageHierarchyData objects</summary> public class NavDataPageHierarchicalEnumerable : ArrayList, IHierarchicalEnumerable { #region IHierarchicalEnumerable Members /// <summary> /// Handles enumeration /// </summary> /// <param name="enumeratedItem"></param> /// <returns></returns> /// <remarks></remarks> public virtual IHierarchyData GetHierarchyData(object enumeratedItem) { return (IHierarchyData) enumeratedItem; } #endregion } }
27.272727
87
0.671111
[ "MIT" ]
MaiklT/Dnn.Platform
DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs
902
C#
using JiraWebApi.Internal; using JiraWebApi.Linq; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JiraWebApi { /// <summary> /// Representation of a JIRA user. /// </summary> public sealed class User { /// <summary> /// Initializes a new instance of the User class. /// </summary> internal User() { } /// <summary> /// Automatic assignee for AssignIssueAsync. /// </summary> public static User AutomaticAssignee { get { return new User() { Name = "-1" }; } } /// <summary> /// Empty assignee for AssignIssueAsync. /// </summary> public static User EmptyAssignee { get { return new User() { Name = null }; } } /// <summary> /// Support of the JQL 'currentUser()' operator in LINQ. /// </summary> /// <returns>Returns always null.</returns> /// <remarks>For Linq use only.</remarks> /// <remarks>NotSupportedException will not work here because the Linq visitor compiles this method.</remarks> [JqlFunction("currentUser")] public static User CurrentUser() { throw new NotSupportedException("Operator only defined to allow Linq comparison."); } /// <summary> /// Support of the JQL 'membersOf()' operator in LINQ. /// </summary> /// <param name="groupName">Name of the group.</param> /// <returns>No result.</returns> /// <remarks>For Linq use only.</remarks> /// <remarks>NotSupportedException will not work here because the Linq visitor compiles this method.</remarks> [JqlFunction("membersOf")] public static User[] MembersOf(string groupName) { throw new NotSupportedException("Operator only defined to allow Linq comparison."); } /// <summary> /// Url of the REST item. /// </summary> [JsonProperty("self")] public Uri Self { get; private set; } /// <summary> /// Name of the JIRA user. /// </summary> [JsonProperty("name")] public string Name { get; internal set; } /// <summary> /// E-mail address of the JIRA user. /// </summary> [JsonProperty("emailAddress")] public string EmailAddress { get; private set; } /// <summary> /// Avatar URLs of the JIRA user. /// </summary> [JsonProperty("avatarUrls")] public AvatarUrls AvatarUrls { get; private set; } /// <summary> /// Display name of the JIRA user. /// </summary> [JsonProperty("displayName")] public string DisplayName { get; private set; } /// <summary> /// Signals if the JIRA user is actve. /// </summary> [JsonProperty("active")] public bool IsActive { get; private set; } /// <summary> /// Time zone of the JIRA user. /// </summary> [JsonProperty("timeZone", NullValueHandling = NullValueHandling.Ignore)] public string TimeZone { get; private set; } /// <summary> /// Returns a string that represents the user. /// </summary> /// <returns>A string that represents the user.</returns> public override string ToString() { return this.Name; } /// <summary> /// Determines whether the specified object is equal to the current object. /// </summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns>true if the specified object is equal to the current object; otherwise, false.</returns> public override bool Equals(object obj) { if (obj == null) { return false; } User user = obj as User; if ((object)user == null) { return false; } return this.Name == user.Name; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns>A hash code for the current Object.</returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Compare equal operator. /// </summary> /// <param name="user1">The first user to compare, or null.</param> /// <param name="user2">The second user to compare, or null.</param> /// <returns>true if the first user is equal to the second user; otherwise, false.</returns> public static bool operator ==(User user1, User user2) { if (ReferenceEquals(user1, user2)) { return true; } if (((object)user1 == null) || ((object)user2 == null)) { return false; } return user1.Equals(user2); } /// <summary> /// Compare not equal operator. /// </summary> /// <param name="user1">The first user to compare, or null.</param> /// <param name="user2">The second user to compare, or null.</param> /// <returns>true if the first user is different from the second user; otherwise, false.</returns> public static bool operator !=(User user1, User user2) { return !(user1 == user2); } /// <summary> /// Compare equal operator. /// </summary> /// <param name="user">The user to compare, or null.</param> /// <param name="name">The user name to compare, or null.</param> /// <returns>true if the user is equal to the user name; otherwise, false.</returns> public static bool operator ==(User user, string name) { return user.Name == name; } /// <summary> /// Compare not equal operator /// </summary> /// <param name="user">The user to compare, or null.</param> /// <param name="name">The user name to compare, or null.</param> /// <returns>true if the user is different from the user name; otherwise, false.</returns> public static bool operator !=(User user, string name) { return user.Name != name; } /// <summary> /// Support of the JQL 'is null' operator in LINQ. /// </summary> /// <returns>Not used.</returns> public bool IsNull() { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL 'is not null' operator in LINQ. /// </summary> /// <returns>Not used.</returns> public bool IsNotNull() { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL 'is empty' operator in LINQ. /// </summary> /// <returns>Not used.</returns> public bool IsEmpty() { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL 'is not empty' operator in LINQ. /// </summary> /// <returns>Not used.</returns> public bool IsNotEmpty() { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL In operator in LINQ. /// </summary> /// <param name="values">List to compare with. This can be a combination of string and User parameters.</param> /// <returns>Not used.</returns> public bool In(params object[] values) { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL Not In operator in LINQ. /// </summary> /// <param name="values">List to compare with. This can be a combination of string and User parameters.</param> /// <returns>Not used.</returns> public bool NotIn(params object[] values) { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL 'was' operator in LINQ. /// </summary> /// <param name="user">Item to compare with.</param> /// <returns>Not used.</returns> public bool Was(object user) { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL 'was not' operator in LINQ. /// </summary> /// <param name="user">Item to compare with.</param> /// <returns>Not used.</returns> public bool WasNot(object user) { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL 'was in' operator in LINQ. /// </summary> /// <param name="values">List to compare with.</param> /// <returns>Not used.</returns> public bool WasIn(params object[] values) { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL 'was not in' operator in LINQ. /// </summary> /// <param name="values">List to compare with.</param> /// <returns>Not used.</returns> public bool WasNotIn(params object[] values) { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } /// <summary> /// Support of the JQL 'changed' operator in LINQ. /// </summary> /// <returns>Not used.</returns> public bool Changed() { throw new NotSupportedException(ExceptionMessages.ForLinqUseOnly); } } }
33.734219
119
0.545795
[ "MIT" ]
Bassman2/JiraWebApi
JiraWebApi/User.cs
10,156
C#
using System; class Indent { static void Main() { Console.WriteLine("들여쓰기는 공백 4칸을 사용"); } }
11.4
45
0.561404
[ "MIT" ]
VisualAcademy/DotNet
DotNet/DotNet/04_Syntax/Indent/Indent.cs
138
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using SFA.DAS.ApprenticeCommitments.Web.Identity; using SFA.DAS.ApprenticeCommitments.Web.Services; namespace SFA.DAS.ApprenticeCommitments.Web.Pages.Apprenticeships { public class ApprenticeshipRevisionPageModel : PageModel, IHasBackLink { [BindProperty(SupportsGet = true)] public HashedId ApprenticeshipId { get; set; } [BindProperty] public long RevisionId { get; set; } public string Backlink => $"/apprenticeships/{ApprenticeshipId.Hashed}"; } }
32.333333
80
0.738832
[ "MIT" ]
SkillsFundingAgency/das-apprentice-commitments-web
src/SFA.DAS.ApprenticeCommitments.Web/Pages/Apprenticeships/ApprenticeshipRevisionPageModel.cs
584
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Musaca.Data; namespace Musaca.Data.Migrations { [DbContext(typeof(MusacaDbContext))] [Migration("20200110161053_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.0") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Musaca.Models.Order", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("CashierId") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<DateTime>("IssuedOn") .HasColumnType("datetime2"); b.Property<int>("Status") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CashierId"); b.ToTable("Orders"); }); modelBuilder.Entity("Musaca.Models.Product", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<string>("OrderId") .HasColumnType("nvarchar(450)"); b.Property<decimal>("Price") .HasColumnType("decimal(18,2)"); b.HasKey("Id"); b.HasIndex("OrderId"); b.ToTable("Products"); }); modelBuilder.Entity("Musaca.Models.User", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("Email") .IsRequired() .HasColumnType("nvarchar(20)") .HasMaxLength(20); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Username") .IsRequired() .HasColumnType("nvarchar(20)") .HasMaxLength(20); b.HasKey("Id"); b.ToTable("Users"); }); modelBuilder.Entity("Musaca.Models.Order", b => { b.HasOne("Musaca.Models.User", "Cashier") .WithMany() .HasForeignKey("CashierId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Musaca.Models.Product", b => { b.HasOne("Musaca.Models.Order", null) .WithMany("Products") .HasForeignKey("OrderId"); }); #pragma warning restore 612, 618 } } }
32.982143
117
0.46562
[ "MIT" ]
KostadinovK/CSharp-Web
01-C# Web Basics/06-Exam Prep II/MUSACA/Apps/Musaca.Data/Migrations/20200110161053_Initial.Designer.cs
3,696
C#
namespace Sitecore.Feature.ChatBot.Utils { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Mail; using System.Configuration; public static class EmailSender { //private static string apiKey = ConfigurationManager.AppSettings["SendGridKey"]; public static async Task<bool> SendEmail(string recipient, string sender, string subject, string body) { try { var msg = new MailMessage(sender, recipient, subject, body); var client = new SmtpClient(); client.Send(msg); return true; } catch (Exception ex) { return false; } } } }
26.677419
110
0.588875
[ "Apache-2.0" ]
taulantracaj/HabitatChatBot
src/Feature/ChatBot/code/Utils/EmailSender.cs
829
C#
/* * Copyright 2021 ALE International * * 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; namespace o2g.Types.AnalyticsNS { /// <summary> /// <c>TimeRange</c> represents an interval between two dates. It is used to filter analytics requests /// </summary> /// <see cref="IAnalytics.GetChargingsAsync(int, TimeRange, int?, bool)"/> public class TimeRange { /// <summary> /// Return the "from" date. /// </summary> /// <value> /// The <see cref="DateTime"/> object that represents the "from" date of this range. /// </value> public DateTime from { get; init; } /// <summary> /// Return the "to" date. /// </summary> /// <value> /// The <see cref="DateTime"/> object that represents the "to" date of this range. /// </value> public DateTime to { get; init; } /// <summary> /// Construct a new <c>TimeRange</c>, with the specified "from" date and "to" date. /// </summary> /// <param name="from">The "from" date.</param> /// <param name="to">The "to" date.</param> public TimeRange(DateTime from, DateTime to) { this.from = from; this.to = to; } /// <summary> /// Construct a new <c>TimeRange</c> with the specified "from" date and a specified number of days. /// </summary> /// <param name="from">The "from" date.</param> /// <param name="days">The number of days in this range.</param> public TimeRange(DateTime from, int days) { this.from = from; this.to = this.from.AddDays(days); } } }
39.652174
107
0.628289
[ "MIT" ]
ALE-OPENNESS/CSharp-SDK
Types/Analytics/TimeRange.cs
2,738
C#
version https://git-lfs.github.com/spec/v1 oid sha256:7ee97e2b0bf8c65aed5515583c9d88772852d0da0611d34db123d79a22a0447e size 3177
32.25
75
0.883721
[ "MIT" ]
kenx00x/ahhhhhhhhhhhh
ahhhhhhhhhh/Library/PackageCache/com.unity.visualeffectgraph@7.1.8/Runtime/Utilities/PropertyBinding/Implementation/VFXAudioSpectrumBinder.cs
129
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LabyrinthMultiDB.Engine { public class RoomInfo { public /* readonly */ int levelNumber; public /* readonly */ int roomNumber; public RoomInfo() // This constructor might help fix my Cassandra Linq bug. { levelNumber = 0; roomNumber = 0; } public RoomInfo(int l, int r) { levelNumber = l; roomNumber = r; } public override bool Equals(object obj) { if (object.ReferenceEquals(this, obj)) { return true; } var otherRoomInfo = obj as RoomInfo; return otherRoomInfo != null && roomNumber == otherRoomInfo.roomNumber && levelNumber == otherRoomInfo.levelNumber; } public override int GetHashCode() { return roomNumber + 1024 * levelNumber; } public override string ToString() { return string.Format("({0}, {1})", levelNumber, roomNumber); } private List<RoomInfo> GeneratePossibleNeighboursOnLevel(LabyrinthGenerator generator, int newLevel) { var result = new List<RoomInfo>(); if (roomNumber == generator.numberOfRoomsPerLevel - 1) { // Rooms with this room number form the central core of the tower. for (int i = 0; i < generator.numberOfRoomsPerLevel - 1; ++i) { result.Add(new RoomInfo(newLevel, i)); } } else { result.Add(new RoomInfo(newLevel, (roomNumber + 1) % (generator.numberOfRoomsPerLevel - 1))); result.Add(new RoomInfo(newLevel, (roomNumber + generator.numberOfRoomsPerLevel - 2) % (generator.numberOfRoomsPerLevel - 1))); result.Add(new RoomInfo(newLevel, generator.numberOfRoomsPerLevel - 1)); } return result; } public List<RoomInfo> GeneratePossibleNeighbours(LabyrinthGenerator generator) { var result = new List<RoomInfo>(); if (levelNumber > 0) { result.AddRange(GeneratePossibleNeighboursOnLevel(generator, levelNumber - 1)); } if (levelNumber < generator.numberOfLevels - 1) { result.AddRange(GeneratePossibleNeighboursOnLevel(generator, levelNumber + 1)); } return result; } } }
30.4
144
0.535453
[ "MIT" ]
tom-weatherhead/3d-labyrinth
c-sharp/LabyrinthMultiDB/LabyrinthMultiDB.Engine/RoomInfo.cs
2,738
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Commands.Storage.Queue { using Commands.Common.Storage.ResourceModel; using Microsoft.WindowsAzure.Commands.Storage.Common; using Microsoft.WindowsAzure.Commands.Storage.Model.Contract; using Microsoft.WindowsAzure.Storage.Queue; using System; using System.Management.Automation; using System.Security.Permissions; [Cmdlet("New", Azure.Commands.ResourceManager.Common.AzureRMConstants.AzurePrefix + "StorageQueue"),OutputType(typeof(AzureStorageQueue))] public class NewAzureStorageQueueCommand : StorageQueueBaseCmdlet { [Alias("N", "Queue")] [Parameter(Position = 0, Mandatory = true, HelpMessage = "Queue name", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string Name { get; set; } /// <summary> /// Initializes a new instance of the GetAzureStorageQueueCommand class. /// </summary> public NewAzureStorageQueueCommand() : this(null) { } /// <summary> /// Initializes a new instance of the NewAzureStorageQueueCommand class. /// </summary> /// <param name="channel">IStorageQueueManagement channel</param> public NewAzureStorageQueueCommand(IStorageQueueManagement channel) { Channel = channel; EnableMultiThread = false; } /// <summary> /// create an azure queue /// </summary> /// <param name="name">queue name</param> /// <returns>an AzureStorageQueue object</returns> internal AzureStorageQueue CreateAzureQueue(string name) { if (!NameUtil.IsValidQueueName(name)) { throw new ArgumentException(String.Format(Resources.InvalidQueueName, name)); } QueueRequestOptions requestOptions = RequestOptions; CloudQueue queue = Channel.GetQueueReference(name); bool created = Channel.CreateQueueIfNotExists(queue, requestOptions, OperationContext); if (!created) { throw new ResourceAlreadyExistException(String.Format(Resources.QueueAlreadyExists, name)); } return new AzureStorageQueue(queue); } /// <summary> /// execute command /// </summary> [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] public override void ExecuteCmdlet() { AzureStorageQueue azureQueue = CreateAzureQueue(Name); WriteObjectWithStorageContext(azureQueue); } } }
40.126437
143
0.607276
[ "MIT" ]
Acidburn0zzz/azure-powershell
src/ResourceManager/Storage/Commands.Storage/Queue/Cmdlet/NewAzureStorageQueue.cs
3,407
C#
using Common.Logging; using Kveer.XBeeApi.Models; using Kveer.XBeeApi.Utils; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Text; namespace Kveer.XBeeApi.Packet.Common { /** * This class represents an AT Command Queue XBee packet. Packet is built * using the parameters of the constructor or providing a valid API payload. * * <p>Used to query or set module parameters on the local device. In contrast * to the {@link ATCommandPacket} API packet, new parameter values are queued * and not applied until either an {@code ATCommandPacket} is sent or the * {@code applyChanges()} method of the {@code XBeeDevice} is issued.</p> * * <p>Register queries (reading parameter values) are returned immediately.</p> * * <p>Command response is received as an {@code ATCommandResponsePacket}.</p> * * @see ATCommandPacket * @see ATCommandResponsePacket * @see com.digi.xbee.api.packet.XBeeAPIPacket */ public class ATCommandQueuePacket : XBeeAPIPacket { // Constants. private const int MIN_API_PAYLOAD_LENGTH = 4; // 1 (Frame type) + 1 (frame ID) + 2 (AT command) /// <summary> /// Gets the AT command. /// </summary> public string Command { get; private set; } /// <summary> /// Gets or sets the AT command parameter. /// </summary> public byte[] Parameter { get; set; } private ILog logger; /** * Creates a new {@code ATCommandQueuePacket} object from the given * payload. * * @param payload The API frame payload. It must start with the frame type * corresponding to a AT Command Queue packet * ({@code 0x09}). The byte array must be in * {@code OperatingMode.API} mode. * * @return Parsed AT Command Queue packet. * * @throws ArgumentException if {@code payload[0] != APIFrameType.AT_COMMAND_QUEUE.getValue()} or * if {@code payload.Length < }{@value #MIN_API_PAYLOAD_LENGTH} or * if {@code frameID < 0} or * if {@code frameID > 255}. * @throws ArgumentNullException if {@code payload == null}. */ public static ATCommandQueuePacket CreatePacket(byte[] payload) { Contract.Requires<ArgumentNullException>(payload != null, "AT Command Queue packet payload cannot be null."); // 1 (Frame type) + 1 (frame ID) + 2 (AT command) Contract.Requires<ArgumentException>(payload.Length >= MIN_API_PAYLOAD_LENGTH, "Incomplete AT Command Queue packet."); Contract.Requires<ArgumentException>((payload[0] & 0xFF) != APIFrameType.AT_COMMAND_QUEUE.GetValue(), "Payload is not an AT Command Queue packet."); // payload[0] is the frame type. int index = 1; // Frame ID byte. byte frameID = payload[index]; index = index + 1; // 2 bytes of AT command, starting at 2nd byte. string command = Encoding.UTF8.GetString(new byte[] { payload[index], payload[index + 1] }); index = index + 2; // Get data. byte[] parameterData = null; if (index < payload.Length) { parameterData = new byte[payload.Length - index]; Array.Copy(payload, index, parameterData, 0, parameterData.Length); //parameterData = Arrays.copyOfRange(payload, index, payload.Length); } return new ATCommandQueuePacket(frameID, command, parameterData); } /** * Class constructor. Instantiates a new {@code ATCommandQueuePacket} * object with the given parameters. * * @param frameID XBee API frame ID. * @param command AT command. * @param parameter AT command parameter as String, {@code null} if it is * not required. * * @throws ArgumentException if {@code frameID < 0} or * if {@code frameID > 255}. * @throws ArgumentNullException if {@code command == null}. */ public ATCommandQueuePacket(byte frameID, String command, String parameter) : this(frameID, command, parameter == null ? null : Encoding.UTF8.GetBytes(parameter)) { } /** * Class constructor. Instantiates a new {@code ATCommandQueuePacket} * object with the given parameters. * * @param frameID XBee API frame ID. * @param command AT command. * @param parameter AT command parameter {@code null} if it is not required. * * @throws ArgumentException if {@code frameID < 0} or * if {@code frameID > 255}. * @throws ArgumentNullException if {@code command == null}. */ public ATCommandQueuePacket(byte frameID, String command, byte[] parameter) : base(APIFrameType.AT_COMMAND_QUEUE) { if (command == null) throw new ArgumentNullException("AT command cannot be null."); this.frameID = frameID; this.Command = command; this.Parameter = parameter; this.logger = LogManager.GetLogger<ATCommandQueuePacket>(); } protected override byte[] APIPacketSpecificData { get { using (MemoryStream os = new MemoryStream()) { try { var rawCmd = Encoding.UTF8.GetBytes(Command); os.Write(rawCmd, 0, rawCmd.Length); if (Parameter != null) os.Write(Parameter, 0, Parameter.Length); } catch (IOException e) { logger.Error(e.Message, e); } return os.ToArray(); } } } public override bool NeedsAPIFrameID { get { return true; } } public string StringParameter { get { if (Parameter == null) return null; return Encoding.UTF8.GetString(Parameter); } set { if (value == null) this.Parameter = null; else this.Parameter = Encoding.UTF8.GetBytes(value); } } public override bool IsBroadcast { get { return false; } } protected override LinkedDictionary<string, string> APIPacketParameters { get { var parameters = new LinkedDictionary<string, string>(); parameters.Add("AT Command", HexUtils.PrettyHexString(HexUtils.ByteArrayToHexString(Encoding.UTF8.GetBytes(Command))) + " (" + Command + ")"); if (Parameter != null) { ATStringCommands cmd; if (Enum.TryParse<ATStringCommands>(Command, out cmd)) parameters.Add("Parameter", HexUtils.PrettyHexString(HexUtils.ByteArrayToHexString(Parameter)) + " (" + Encoding.UTF8.GetString(Parameter) + ")"); else parameters.Add("Parameter", HexUtils.PrettyHexString(HexUtils.ByteArrayToHexString(Parameter))); } return parameters; } } } }
31.924171
153
0.630048
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
LordVeovis/xbee-csharp-library
XBeeLibrary/Packet/Common/ATCommandQueuePacket.cs
6,736
C#
using System; using System.Collections.Generic; using System.Linq; using AutoFixture.NUnit3; using FluentAssertions; using NUnit.Framework; using SFA.DAS.CourseDelivery.Domain.Entities; using SFA.DAS.CourseDelivery.Domain.Models; namespace SFA.DAS.CourseDelivery.Domain.UnitTests.Models { public class WhenMappingFromProviderStandardAndLocationToProviderLocation { [Test, AutoData] public void Then_The_Fields_Are_Correctly_Mapped(string name, int ukprn, string contactUrl, string email, string phone, string tradingName, string marketingInfo, double providerDistanceInMiles, string providerHeadOfficeAddress1, string providerHeadOfficeAddress2, string providerHeadOfficeAddress3, string providerHeadOfficeAddress4, string providerHeadOfficeAddressTown, string providerHeadOfficeAddressPostcode, string standardInfoUrl, Guid? shortlistId, List<ProviderWithStandardAndLocation> providerWithStandardAndLocations) { var actual = new ProviderLocation(ukprn, name, tradingName, contactUrl, phone, email, standardInfoUrl, providerDistanceInMiles, providerHeadOfficeAddress1, providerHeadOfficeAddress2, providerHeadOfficeAddress3, providerHeadOfficeAddress4, providerHeadOfficeAddressTown, providerHeadOfficeAddressPostcode, shortlistId, marketingInfo, providerWithStandardAndLocations); actual.Name.Should().Be(name); actual.TradingName.Should().Be(tradingName); actual.Ukprn.Should().Be(ukprn); actual.ContactUrl.Should().Be(contactUrl); actual.Email.Should().Be(email); actual.Phone.Should().Be(phone); actual.ShortlistId.Should().Be(shortlistId); actual.AchievementRates.Should().NotBeEmpty(); actual.DeliveryTypes.Should().NotBeEmpty(); actual.Address.Address1.Should().Be(providerHeadOfficeAddress1); actual.Address.Address2.Should().Be(providerHeadOfficeAddress2); actual.Address.Address3.Should().Be(providerHeadOfficeAddress3); actual.Address.Address4.Should().Be(providerHeadOfficeAddress4); actual.Address.Town.Should().Be(providerHeadOfficeAddressTown); actual.Address.Postcode.Should().Be(providerHeadOfficeAddressPostcode); actual.Address.DistanceInMiles.Should().Be(providerDistanceInMiles); actual.StandardInfoUrl.Should().Be(standardInfoUrl); actual.MarketingInfo.Should().Be(marketingInfo); actual.DeliveryTypes.ToList().Count.Should().Be(providerWithStandardAndLocations.Count); } } }
45.030769
114
0.667236
[ "MIT" ]
SkillsFundingAgency/das-coursedelivery-api
src/SFA.DAS.CourseDelivery.Domain.UnitTests/Models/WhenMappingFromProviderStandardAndLocationToProviderLocation.cs
2,927
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mina.Core.Buffer; using FSO.Common.Serialization; namespace FSO.Server.Protocol.Voltron.Packets { public class ClientByePDU : AbstractVoltronPacket { public uint ReasonCode; public string ReasonText; public byte RequestTicket; public override void Deserialize(IoBuffer input, ISerializationContext context) { this.ReasonCode = input.GetUInt32(); this.ReasonText = input.GetPascalString(); this.RequestTicket = input.Get(); } public override VoltronPacketType GetPacketType() { return VoltronPacketType.ClientByePDU; } public override void Serialize(IoBuffer output, ISerializationContext context) { var text = ReasonText; if(text == null){ text = ""; } output.PutUInt32(ReasonCode); output.PutPascalString(text); output.Put(RequestTicket); } } }
26.904762
87
0.617699
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Blayer98/FreeSO
TSOClient/FSO.Server.Protocol/Voltron/Packets/ClientByePDU.cs
1,132
C#
using ARMeilleure.Decoders; using ARMeilleure.IntermediateRepresentation; using ARMeilleure.State; using ARMeilleure.Translation; using System; using static ARMeilleure.Instructions.InstEmitHelper; using static ARMeilleure.IntermediateRepresentation.OperandHelper; namespace ARMeilleure.Instructions { static partial class InstEmit { private const int DczSizeLog2 = 4; public static void Hint(ArmEmitterContext context) { // Execute as no-op. } public static void Isb(ArmEmitterContext context) { // Execute as no-op. } public static void Mrs(ArmEmitterContext context) { OpCodeSystem op = (OpCodeSystem)context.CurrOp; Delegate dlg; switch (GetPackedId(op)) { case 0b11_011_0000_0000_001: dlg = new _U64(NativeInterface.GetCtrEl0); break; case 0b11_011_0000_0000_111: dlg = new _U64(NativeInterface.GetDczidEl0); break; case 0b11_011_0100_0010_000: EmitGetNzcv(context); return; case 0b11_011_0100_0100_000: dlg = new _U64(NativeInterface.GetFpcr); break; case 0b11_011_0100_0100_001: dlg = new _U64(NativeInterface.GetFpsr); break; case 0b11_011_1101_0000_010: dlg = new _U64(NativeInterface.GetTpidrEl0); break; case 0b11_011_1101_0000_011: dlg = new _U64(NativeInterface.GetTpidr); break; case 0b11_011_1110_0000_000: dlg = new _U64(NativeInterface.GetCntfrqEl0); break; case 0b11_011_1110_0000_001: dlg = new _U64(NativeInterface.GetCntpctEl0); break; default: throw new NotImplementedException($"Unknown MRS 0x{op.RawOpCode:X8} at 0x{op.Address:X16}."); } SetIntOrZR(context, op.Rt, context.Call(dlg)); } public static void Msr(ArmEmitterContext context) { OpCodeSystem op = (OpCodeSystem)context.CurrOp; Delegate dlg; switch (GetPackedId(op)) { case 0b11_011_0100_0010_000: EmitSetNzcv(context); return; case 0b11_011_0100_0100_000: dlg = new _Void_U64(NativeInterface.SetFpcr); break; case 0b11_011_0100_0100_001: dlg = new _Void_U64(NativeInterface.SetFpsr); break; case 0b11_011_1101_0000_010: dlg = new _Void_U64(NativeInterface.SetTpidrEl0); break; default: throw new NotImplementedException($"Unknown MSR 0x{op.RawOpCode:X8} at 0x{op.Address:X16}."); } context.Call(dlg, GetIntOrZR(context, op.Rt)); } public static void Nop(ArmEmitterContext context) { // Do nothing. } public static void Sys(ArmEmitterContext context) { // This instruction is used to do some operations on the CPU like cache invalidation, // address translation and the like. // We treat it as no-op here since we don't have any cache being emulated anyway. OpCodeSystem op = (OpCodeSystem)context.CurrOp; switch (GetPackedId(op)) { case 0b11_011_0111_0100_001: { // DC ZVA Operand t = GetIntOrZR(context, op.Rt); for (long offset = 0; offset < (4 << DczSizeLog2); offset += 8) { Operand address = context.Add(t, Const(offset)); context.Call(new _Void_U64_U64(NativeInterface.WriteUInt64), address, Const(0L)); } break; } // No-op case 0b11_011_0111_1110_001: //DC CIVAC break; } } private static int GetPackedId(OpCodeSystem op) { int id; id = op.Op2 << 0; id |= op.CRm << 3; id |= op.CRn << 7; id |= op.Op1 << 11; id |= op.Op0 << 14; return id; } private static void EmitGetNzcv(ArmEmitterContext context) { OpCodeSystem op = (OpCodeSystem)context.CurrOp; Operand vSh = context.ShiftLeft(GetFlag(PState.VFlag), Const((int)PState.VFlag)); Operand cSh = context.ShiftLeft(GetFlag(PState.CFlag), Const((int)PState.CFlag)); Operand zSh = context.ShiftLeft(GetFlag(PState.ZFlag), Const((int)PState.ZFlag)); Operand nSh = context.ShiftLeft(GetFlag(PState.NFlag), Const((int)PState.NFlag)); Operand nzcvSh = context.BitwiseOr(context.BitwiseOr(nSh, zSh), context.BitwiseOr(cSh, vSh)); SetIntOrZR(context, op.Rt, nzcvSh); } private static void EmitSetNzcv(ArmEmitterContext context) { OpCodeSystem op = (OpCodeSystem)context.CurrOp; Operand t = GetIntOrZR(context, op.Rt); t = context.ConvertI64ToI32(t); Operand v = context.ShiftRightUI(t, Const((int)PState.VFlag)); v = context.BitwiseAnd (v, Const(1)); Operand c = context.ShiftRightUI(t, Const((int)PState.CFlag)); c = context.BitwiseAnd (c, Const(1)); Operand z = context.ShiftRightUI(t, Const((int)PState.ZFlag)); z = context.BitwiseAnd (z, Const(1)); Operand n = context.ShiftRightUI(t, Const((int)PState.NFlag)); n = context.BitwiseAnd (n, Const(1)); SetFlag(context, PState.VFlag, v); SetFlag(context, PState.CFlag, c); SetFlag(context, PState.ZFlag, z); SetFlag(context, PState.NFlag, n); } } }
37.242038
118
0.573114
[ "MIT" ]
AidanXu/Ryujinx
ARMeilleure/Instructions/InstEmitSystem.cs
5,847
C#
using System.Collections.Generic; public class UhpPin { public enum IOMode { IN, OUT, INOUT } public const string JSON_NAME_KEY = "name"; public const string JSON_MODE_KEY = "mode"; public const string JSON_TYPE_KEY = "type"; public const string JSON_MNEMONIC_KEY = "mnemonic"; public const string JSON_DESCRIPTION_KEY = "description"; public string name { get; set; } public IOMode mode { get; set; } public UhpType type { get; set; } public string mnemonic { get; set; } public string description { get; set; } public IDictionary<string, object> ToJSON() { var json = new Dictionary<string, object>(); if (name != null) json[JSON_NAME_KEY] = name; json[JSON_MODE_KEY] = mode.ToString(); if (type != null) json[JSON_TYPE_KEY] = type.ToJSON(); if (mnemonic != null) json[JSON_MNEMONIC_KEY] = mnemonic; if (description != null) json[JSON_DESCRIPTION_KEY] = description; return json; } public override bool Equals(object obj) { if (obj == this) return true; if (!(obj is UhpPin)) return false; UhpPin other = (UhpPin)obj; if (!object.Equals(this.name, other.name)) return false; if (!object.Equals(this.mode, other.mode)) return false; if (!object.Equals(this.type, other.type)) return false; if (!object.Equals(this.mnemonic, other.mnemonic)) return false; if (!object.Equals(this.description, other.description)) return false; return true; } public override int GetHashCode() { int hash = 0; hash ^= (name != null) ? name.GetHashCode() : 0; hash ^= mode.GetHashCode(); hash ^= (type != null) ? type.GetHashCode() : 0; hash ^= (mnemonic != null) ? mnemonic.GetHashCode() : 0; hash ^= (description != null) ? description.GetHashCode() : 0; return hash; } public override string ToString() { return MiniJSON.Json.Serialize(ToJSON()); } }
29.026667
70
0.575563
[ "Apache-2.0" ]
UnBiHealth/fisiogame
Assets/Script/Drivers/Pin/UhpPin.cs
2,179
C#
using System; using EventSourcingPoc.EventSourcing.Exceptions; namespace EventSourcingPoc.EventSourcing.Domain { public struct StreamIdentifier { public StreamIdentifier(string name, Guid id) { if (string.IsNullOrWhiteSpace(name)) throw new StreamIdentifierException("StreamIdentifier Name Required"); if(id == Guid.Empty) throw new StreamIdentifierException("StreamIdentifier Id Required"); Value = $"{name}-{id}"; } public string Value { get; } } }
28.157895
119
0.671028
[ "MIT" ]
Coilz/event-sourcing-poc
src/EventSourcingPoc.EventSourcing/Domain/StreamIdentifier.cs
537
C#
using System.Collections.Generic; using VkNet.Utils; namespace VkNet.Model.RequestParams { /// <summary> /// Параметры метода audio.get /// </summary> public struct AudioGetParams { /// <summary> /// Параметры метода audio.get /// </summary> /// <param name="gag">Заглушка для конструктора.</param> public AudioGetParams(bool gag = true) { OwnerId = null; AlbumId = null; AudioIds = null; NeedUser = null; Offset = null; Count = null; } /// <summary> /// Идентификатор владельца аудиозаписей (пользователь или сообщество). Обратите внимание, идентификатор сообщества в параметре owner_id необходимо указывать со знаком "-" — например, owner_id=-1 соответствует идентификатору сообщества ВКонтакте API (club1) целое число, по умолчанию идентификатор текущего пользователя. /// </summary> public long? OwnerId { get; set; } /// <summary> /// Идентификатор альбома с аудиозаписями. целое число. /// </summary> public long? AlbumId { get; set; } /// <summary> /// Идентификаторы аудиозаписей, информацию о которых необходимо вернуть. список положительных чисел, разделенных запятыми. /// </summary> public IEnumerable<long> AudioIds { get; set; } /// <summary> /// 1 — возвращать информацию о пользователях, загрузивших аудиозапись. флаг, может принимать значения 1 или 0. /// </summary> public bool? NeedUser { get; set; } /// <summary> /// Смещение, необходимое для выборки определенного количества аудиозаписей. По умолчанию — 0. положительное число. /// </summary> public long? Offset { get; set; } /// <summary> /// Количество аудиозаписей, информацию о которых необходимо вернуть. Максимальное значение — 6000. положительное число. /// </summary> public long? Count { get; set; } /// <summary> /// Привести к типу VkParameters. /// </summary> /// <param name="p">Параметры.</param> /// <returns></returns> public static VkParameters ToVkParameters(AudioGetParams p) { var parameters = new VkParameters { { "owner_id", p.OwnerId }, { "album_id", p.AlbumId }, { "audio_ids", p.AudioIds }, { "need_user", p.NeedUser }, { "offset", p.Offset }, { "count", p.Count } }; return parameters; } } }
29.853333
323
0.673068
[ "MIT" ]
uid17/VK
VkNet/Model/RequestParams/Audio/AudioGetParams.cs
2,988
C#
using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models.Editors; using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { /// <summary> /// Represents a media picker property editor. /// Marked as Deprecated as best to use the NEW Media Picker aka MediaPicker3 /// </summary> [DataEditor( Constants.PropertyEditors.Aliases.MediaPicker, EditorType.PropertyValue | EditorType.MacroParameter, "(Obsolete) Media Picker", "mediapicker", ValueType = ValueTypes.Text, Group = Constants.PropertyEditors.Groups.Media, Icon = Constants.Icons.MediaImage, IsDeprecated = true)] public class MediaPickerPropertyEditor : DataEditor { /// <summary> /// Initializes a new instance of the <see cref="MediaPickerPropertyEditor"/> class. /// </summary> public MediaPickerPropertyEditor(ILogger logger) : base(logger) { } /// <inheritdoc /> protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPickerConfigurationEditor(); protected override IDataValueEditor CreateValueEditor() => new MediaPickerPropertyValueEditor(Attribute); internal class MediaPickerPropertyValueEditor : DataValueEditor, IDataValueReference { public MediaPickerPropertyValueEditor(DataEditorAttribute attribute) : base(attribute) { } public IEnumerable<UmbracoEntityReference> GetReferences(object value) { var asString = value is string str ? str : value?.ToString(); if (string.IsNullOrEmpty(asString)) yield break; foreach (var udiStr in asString.Split(Constants.CharArrays.Comma)) { if (Udi.TryParse(udiStr, out var udi)) yield return new UmbracoEntityReference(udi); } } } } }
33.508197
116
0.638943
[ "MIT" ]
JoseMarcenaro/Umbraco-CMS
src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs
2,046
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Xml.Linq; namespace DocumentFormat.OpenXml.Linq { /// <summary> /// Declares XNamespace and XName fields for the xmlns:x15ac="http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac" namespace. /// </summary> public static class X15AC { /// <summary> /// Defines the XML namespace associated with the x15ac prefix. /// </summary> public static readonly XNamespace x15ac = "http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac"; /// <summary> /// Represents the x15ac:absPath XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="X.workbook" />.</description></item> /// <item><description>has the following XML attributes: <see cref="NoNamespace.url" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: AbsolutePath.</description></item> /// </list> /// </remarks> public static readonly XName absPath = x15ac + "absPath"; } }
41.6875
138
0.64018
[ "MIT" ]
929496959/Open-XML-SDK
src/DocumentFormat.OpenXml.Linq/GeneratedCode/X15AC.g.cs
1,334
C#