content
stringlengths
23
1.05M
namespace Serenity.TypeScript.TsTypes { [Flags] public enum NodeFlags { None = 0, Let = 1 << 0, // Variable declaration Const = 1 << 1, // Variable declaration NestedNamespace = 1 << 2, // Namespace declaration Synthesized = 1 << 3, // Node was synthesized during transformation Namespace = 1 << 4, // Namespace declaration ExportContext = 1 << 5, // Export context (initialized by binding) ContainsThis = 1 << 6, // Interface contains references to "this" HasImplicitReturn = 1 << 7, // If function implicitly returns on one of codepaths (initialized by binding) HasExplicitReturn = 1 << 8, // If function has explicit reachable return on one of codepaths (initialized by binding) GlobalAugmentation = 1 << 9, // Set if module declaration is an augmentation for the global scope HasAsyncFunctions = 1 << 10, // If the file has async functions (initialized by binding) DisallowInContext = 1 << 11, // If node was parsed in a context where 'in-expressions' are not allowed YieldContext = 1 << 12, // If node was parsed in the 'yield' context created when parsing a generator DecoratorContext = 1 << 13, // If node was parsed as part of a decorator AwaitContext = 1 << 14, // If node was parsed in the 'await' context created when parsing an async function ThisNodeHasError = 1 << 15, // If the parser encountered an error when parsing the code that created this node JavaScriptFile = 1 << 16, // If node was parsed in a JavaScript ThisNodeOrAnySubNodesHasError = 1 << 17, // If this node or any of its children had an error HasAggregatedChildData = 1 << 18, // If we've computed data from children and cached it in this node BlockScoped = Let | Const, ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn, ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions, // Parsing context flags ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile, // Exclude these flags when parsing a Type TypeExcludesFlags = YieldContext | AwaitContext } public enum ParsingContext { SourceElements, // Elements in source file BlockStatements, // Statements in block SwitchClauses, // Clauses in switch statement SwitchClauseStatements, // Statements in switch clause TypeMembers, // Members in interface or type literal ClassMembers, // Members in class declaration EnumMembers, // Members in enum declaration HeritageClauseElement, // Elements in a heritage clause VariableDeclarations, // Variable declarations in variable statement ObjectBindingElements, // Binding elements in object binding list ArrayBindingElements, // Binding elements in array binding list ArgumentExpressions, // Expressions in argument list ObjectLiteralMembers, // Members in object literal JsxAttributes, // Attributes in jsx element JsxChildren, // Things between opening and closing JSX tags ArrayLiteralMembers, // Members in array literal Parameters, // Parameters in parameter list RestProperties, // Property names in a rest type list TypeParameters, // Type parameters in type parameter list TypeArguments, // Type arguments in type argument list TupleElementTypes, // Element types in tuple element type list HeritageClauses, // Heritage clauses for a class or interface declaration. ImportOrExportSpecifiers, // Named import clause's import specifier list JSDocFunctionParameters, JSDocTypeArguments, JSDocRecordMembers, JSDocTupleTypes, Count // Number of parsing contexts } public enum Tristate { False, True, Unknown } public enum JSDocState { BeginningOfLine, SawAsterisk, SavingComments } public enum ModifierFlags { None = 0, Export = 1 << 0, // Declarations Ambient = 1 << 1, // Declarations Public = 1 << 2, // Property/Method Private = 1 << 3, // Property/Method Protected = 1 << 4, // Property/Method Static = 1 << 5, // Property/Method Readonly = 1 << 6, // Property/Method Abstract = 1 << 7, // Class/Method/ConstructSignature Async = 1 << 8, // Property/Method/Function Default = 1 << 9, // Function/Class (export default declaration) Const = 1 << 11, // Variable declaration HasComputedFlags = 1 << 29, // Modifier flags have been computed AccessibilityModifier = Public | Private | Protected, // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. ParameterPropertyModifier = AccessibilityModifier | Readonly, NonPublicAccessibilityModifier = Private | Protected, TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const, ExportDefault = Export | Default } public enum JsxFlags { None = 0, /** An element from a named property of the JSX.IntrinsicElements interface */ IntrinsicNamedElement = 1 << 0, /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 1 << 1, IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement } public enum RelationComparisonResult { Succeeded = 1, // Should be truthy Failed = 2, FailedAndReported = 3 } public enum GeneratedIdentifierKind { None, // Not automatically generated. Auto, // Automatically generated identifier. Loop, // Automatically generated identifier with a preference for '_i'. Unique, // Unique name based on the 'text' property. Node // Unique name based on the node in the 'original' property. } public enum FlowFlags { Unreachable = 1 << 0, // Unreachable code Start = 1 << 1, // Start of flow graph BranchLabel = 1 << 2, // Non-looping junction LoopLabel = 1 << 3, // Looping junction Assignment = 1 << 4, // Assignment TrueCondition = 1 << 5, // Condition known to be true FalseCondition = 1 << 6, // Condition known to be false SwitchClause = 1 << 7, // Switch statement clause ArrayMutation = 1 << 8, // Potential array mutation Referenced = 1 << 9, // Referenced as antecedent once Shared = 1 << 10, // Referenced as antecedent more than once PreFinally = 1 << 11, // Injected edge that links pre-finally label and pre-try flow AfterFinally = 1 << 12, // Injected edge that links post-finally flow with the rest of the graph Label = BranchLabel | LoopLabel, Condition = TrueCondition | FalseCondition } public enum ExitStatus { // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, // when -version or -help was provided, or this was a normal compilation, no diagnostics // were produced, and all outputs were generated successfully. Success = 0, // Diagnostics were produced and because of them no code was generated. DiagnosticsPresentOutputsSkipped = 1, // Diagnostics were produced and outputs were generated in spite of them. DiagnosticsPresentOutputsGenerated = 2 } public enum NodeBuilderFlags { None = 0, AllowThisInObjectLiteral = 1 << 0, AllowQualifedNameInPlaceOfIdentifier = 1 << 1, AllowTypeParameterInQualifiedName = 1 << 2, AllowAnonymousIdentifier = 1 << 3, AllowEmptyUnionOrIntersection = 1 << 4, AllowEmptyTuple = 1 << 5 } public enum TypeFormatFlags { None = 0x00000000, WriteArrayAsGenericType = 0x00000001, // Write Array<T> instead T[] UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal NoTruncation = 0x00000004, // Don't truncate typeToString result WriteArrowStyleSignature = 0x00000008, // Write arrow style signature WriteOwnNameForAnyLike = 0x00000010, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature InElementType = 0x00000040, // Writing an array or union element type UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type) InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type InTypeAlias = 0x00000200, // Writing type in type alias declaration UseTypeAliasValue = 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type. AddUndefined = 0x00001000 // Add undefined to types of initialized, non-optional parameters } public enum SymbolFormatFlags { None = 0x00000000, // Write symbols's type argument if it is instantiated symbol // eg. class C<T> { p: T } <-- Show p as C<T>.p here // var a: C<number>; // var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p WriteTypeParametersOrArguments = 0x00000001, // Use only external alias information to get the symbol name in the given context // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x UseOnlyExternalAliasing = 0x00000002 } public enum SymbolAccessibility { Accessible, NotAccessible, CannotBeNamed } public enum SyntheticSymbolKind { UnionOrIntersection, Spread } public enum TypePredicateKind { This, Identifier } public enum TypeReferenceSerializationKind { Unknown, // The TypeReferenceNode could not be resolved. The type name // should be emitted using a safe fallback. TypeWithConstructSignatureAndValue, // The TypeReferenceNode resolves to a type with a constructor // function that can be reached at runtime (e.g. a `class` // declaration or a `var` declaration for the static side // of a type, such as the global `Promise` type in lib.d.ts). VoidNullableOrNeverType, // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type. NumberLikeType, // The TypeReferenceNode resolves to a Number-like type. StringLikeType, // The TypeReferenceNode resolves to a String-like type. BooleanType, // The TypeReferenceNode resolves to a Boolean-like type. ArrayLikeType, // The TypeReferenceNode resolves to an Array-like type. EsSymbolType, // The TypeReferenceNode resolves to the ESSymbol type. Promise, // The TypeReferenceNode resolved to the global Promise constructor symbol. TypeWithCallSignature, // The TypeReferenceNode resolves to a Function type or a type // with call signatures. ObjectType // The TypeReferenceNode resolves to any other type. } public enum SymbolFlags { None = 0, FunctionScopedVariable = 1 << 0, // Variable (var) or parameter BlockScopedVariable = 1 << 1, // A block-scoped variable (let or const) Property = 1 << 2, // Property or enum member EnumMember = 1 << 3, // Enum member Function = 1 << 4, // Function Class = 1 << 5, // Class Interface = 1 << 6, // Interface ConstEnum = 1 << 7, // Const enum RegularEnum = 1 << 8, // Enum ValueModule = 1 << 9, // Instantiated module NamespaceModule = 1 << 10, // Uninstantiated module TypeLiteral = 1 << 11, // Type Literal or mapped type ObjectLiteral = 1 << 12, // Object Literal Method = 1 << 13, // Method Constructor = 1 << 14, // Constructor GetAccessor = 1 << 15, // Get accessor SetAccessor = 1 << 16, // Set accessor Signature = 1 << 17, // Call, construct, or index signature TypeParameter = 1 << 18, // Type parameter TypeAlias = 1 << 19, // Type alias ExportValue = 1 << 20, // Exported value marker (see comment in declareModuleMember in binder) ExportType = 1 << 21, // Exported type marker (see comment in declareModuleMember in binder) ExportNamespace = 1 << 22, // Exported namespace marker (see comment in declareModuleMember in binder) Alias = 1 << 23, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker) Prototype = 1 << 24, // Prototype property (no source representation) ExportStar = 1 << 25, // Export * declaration Optional = 1 << 26, // Optional property Transient = 1 << 27, // Transient symbol (created during type check) Enum = RegularEnum | ConstEnum, Variable = FunctionScopedVariable | BlockScopedVariable, Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor, Type = Class | Interface | Enum | EnumMember | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias, Namespace = ValueModule | NamespaceModule | Enum, Module = ValueModule | NamespaceModule, Accessor = GetAccessor | SetAccessor, // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class FunctionScopedVariableExcludes = Value & ~FunctionScopedVariable, // Block-scoped declarations are not allowed to be re-declared // they can not merge with anything in the value space BlockScopedVariableExcludes = Value, ParameterExcludes = Value, PropertyExcludes = None, EnumMemberExcludes = Value | Type, FunctionExcludes = Value & ~(Function | ValueModule), ClassExcludes = (Value | Type) & ~(ValueModule | Interface), // class-interface mergability done in checker.ts InterfaceExcludes = Type & ~(Interface | Class), RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule), NamespaceModuleExcludes = 0, MethodExcludes = Value & ~Method, GetAccessorExcludes = Value & ~SetAccessor, SetAccessorExcludes = Value & ~GetAccessor, TypeParameterExcludes = Type & ~TypeParameter, TypeAliasExcludes = Type, AliasExcludes = Alias, ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Alias, ExportHasLocal = Function | Class | Enum | ValueModule, HasExports = Class | Enum | Module, HasMembers = Class | Interface | TypeLiteral | ObjectLiteral, BlockScoped = BlockScopedVariable | Class | Enum, PropertyOrAccessor = Property | Accessor, Export = ExportNamespace | ExportType | ExportValue, ClassMember = Method | Accessor | Property, /* @internal */ // The set of things we consider semantically classifiable. Used to speed up the LS during // classification. Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module } public enum CheckFlags { Instantiated = 1 << 0, // Instantiated symbol SyntheticProperty = 1 << 1, // Property in union or intersection type SyntheticMethod = 1 << 2, // Method in union or intersection type Readonly = 1 << 3, // Readonly transient symbol Partial = 1 << 4, // Synthetic property present in some but not all constituents HasNonUniformType = 1 << 5, // Synthetic property with non-uniform type in constituents ContainsPublic = 1 << 6, // Synthetic property with public constituent(s) ContainsProtected = 1 << 7, // Synthetic property with protected constituent(s) ContainsPrivate = 1 << 8, // Synthetic property with private constituent(s) ContainsStatic = 1 << 9, // Synthetic property with static constituent(s) Synthetic = SyntheticProperty | SyntheticMethod } public enum NodeCheckFlags { TypeChecked = 0x00000001, // Node has been type checked LexicalThis = 0x00000002, // Lexical 'this' reference CaptureThis = 0x00000004, // Lexical 'this' used in body CaptureNewTarget = 0x00000008, // Lexical 'new.target' used in body SuperInstance = 0x00000100, // Instance 'super' reference SuperStatic = 0x00000200, // Static 'super' reference ContextChecked = 0x00000400, // Contextual types have been assigned AsyncMethodWithSuper = 0x00000800, // An async method that reads a value from a member of 'super'. AsyncMethodWithSuperBinding = 0x00001000, // An async method that assigns a value to a member of 'super'. CaptureArguments = 0x00002000, // Lexical 'arguments' used in body (for async functions) EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them. LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration. LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function BlockScopedBindingInLoop = 0x00040000, // Block-scoped binding with declaration nested inside iteration statement ClassWithBodyScopedClassBinding = 0x00080000, // Decorated class that contains a binding to itself inside of the class body. BodyScopedClassBinding = 0x00100000, // Binding to a decorated class inside of the class's body. NeedsLoopOutParameter = 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop AssignmentsMarked = 0x00400000, // Parameter assignments have been marked ClassWithConstructorReference = 0x00800000, // Class that contains a binding to its constructor inside of the class body. ConstructorReferenceInClass = 0x01000000 // Binding to a class constructor inside of the class's body. } public enum TypeFlags { Any = 1 << 0, String = 1 << 1, Number = 1 << 2, Boolean = 1 << 3, Enum = 1 << 4, StringLiteral = 1 << 5, NumberLiteral = 1 << 6, BooleanLiteral = 1 << 7, EnumLiteral = 1 << 8, EsSymbol = 1 << 9, // Type of symbol primitive introduced in ES6 Void = 1 << 10, Undefined = 1 << 11, Null = 1 << 12, Never = 1 << 13, // Never type TypeParameter = 1 << 14, // Type parameter Object = 1 << 15, // Object type Union = 1 << 16, // Union (T | U) Intersection = 1 << 17, // Intersection (T & U) Index = 1 << 18, // keyof T IndexedAccess = 1 << 19, // T[K] /* @internal */ FreshLiteral = 1 << 20, // Fresh literal type /* @internal */ ContainsWideningType = 1 << 21, // Type is or contains undefined or null widening type /* @internal */ ContainsObjectLiteral = 1 << 22, // Type is or contains object literal type /* @internal */ ContainsAnyFunctionType = 1 << 23, // Type is or contains object literal type NonPrimitive = 1 << 24, // intrinsic object type /* @internal */ JsxAttributes = 1 << 25, // Jsx attributes type /* @internal */ Nullable = Undefined | Null, Literal = StringLiteral | NumberLiteral | BooleanLiteral | EnumLiteral, StringOrNumberLiteral = StringLiteral | NumberLiteral, /* @internal */ DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null, PossiblyFalsy = DefinitelyFalsy | String | Number | Boolean, /* @internal */ Intrinsic = Any | String | Number | Boolean | BooleanLiteral | EsSymbol | Void | Undefined | Null | Never | NonPrimitive, /* @internal */ Primitive = String | Number | Boolean | Enum | EsSymbol | Void | Undefined | Null | Literal, StringLike = String | StringLiteral | Index, NumberLike = Number | NumberLiteral | Enum | EnumLiteral, BooleanLike = Boolean | BooleanLiteral, EnumLike = Enum | EnumLiteral, UnionOrIntersection = Union | Intersection, StructuredType = Object | Union | Intersection, StructuredOrTypeVariable = StructuredType | TypeParameter | Index | IndexedAccess, TypeVariable = TypeParameter | IndexedAccess, // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never Narrowable = Any | StructuredType | TypeParameter | Index | IndexedAccess | StringLike | NumberLike | BooleanLike | EsSymbol | NonPrimitive, NotUnionOrUnit = Any | EsSymbol | Object | NonPrimitive, /* @internal */ RequiresWidening = ContainsWideningType | ContainsObjectLiteral, /* @internal */ PropagatingFlags = ContainsWideningType | ContainsObjectLiteral | ContainsAnyFunctionType } public enum ObjectFlags { Class = 1 << 0, // Class Interface = 1 << 1, // Interface Reference = 1 << 2, // Generic type reference Tuple = 1 << 3, // Synthesized generic tuple type Anonymous = 1 << 4, // Anonymous Mapped = 1 << 5, // Mapped Instantiated = 1 << 6, // Instantiated anonymous or mapped type ObjectLiteral = 1 << 7, // Originates in an object literal EvolvingArray = 1 << 8, // Evolving array type ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties ClassOrInterface = Class | Interface } public enum SignatureKind { Call, Construct } public enum IndexKind { String, Number } public enum SpecialPropertyAssignmentKind { None, /// exports.name = expr ExportsProperty, /// module.exports = expr ModuleExports, /// className.prototype.name = expr PrototypeProperty, /// this.name = expr ThisProperty, // F.name = expr Property } public enum DiagnosticCategory { Warning, Error, Message, Unknown } public enum ModuleResolutionKind { Classic = 1, NodeJs = 2 } public enum ModuleKind { None = 0, CommonJs = 1, Amd = 2, Umd = 3, System = 4, Es2015 = 5 } public enum JsxEmit { None = 0, Preserve = 1, React = 2, ReactNative = 3 } public enum NewLineKind { CarriageReturnLineFeed = 0, LineFeed = 1 } public enum ScriptKind { Unknown = 0, Js = 1, Jsx = 2, Ts = 3, Tsx = 4, External = 5 } public enum LanguageVariant { Standard, Jsx } public enum DiagnosticStyle { Simple, Pretty } public enum WatchDirectoryFlags { None = 0, Recursive = 1 << 0 } public enum CharacterCodes { MaxAsciiCharacter = 0x7F, LineSeparator = 0x2028, ParagraphSeparator = 0x2029, NextLine = 0x0085, NonBreakingSpace = 0x00A0, EnQuad = 0x2000, EmQuad = 0x2001, EnSpace = 0x2002, EmSpace = 0x2003, ThreePerEmSpace = 0x2004, FourPerEmSpace = 0x2005, SixPerEmSpace = 0x2006, FigureSpace = 0x2007, PunctuationSpace = 0x2008, ThinSpace = 0x2009, HairSpace = 0x200A, ZeroWidthSpace = 0x200B, NarrowNoBreakSpace = 0x202F, IdeographicSpace = 0x3000, MathematicalSpace = 0x205F, Ogham = 0x1680, ByteOrderMark = 0xFEFF, } public enum Extension { Ts, Tsx, Dts, Js, Jsx, LastTypeScriptExtension = Dts } public enum TransformFlags { None = 0, // Facts // - Flags used to indicate that a node or subtree contains syntax that requires transformation. TypeScript = 1 << 0, ContainsTypeScript = 1 << 1, ContainsJsx = 1 << 2, ContainsEsNext = 1 << 3, ContainsEs2017 = 1 << 4, ContainsEs2016 = 1 << 5, Es2015 = 1 << 6, ContainsEs2015 = 1 << 7, Generator = 1 << 8, ContainsGenerator = 1 << 9, DestructuringAssignment = 1 << 10, ContainsDestructuringAssignment = 1 << 11, // Markers // - Flags used to indicate that a subtree contains a specific transformation. ContainsDecorators = 1 << 12, ContainsPropertyInitializer = 1 << 13, ContainsLexicalThis = 1 << 14, ContainsCapturedLexicalThis = 1 << 15, ContainsLexicalThisInComputedPropertyName = 1 << 16, ContainsDefaultValueAssignments = 1 << 17, ContainsParameterPropertyAssignments = 1 << 18, ContainsSpread = 1 << 19, ContainsObjectSpread = 1 << 20, ContainsRest = ContainsSpread, ContainsObjectRest = ContainsObjectSpread, ContainsComputedPropertyName = 1 << 21, ContainsBlockScopedBinding = 1 << 22, ContainsBindingPattern = 1 << 23, ContainsYield = 1 << 24, ContainsHoistedDeclarationOrCompletion = 1 << 25, HasComputedFlags = 1 << 29, // Transform flags have been computed. // Assertions // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. AssertTypeScript = TypeScript | ContainsTypeScript, AssertJsx = ContainsJsx, AssertEsNext = ContainsEsNext, AssertEs2017 = ContainsEs2017, AssertEs2016 = ContainsEs2016, AssertEs2015 = Es2015 | ContainsEs2015, AssertGenerator = Generator | ContainsGenerator, AssertDestructuringAssignment = DestructuringAssignment | ContainsDestructuringAssignment, // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. NodeExcludes = TypeScript | Es2015 | DestructuringAssignment | Generator | HasComputedFlags, ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsComputedPropertyName | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName, ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion, TypeExcludes = ~ContainsTypeScript, ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | ContainsLexicalThisInComputedPropertyName | ContainsObjectSpread, ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpread, VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRest, ParameterExcludes = NodeExcludes, CatchClauseExcludes = NodeExcludes | ContainsObjectRest, BindingPatternExcludes = NodeExcludes | ContainsRest, // Masks // - Additional bitmasks TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | ContainsDecorators, Es2015FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments } public enum EmitFlags { SingleLine = 1 << 0, // The contents of this node should be emitted on a single line. AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node. NoSubstitution = 1 << 2, // Disables further substitution of an expression. CapturesThis = 1 << 3, // The function captures a lexical `this` NoLeadingSourceMap = 1 << 4, // Do not emit a leading source map location for this node. NoTrailingSourceMap = 1 << 5, // Do not emit a trailing source map location for this node. NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node. NoNestedSourceMaps = 1 << 6, // Do not emit source map locations for children of this node. NoTokenLeadingSourceMaps = 1 << 7, // Do not emit leading source map location for token nodes. NoTokenTrailingSourceMaps = 1 << 8, // Do not emit trailing source map location for token nodes. NoTokenSourceMaps = NoTokenLeadingSourceMaps | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node. NoLeadingComments = 1 << 9, // Do not emit leading comments for this node. NoTrailingComments = 1 << 10, // Do not emit trailing comments for this node. NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node. NoNestedComments = 1 << 11, HelperName = 1 << 12, ExportName = 1 << 13, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal). LocalName = 1 << 14, // Ensure an export prefix is not added for an identifier that points to an exported declaration. Indented = 1 << 15, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter). NoIndentation = 1 << 16, // Do not indent the node. AsyncFunctionBody = 1 << 17, ReuseTempVariableScope = 1 << 18, // Reuse the existing temp variable scope during emit. CustomPrologue = 1 << 19, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed). NoHoisting = 1 << 20, // Do not hoist this declaration in --module system HasEndOfDeclarationMarker = 1 << 21 // Declaration has an associated NotEmittedStatement to mark the end of the declaration } public enum ExternalEmitHelpers { Extends = 1 << 0, // __extends (used by the ES2015 class transformation) Assign = 1 << 1, // __assign (used by Jsx and ESNext object spread transformations) Rest = 1 << 2, // __rest (used by ESNext object rest transformation) Decorate = 1 << 3, // __decorate (used by TypeScript decorators transformation) Metadata = 1 << 4, // __metadata (used by TypeScript decorators transformation) Param = 1 << 5, // __param (used by TypeScript decorators transformation) Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation) Generator = 1 << 7, // __generator (used by ES2015 generator transformation) Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations) Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) Spread = 1 << 10, // __spread (used by ES2015 array spread and argument list spread transformations) AsyncGenerator = 1 << 11, // __asyncGenerator (used by ES2017 async generator transformation) AsyncDelegator = 1 << 12, // __asyncDelegator (used by ES2017 async generator yield* transformation) AsyncValues = 1 << 13, // __asyncValues (used by ES2017 for..await..of transformation) // Helpers included by ES2015 for..of ForOfIncludes = Values, // Helpers included by ES2017 for..await..of ForAwaitOfIncludes = AsyncValues, // Helpers included by ES2015 spread SpreadIncludes = Read | Spread, FirstEmitHelper = Extends, LastEmitHelper = AsyncValues } public enum EmitHint { SourceFile, // Emitting a SourceFile Expression, // Emitting an Expression IdentifierName, // Emitting an IdentifierName Unspecified // Emitting an otherwise unspecified node } }
using Visitor.Visitors; namespace Visitor.Element { public class Kid : IElement { public Kid(string name) { this.KidName = name; } public string KidName { get; set; } public void Accept(IVisitor visitor) { visitor.Visit(this); } } }
using System; using Vecto.Core.Entities; namespace Vecto.Application.Sections { public static class SectionMapper { public static Section MapToSection(this SectionDTO dto) { return dto.SectionType switch { nameof(PackingSection) => new PackingSection() { Name = dto.Name }, nameof(TodoSection) => new TodoSection() { Name = dto.Name }, _ => throw new ArgumentException("Section type is not valid", nameof(dto.SectionType)) }; } public static void UpdateWith(this Section section, SectionDTO model) { section.Name = model.Name ?? section.Name; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HurtPlayer : MonoBehaviour { //damage the player wll receive public int damageGiven; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } //When two objects with a collider colides something will happen void OnCollisionEnter2D(Collision2D other) { //if the player collides, this will happen if(other.gameObject.name == "Player") { other.gameObject.GetComponent<PlayerHealthManager>().HurtPlayer(damageGiven); //Player object becomes inactive //other.gameObject.SetActive(false); //reloading = true; //thePlayer = other.gameObject; } } }
/* https://www.codewars.com/kata/56cafdabc8cfcc3ad4000a2b/csharp 7 kyu Binary scORe Objective Given a number n we will define its scORe to be 0 | 1 | 2 | 3 | ... | n, where | is the bitwise OR operator. Write a function that takes n and finds it's scORe. n scORe n 0 0 1 1 49 63 1000000 1048575 Any feedback would be much appreciated */ using System; using System.Numerics; namespace CodeWars { public class BinaryScORe { public static BigInteger Score(BigInteger n) { // for (BigInteger i = 1; i < n; i <<= 1) // { // n |= i; // } // return n; //return n > 0 ? BigInteger.Pow(new BigInteger(2), (int) BigInteger.Log(n, 2) + 1) - 1 : n; return BigInteger.Pow(2, (int) Math.Ceiling(BigInteger.Log(n + 1, 2))) - 1; } } }
using System; using System.Linq.Expressions; using System.Text; using JetBrains.Annotations; using PK.Sql.Generator.Extensions.Extensions.Assigment; using PK.Sql.Generator.Extensions.Interfaces; namespace PK.Sql.Generator.Extensions.Assigment { public class CustomColumnOperation : AssigmentOperationBase { [NotNull] private readonly IAssigmentOperation _operation; #region Overrides of AssigmentOperationBase /// <inheritdoc /> public override bool IsValue => _operation.IsValue; /// <inheritdoc /> public override object Value => _operation.Value; #endregion /// <inheritdoc /> public CustomColumnOperation( [NotNull] MethodCallExpression expression, [NotNull] ISqlDialect dialect, [NotNull] INameConverter nameConverter, [NotNull] AssigmentParseHelpers assigmentParseHelpers ) : base(null, dialect, nameConverter) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } Name = expression.Arguments[1].NodeType == ExpressionType.Constant ? ((ConstantExpression) expression.Arguments[1]).Value as string : throw new InvalidOperationException(); _operation = assigmentParseHelpers.ParseExpression(expression.Arguments[2], Name, true); } /// <inheritdoc /> public override void AppendSql(StringBuilder builder, GeneratorContext filterParams) { _operation.AppendSql(builder, filterParams); } } }
// Copyright (c) Daniel Crenna & Contributors. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using ActiveAuth.Models; using ActiveTenant; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; namespace ActiveAuth.Stores { public static class Add { public static IdentityBuilder AddIdentityStores<TKey, TUser, TRole, TTenant, TApplication> ( this IdentityBuilder identityBuilder ) where TKey : IEquatable<TKey> where TUser : IdentityUserExtended<TKey> where TRole : IdentityRoleExtended<TKey> where TTenant : IdentityTenant<TKey> where TApplication : IdentityApplication<TKey> { var services = identityBuilder.Services; services.AddTransient<IUserStoreExtended<TUser>, UserStore<TUser, TKey, TRole>>(); services.AddTransient<IUserStore<TUser>>(r => r.GetRequiredService<IUserStoreExtended<TUser>>()); services.AddTransient<IRoleStoreExtended<TRole>, RoleStore<TKey, TRole>>(); services.AddTransient<IRoleStore<TRole>>(r => r.GetRequiredService<IRoleStoreExtended<TRole>>()); services.AddTransient<ITenantStore<TTenant>, TenantStore<TTenant, TKey>>(); services.AddScoped<TenantManager<TTenant, TUser, TKey>>(); services.AddTransient<IApplicationStore<TApplication>, ApplicationStore<TApplication, TKey>>(); services.AddScoped<ApplicationManager<TApplication, TUser, TKey>>(); return identityBuilder .AddRoles<TRole>() .AddUserManager<UserManager<TUser>>() .AddRoleManager<RoleManager<TRole>>() .AddSignInManager<SignInManager<TUser>>(); } } }
using Unity.Collections; using Unity.Entities; [UpdateBefore(typeof(ShipSystem))] public class FindTargetSystem : FixedEcbSystem { private EntityQuery _findTargetQuerry; private EntityQuery _targetsQuery; protected override void OnCreate() { base.OnCreate(); _findTargetQuerry = GetEntityQuery( ComponentType.ReadWrite<OrderState>(), ComponentType.ReadWrite<FindTarget>(), ComponentType.ReadWrite<FireAtTarget>(), ComponentType.ReadWrite<RandomData>(), ComponentType.ReadOnly<Team>()); RequireForUpdate(_findTargetQuerry); _targetsQuery = GetEntityQuery( ComponentType.ReadOnly<Ship>(), ComponentType.ReadOnly<Team>()); } protected override void OnUpdate() { var ecb = _ecbSystem.CreateCommandBuffer().AsParallelWriter(); var targetEntities = _targetsQuery.ToEntityArray(Allocator.TempJob); var teams = GetComponentDataFromEntity<Team>(true); Entities .WithName("FindTarget") .WithAll<FindTarget>() .WithAll<Team>() .WithReadOnly(teams) .WithReadOnly(targetEntities) .WithDisposeOnCompletion(targetEntities) .ForEach( (Entity entity, int entityInQueryIndex, ref OrderState orederState, ref FireAtTarget fireAtTarget, ref RandomData randomData) => { var teamId = teams[entity].Id; var targets = new NativeList<Entity>(Allocator.Temp); for (int i = 0; i < targetEntities.Length; i++) { var target = targetEntities[i]; if (teams[target].Id != teamId) targets.Add(target); } if (targets.Length > 0) fireAtTarget.Entity = targets[randomData.Random.NextInt(targets.Length)]; else orederState.Completed = true; ecb.RemoveComponent<FindTarget>(entityInQueryIndex, entity); targets.Dispose(); }).ScheduleParallel(); _ecbSystem.AddJobHandleForProducer(Dependency); } }
using System; using System.Diagnostics.Contracts; using System.Linq; using ErrorProne.NET.Common; using Microsoft.CodeAnalysis; namespace ErrorProne.NET.Extensions { public static class TypeSymbolExtensions { public static string FullName(this ITypeSymbol symbol) { Contract.Requires(symbol != null); var symbolDisplayFormat = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); return symbol.ToDisplayString(symbolDisplayFormat); } public static string Defaultvalue(this ITypeSymbol symbol) { if (symbol.IsReferenceType) { return "null"; } if (symbol.IsEnum()) { var v = symbol.GetMembers().OfType<IFieldSymbol>().FirstOrDefault(); if (v == null || Convert.ToInt32(v.ConstantValue) != 0) { return "0"; } return v.Name; } if (symbol.SpecialType == SpecialType.None) { return $"default({symbol.Name})"; } var clrType = Type.GetType(symbol.FullName()); return Activator.CreateInstance(clrType).ToString(); } public static ITypeSymbol UnwrapGenericIfNeeded(this ITypeSymbol type) { Contract.Requires(type != null); var named = type as INamedTypeSymbol; return named != null ? named.ConstructedFrom : type; } public static bool IsEnum(this ITypeSymbol type) { Contract.Requires(type != null); return type?.IsValueType == true && type.BaseType.SpecialType == SpecialType.System_Enum; } public static ITypeSymbol GetEnumUnderlyingType(this ITypeSymbol enumType) { var namedTypeSymbol = enumType as INamedTypeSymbol; return namedTypeSymbol?.EnumUnderlyingType; } public static bool IsNullableEnum(this ITypeSymbol type, SemanticModel semanticModel) { Contract.Requires(type != null); Contract.Requires(semanticModel != null); return type.UnwrapFromNullableType(semanticModel)?.IsEnum() == true; } public static bool IsNullablePrimitiveType(this ITypeSymbol type, SemanticModel semanticModel) { Contract.Requires(type != null); Contract.Requires(semanticModel != null); return type.UnwrapFromNullableType(semanticModel)?.IsPrimitiveType() == true; } public static ITypeSymbol UnwrapFromNullableType(this ITypeSymbol type, SemanticModel semanticModel) { var namedType = type as INamedTypeSymbol; if (namedType == null) return null; if (type.UnwrapGenericIfNeeded().Equals(semanticModel.GetClrType(typeof (Nullable<>)))) { return namedType.TypeArguments[0]; } return null; } public static bool IsPrimitiveType(this ITypeSymbol type) { Contract.Requires(type != null); switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_DateTime: return true; } return false; } public static bool TryGetPrimitiveSize(this ITypeSymbol type, out int size) { Contract.Requires(type != null); switch (type.SpecialType) { case SpecialType.System_Boolean: size = sizeof(bool); break; case SpecialType.System_Char: size = sizeof(char); break; case SpecialType.System_SByte: case SpecialType.System_Byte: size = sizeof(byte); break; case SpecialType.System_Int16: case SpecialType.System_UInt16: size = sizeof(short); break; case SpecialType.System_Single: size = sizeof(float); break; case SpecialType.System_Int32: case SpecialType.System_UInt32: size = sizeof(int); break; case SpecialType.System_Int64: case SpecialType.System_UInt64: size = sizeof(long); break; case SpecialType.System_Decimal: size = sizeof(decimal); break; case SpecialType.System_Double: size = sizeof(double); break; case SpecialType.System_DateTime: size = sizeof(long); break; default: size = 0; break; } return size != 0; } } }
using NUnit.Framework; using RingCentral.Http; using System.Linq; namespace RingCentral.Test { [TestFixture] class APIVersionsTest : BaseTest { [Test] public void BaseURL() { var request = new Request("/restapi/"); var response = sdk.Platform.Get(request); var uriString = (string)response.Json.SelectToken("apiVersions").First().SelectToken("uriString"); Assert.AreEqual("v1.0", uriString); } } }
using System.Threading.Tasks; using Business.Abstract; using Core.Utilities.Results; using Entities.DTOs; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace WebApplication.Controllers { [Route("api/auth")] [ApiController] public class AuthController : Controller { private readonly IAuthenticationService _authenticationService; public AuthController(IAuthenticationService authenticationService) { _authenticationService = authenticationService; } [HttpPost] [Route("register")] public async Task<IActionResult> Register([FromBody] UserForRegisterDto model) { var result = await _authenticationService.Register(model, Url.Content("~/auth/confirm-mail")); return result.Success ? StatusCode(StatusCodes.Status201Created, result) : StatusCode(StatusCodes.Status404NotFound, result); } [HttpPost] [Route("register-admin")] public async Task<IActionResult> RegisterAdmin([FromBody] UserForRegisterDto model) { var result = await _authenticationService.RegisterAdmin(model, Url.Content("~/auth/confirm-mail")); return result.Success ? StatusCode(StatusCodes.Status201Created, result) : StatusCode(StatusCodes.Status404NotFound, result); } [HttpPost] [Route("login")] public async Task<IActionResult> Login([FromBody] UserForLoginDto model) { var result = await _authenticationService.Login(model); return result.Success ? StatusCode(StatusCodes.Status200OK, result) : StatusCode(StatusCodes.Status404NotFound, result); } [HttpPost] [Route("sign-out")] public new void SignOut() { _authenticationService.SignOut(); } [HttpPost] [Route("confirm-mail")] public Task<IResult> ConfirmMail(string token, string email) { return _authenticationService.ConfirmEmail(token, email); } [HttpPost] [Route("enable-two-factor-security")] public async Task<IActionResult> EnableTwoFactorSecurity(string id) { var result = await _authenticationService.EnableTwoFactorSecurity(id); return result.Success ? StatusCode(StatusCodes.Status200OK, result) : StatusCode(StatusCodes.Status404NotFound, result); } [HttpPost] [Route("disable-two-factor-security")] public async Task<IActionResult> DisableTwoFactorSecurity(string id) { var result = await _authenticationService.DisableTwoFactorSecurity(id); return result.Success ? StatusCode(StatusCodes.Status200OK, result) : StatusCode(StatusCodes.Status404NotFound, result); } [HttpPost] [Route("login-with-two-factor-security")] public async Task<IActionResult> LoginWithTwoFactorSecurity(string code) { var result = await _authenticationService.LoginWithTwoFactorSecurity(code); return result.Success ? StatusCode(StatusCodes.Status200OK, result) : StatusCode(StatusCodes.Status404NotFound, result); } } }
@section MetaTags{ <meta name="description" content="This example illustrates exporting Gantt project tasks to Excel and PDF formats."> } @section SampleHeading{<span class="sampleName">Gantt-Exporting Gantt-ASP.NET MVC-SYNCFUSION</span>} @section ControlsSection{ @(Html.EJ().Gantt("GanttContainer") .ChildMapping("Children") .TreeColumnIndex(1) .TaskIdMapping("TaskId") .TaskNameMapping("TaskName") .StartDateMapping("StartDate") .EndDateMapping("EndDate") .ProgressMapping("Progress") .EditSettings(es => es.AllowDeleting(false)) .SizeSettings(ss => ss.Width("100%").Height("450px")) .IsResponsive(true) .TaskSchedulingMode(GanttTaskSchedulingMode.Custom) .TaskSchedulingModeMapping("IsManual") .ClientSideEvents(cs => cs.Load("load").ToolbarClick("toolbarClick")) .ToolbarSettings(tool => { tool.ShowToolbar(true); tool.ToolbarItems(new List<GanttToolBarItems>() { GanttToolBarItems.ExcelExport, GanttToolBarItems.PdfExport }); }) .Datasource(ViewBag.datasource) ) } @section PropertiesSection{ <div class="prop-grid"> <div class="row"> <div class="col-md-3"> Fit timeline to one page in PDF </div> <div class="col-md-3"> <div style="padding-left:10px;"> @(Html.EJ().CheckBox("enablePageBreak") .Checked(false) ) </div> </div> </div> </div> } @section ScriptSection{ <script type="text/javascript"> $(function () { $("#sampleProperties").ejPropertiesPanel(); }); function toolbarClick(args) { var id = $(args.currentTarget).attr("id"); this.model["exportData"] = JSON.stringify(this.dataSource()); this.exportGrid = this["export"]; if (id == "GanttContainer_pdfExport") { var isChecked = $("#enablePageBreak").ejCheckBox("isChecked"); if (isChecked) this.exportGrid("FitToPagePdfExport", "", false); else this.exportGrid("ExportToPdf", "", false); args.cancel = true; } } function load(args) { var columns = this.getColumns(); columns[0].width = 60; } </script> }
using System; using System.Windows.Forms; namespace CompilerGUI { public partial class MainForm : Form { private void quietMode_CheckedChanged(object sender, EventArgs e) { if (quietMode.Checked) ArgumentList.Add("-q"); else ArgumentList.Remove("-q"); } private void vQuietMode_CheckedChanged(object sender, EventArgs e) { if (vQuietMode.Checked) ArgumentList.Add("+q"); else ArgumentList.Remove("+q"); } private void compileOnly_CheckedChanged(object sender, EventArgs e) { if (compileOnly.Checked) ArgumentList.Add("-c"); else ArgumentList.Remove("-c"); } private void debugCompile_CheckedChanged(object sender, EventArgs e) { if (debugCompile.Checked) ArgumentList.Add("-d"); else ArgumentList.Remove("-d"); } private void dKeywords_CheckedChanged(object sender, EventArgs e) { if (dKeywords.Checked) ArgumentList.Add("-k"); else ArgumentList.Remove("-k"); } private void dKeywordsSyntax_CheckedChanged(object sender, EventArgs e) { if (dKeywordsSyntax.Checked) ArgumentList.Add("+k"); else ArgumentList.Remove("+k"); } } }
using LeakBlocker.Libraries.Common; using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace LeakBlocker.AdminView.Desktop.Themes { internal sealed partial class Generics { public Generics() { InitializeComponent(); } private void TransparentButtonLoadedHandler(object sender, RoutedEventArgs e) { var button = (Button)sender; var targetBorder = (Border)button.Template.FindName("Bd",button); if (targetBorder == null) return; targetBorder.BorderBrush = Brushes.Transparent; targetBorder.BorderThickness = new Thickness(0); } } }
using Mirror; namespace WeaverSyncObjectsTest.SyncObjectsMoreThanMax { public class RecommendsReadonly : NetworkBehaviour { // NOT readonly. should show weaver recommendation. public SyncList<int> list = new SyncList<int>(); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.WebJobs.Hosting { /// <summary> /// Interface defining a startup action for configuring application configuration /// as part of host startup. /// </summary> public interface IWebJobsConfigurationStartup { /// <summary> /// Performs the startup action for configuring application configuration with an /// <see cref="Extensions.Configuration.IConfigurationBuilder"></see>. The host will call this method at the /// right time during host initialization. /// </summary> /// <param name="context">The builder context</param> /// <param name="builder">The <see cref="IWebJobsConfigurationBuilder"/> that can be used to /// configure the host application configuration.</param> void Configure(WebJobsBuilderContext context, IWebJobsConfigurationBuilder builder); } }
using System; using System.Collections.Generic; using System.Linq; using Medja.Controls; namespace SecureTextEditor.Views { /// <summary> /// Static class holding extension methods to simplify working with comboBox updates. /// </summary> internal static class ComboBoxExtensions { /// <summary> /// Adds multiple entries to Combobox at once. /// Accepts an iterable collection. /// Results in one call instead of calling add-method multiple times with one entry each time. /// </summary> /// <param name="comboBox">comboBox object</param> /// <param name="items">iterable string object</param> public static void AddRange(this ComboBox comboBox, IEnumerable<string> items) { foreach (var title in items) comboBox.Add(title); } public static void AddRange(this ComboBox comboBox, params string[] items) { AddRange(comboBox, (IEnumerable<string>)items); } public static void AddRange<T>(this ComboBox comboBox, params T[] items) where T : Enum { AddRange(comboBox, (IEnumerable<T>)items); } public static void AddRange<T>(this ComboBox comboBox, IEnumerable<T> items) where T : Enum { AddRange(comboBox, items.Select(p => Enum.GetName(typeof(T), p))); } public static void Add<T>(this ComboBox comboBox, T item) where T : Enum { comboBox.Add(Enum.GetName(typeof(T), item)); } /// <summary> /// Selecting first item in combobox. /// Results in Display. /// Otherwise title of combobox would have been displayed instead. /// </summary> public static void SelectFirstItem(this ComboBox comboBox) { if (comboBox.ItemsPanel.Children.Count == 0) return; comboBox.SelectedItem = comboBox.ItemsPanel.Children[0]; } } }
namespace EveEchoesPlanetaryProductionApi.Web.Common { public class PresentationConstants { public const string PriceFormat = "F2"; public const string IskSymbol = " Ƶ"; public const string UserKey = "68cc19c0-d20a-4d64-9858-f10338746e38userKey"; public const string IconsApiEndpoint = "resources/items"; public const long DefaultBluePrint = 240000001; public const string BlueprintCalculationTotal = "Grand Total"; } }
@{ ViewData["Title"] = "Confirm email"; Layout = "_WindowLayout"; } <p>Thank you for confirming your email.</p>
/// SafeExchange namespace SpaceOyster.SafeExchange.Core { using Microsoft.Extensions.Logging; using Microsoft.Graph; using System.Threading.Tasks; public interface IGraphClientProvider { Task<GraphServiceClient> GetGraphClientAsync(TokenResult tokenResult, string[] scopes, ILogger logger); } }
using Gdpr.Api.Infrastructure.Data.Entities; namespace Gdpr.Api.Infrastructure.Data.Models { public class AppUser : BaseEntity { public AppUser(string firstName, string lastName, string email, string passwordHash, string id, int role) { FirstName = firstName; LastName = lastName; Email = email; PasswordHash = passwordHash; Id = id; Role = role; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string PasswordHash { get; set; } public int Role { get; set; } } }
namespace DFC.App.SkillsHealthCheck.Services.SkillsCentral.Models { public class Image { public string Src { get; set; } public string Title { get; set; } public string Alttext { get; set; } } }
using System.Collections.Generic; using System.Linq; namespace Shared { public class FoundServices { public FoundServices(IEnumerable<Service> services) { Services = services.ToArray(); } public Service[] Services { get; private set; } } public class Service { private readonly HashSet<string> _urls; public Service(string name, IEnumerable<string> urls) { Name = name; _urls = urls != null ? new HashSet<string>(urls) : new HashSet<string>(); } public string Name { get; private set; } public string[] URLs { get { return _urls.ToArray(); } } public void AddUrl(string url) { _urls.Add(url); } } }
using System; using System.Collections.Generic; using Moq; using NUnit.Framework; using SchoolSystem.Data.Models.CustomModels; using SchoolSystem.MVP.Account.Models; using SchoolSystem.MVP.Account.Presenters; using SchoolSystem.MVP.Account.Views; using SchoolSystem.Web.Services.Contracts; namespace SchoolSystem.MVP.Tests.Account.Presenters.RegistrationPresenterTests { [TestFixture] public class View_EventGetAvailableSubjects_Should { [Test] public void BindAllSubjectsWithoutTeacher_ToModel_WhenArgumentsAreValid() { var mockedRegisterView = new Mock<IRegisterView>(); var mockedRegistrationService = new Mock<IRegistrationService>(); var mockedSubjectManagementService = new Mock<ISubjectManagementService>(); var mockedClassOfStudentsManagementService = new Mock<IClassOfStudentsManagementService>(); var mockedAccountManagementService = new Mock<IAccountManagementService>(); var mockedEmailSenderService = new Mock<IEmailSenderService>(); var mockedPasswordService = new Mock<IPasswordGeneratorService>(); mockedRegisterView .SetupGet(x => x.Model) .Returns(new RegistrationModel()); var expectedSubjects = new List<SubjectBasicInfoModel>() { new SubjectBasicInfoModel(), new SubjectBasicInfoModel(), new SubjectBasicInfoModel() }; mockedSubjectManagementService .Setup(x => x.GetAllSubjectsWithoutTeacher()) .Returns(expectedSubjects); var registrationPresenter = new RegistrationPresenter( mockedRegisterView.Object, mockedRegistrationService.Object, mockedSubjectManagementService.Object, mockedClassOfStudentsManagementService.Object, mockedAccountManagementService.Object, mockedEmailSenderService.Object, mockedPasswordService.Object); mockedRegisterView.Raise(x => x.EventGetAvailableSubjects += null, EventArgs.Empty); CollectionAssert.AreEquivalent(expectedSubjects, mockedRegisterView.Object.Model.Subjects); } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using Elastic.Elasticsearch.Xunit.XunitPlumbing; using System.ComponentModel; using Nest; namespace Examples.Search { public class AsyncSearchPage : ExampleBase { [U(Skip = "Example not implemented")] [Description("search/async-search.asciidoc:17")] public void Line17() { // tag::e50f9492af9e0174c7ecbe5ad7f09d74[] var response0 = new SearchResponse<object>(); // end::e50f9492af9e0174c7ecbe5ad7f09d74[] response0.MatchesExample(@"POST /sales*/_async_search?size=0 { ""sort"" : [ { ""date"" : {""order"" : ""asc""} } ], ""aggs"" : { ""sale_date"" : { ""date_histogram"" : { ""field"" : ""date"", ""calendar_interval"": ""1d"" } } } }"); } [U(Skip = "Example not implemented")] [Description("search/async-search.asciidoc:146")] public void Line146() { // tag::14b81f96297952970b78a3216e059596[] var response0 = new SearchResponse<object>(); // end::14b81f96297952970b78a3216e059596[] response0.MatchesExample(@"GET /_async_search/FmRldE8zREVEUzA2ZVpUeGs2ejJFUFEaMkZ5QTVrSTZSaVN3WlNFVmtlWHJsdzoxMDc="); } [U(Skip = "Example not implemented")] [Description("search/async-search.asciidoc:233")] public void Line233() { // tag::7a3a7fbd81e5050b42e8c1eca26c7c1d[] var response0 = new SearchResponse<object>(); // end::7a3a7fbd81e5050b42e8c1eca26c7c1d[] response0.MatchesExample(@"DELETE /_async_search/FmRldE8zREVEUzA2ZVpUeGs2ejJFUFEaMkZ5QTVrSTZSaVN3WlNFVmtlWHJsdzoxMDc="); } } }
using UnityEngine; namespace Wowsome.TwoDee { [ExecuteInEditMode] public class WScaleFitCanvas : MonoBehaviour { public Transform canvasObject; public Transform rootObject; void ReScale() { if (null != canvasObject) { rootObject.localScale = canvasObject.localScale; } } void Awake() { ReScale(); } void Update() { #if UNITY_EDITOR ReScale(); #endif } } }
// Instance generated by TankLibHelper.InstanceBuilder using TankLib.STU.Types.Enums; // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0x600E3C59)] public class STU_600E3C59 : STU_6243C374 { [STUFieldAttribute(0xD655C99A, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_D655C99A; [STUFieldAttribute(0x5DC5168B, "m_width", ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_width; [STUFieldAttribute(0x9CDDC24D, "m_weight", ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_weight; [STUFieldAttribute(0xB802CBBA, ReaderType = typeof(EmbeddedInstanceFieldReader))] public STUConfigVar m_B802CBBA; [STUFieldAttribute(0xDD792FF0)] public Enum_4131E6E0 m_DD792FF0; } }
using System; using System.ComponentModel.DataAnnotations; namespace JudgeMyTaste.Models { public class FavoriteBand { public int Id { get; set; } [Display(Name="Band/Artist Name")] public string Name { get; set; } [Display(Name="Entered By")] public string EnteredBy { get; set; } [Display(Name="Entered On")] public DateTime EnteredOn { get; set; } } }
using WebApp.Models; using Microsoft.AspNetCore.Components; namespace WebApp.Components; public class ProductModalComponent : ComponentBase { [Parameter] public Product Product { get; set; } protected override void OnParametersSet() { Product ??= new Product(); base.OnParametersSet(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Ports; using System.Threading; namespace Console_to_Gui { public partial class Form1 : Form { private readonly SerialPort _serialPort; private readonly bool _continue; public Form1() { InitializeComponent(); StringComparer stringComparer = StringComparer.OrdinalIgnoreCase; // Create a new SerialPort object with default settings. _serialPort = new SerialPort(); // Allow the user to set the appropriate properties. _serialPort.PortName = "COM6"; // Set the read/write timeouts _serialPort.ReadTimeout = 5000; _serialPort.WriteTimeout = 5000; _serialPort.Open(); _continue = true; //Console.WriteLine("Type QUIT to exit"); } private void button1_Click(object sender, EventArgs e) { string message; message = textBox1.Text; _serialPort.Write(message); } } }
using System.IO; using System; using System.Net; using System.Collections.Specialized; class Program { static void Main() { var parameters = new NameValueCollection { { "token", "APP_TOKEN" }, { "user", "USER_KEY" }, { "message", "hello world" } }; using (var client = new WebClient()) client.UploadValues("https://api.pushover.net/1/messages.json", parameters); } }
/* EFrt - (C) 2021 Premysl Fara */ namespace EFrt.Core.Words { using EFrt.Core.Extensions; /// <summary> /// A word keeping a floating point value. /// </summary> public class FloatingPointConstantWord : AWordBase { /// <summary> /// Constructor. /// </summary> /// <param name="interpreter">An IInterpreter instance, that is executing this word.</param> /// <param name="name">A name of this constant.</param> /// <param name="value">The value of this constant.</param> public FloatingPointConstantWord(IInterpreter interpreter, string name, double value) : base(interpreter) { Name = name; IsControlWord = true; Action = () => { Interpreter.FStackFree(1); Interpreter.FPush(_value); return 1; }; _value = value; } private readonly double _value; } }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace Navigation.Utils { public class NavigationManager : INavigationManager { #region Fields private readonly Dispatcher _dispatcher; private readonly ContentControl _frameControl; private readonly IDictionary<string, object> _viewModelsByNavigationKey = new Dictionary<string, object>(); private readonly IDictionary<Type, Type> _viewTypesByViewModelType = new Dictionary<Type, Type>(); #endregion #region Ctor public NavigationManager(Dispatcher dispatcher, ContentControl frameControl) { if (dispatcher == null) throw new ArgumentNullException("dispatcher"); if (frameControl == null) throw new ArgumentNullException("frameControl"); _dispatcher = dispatcher; _frameControl = frameControl; } #endregion public void Register<TViewModel, TView>(TViewModel viewModel, string navigationKey) where TViewModel : class where TView : FrameworkElement { if (viewModel == null) throw new ArgumentNullException("viewModel"); if (navigationKey == null) throw new ArgumentNullException("navigationKey"); _viewModelsByNavigationKey[navigationKey] = viewModel; _viewTypesByViewModelType[typeof (TViewModel)] = typeof (TView); } public void Navigate(string navigationKey, object arg = null) { if (navigationKey == null) throw new ArgumentNullException("navigationKey"); InvokeInMainThread(() => { InvokeNavigatingFrom(); var viewModel = GetNewViewModel(navigationKey); InvokeNavigatingTo(viewModel, arg); var view = CreateNewView(viewModel); _frameControl.Content = view; }); } private void InvokeInMainThread(Action action) { _dispatcher.Invoke(action); } private FrameworkElement CreateNewView(object viewModel) { var viewType = _viewTypesByViewModelType[viewModel.GetType()]; var view = (FrameworkElement)Activator.CreateInstance(viewType); view.DataContext = viewModel; return view; } private object GetNewViewModel(string navigationKey) { return _viewModelsByNavigationKey[navigationKey]; } private void InvokeNavigatingFrom() { var oldView = _frameControl.Content as FrameworkElement; if (oldView == null) return; var navigationAware = oldView.DataContext as INavigationAware; if (navigationAware == null) return; navigationAware.OnNavigatingFrom(); } private static void InvokeNavigatingTo(object viewModel, object arg) { var navigationAware = viewModel as INavigationAware; if (navigationAware == null) return; navigationAware.OnNavigatingTo(arg); } } }
using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TaskManagement.Repositories.TaskActivityData { public class TaskActivityRepository : BaseRepository<TaskActivityEntity> { /// <summary> /// Initializes a new instance of the <see cref="UserDataRepository"/> class. /// </summary> /// <param name="configuration">Represents the application configuration.</param> /// <param name="isFromAzureFunction">Flag to show if created from Azure Function.</param> public TaskActivityRepository(IConfiguration configuration, bool isFromAzureFunction = false) : base( configuration, PartitionKeyNames.TaskActivityDataTable.TableName, PartitionKeyNames.TaskActivityDataTable.TaskActivityDataPartition, isFromAzureFunction) { } public async Task<List<TaskActivityEntity>> GetTaskActivityDetailsByTaskIDAsync(Guid taskId) { var allRows = await this.GetAllAsync(PartitionKeyNames.TaskActivityDataTable.TableName); List<TaskActivityEntity> taskActivityEntity = allRows.Where(c => c.TaskID == taskId).ToList(); return taskActivityEntity; } } }
using System; using System.Collections.Generic; using GuardNet; using Humanizer; using Microsoft.Extensions.Options; using Promitor.Agents.Core.Usability; using Promitor.Agents.ResourceDiscovery.Configuration; using Spectre.Console; namespace Promitor.Agents.ResourceDiscovery.Usability { public class DiscoveryGroupTableGenerator : AsciiTableGenerator { private readonly IOptionsMonitor<ResourceDeclaration> _resourceDeclarationMonitor; public DiscoveryGroupTableGenerator(IOptionsMonitor<ResourceDeclaration> resourceDeclarationMonitor) { Guard.NotNull(resourceDeclarationMonitor, nameof(resourceDeclarationMonitor)); _resourceDeclarationMonitor = resourceDeclarationMonitor; } /// <summary> /// Plots all configured information into an ASCII table /// </summary> public void PlotOverviewInAsciiTable() { var resourceDeclaration = _resourceDeclarationMonitor.CurrentValue; PlotAzureMetadataInAsciiTable(resourceDeclaration.AzureLandscape); PlotResourceDiscoveryGroupsInAsciiTable(resourceDeclaration.ResourceDiscoveryGroups); } private void PlotResourceDiscoveryGroupsInAsciiTable(List<ResourceDiscoveryGroup> resourceDiscoveryGroups) { var asciiTable = CreateResourceDiscoveryGroupsAsciiTable(); foreach (var resourceDiscoveryGroup in resourceDiscoveryGroups) { var isInclusionCriteriaConfigured = resourceDiscoveryGroup.Criteria.Include != null ? "Yes" : "No"; asciiTable.AddRow(resourceDiscoveryGroup.Name, resourceDiscoveryGroup.Type.Humanize(LetterCasing.Title), isInclusionCriteriaConfigured); } AnsiConsole.Write(asciiTable); } private void PlotAzureMetadataInAsciiTable(AzureLandscape azureLandscape) { var asciiTable = CreateAzureMetadataAsciiTable(); var rawSubscriptions = "- " + string.Join($"{Environment.NewLine} - ", azureLandscape.Subscriptions); asciiTable.AddRow(azureLandscape.TenantId, azureLandscape.Cloud.Humanize(LetterCasing.Title), rawSubscriptions); AnsiConsole.Write(asciiTable); } private Table CreateResourceDiscoveryGroupsAsciiTable() { var asciiTable = CreateAsciiTable("Resource Discovery Groups"); // Add some columns asciiTable.AddColumn("Name"); asciiTable.AddColumn("Resource Type"); asciiTable.AddColumn("Is Include Criteria Configured?"); return asciiTable; } private Table CreateAzureMetadataAsciiTable() { var asciiTable = CreateAsciiTable("Azure Landscape"); // Add some columns asciiTable.AddColumn("Tenant Id"); asciiTable.AddColumn("Azure Cloud"); asciiTable.AddColumn("Subscriptions"); return asciiTable; } } }
// // BSD 3-Clause License // // Copyright (c) 2020-201, Boia Alexandru // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 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. // using LVD.Stakhanovise.NET.Helpers; using LVD.Stakhanovise.NET.Logging; using LVD.Stakhanovise.NET.Model; using LVD.Stakhanovise.NET.Options; using Npgsql; using NpgsqlTypes; using System; using System.Collections.Generic; using System.Data; using System.Reflection; using System.Threading.Tasks; namespace LVD.Stakhanovise.NET.Queue { public class PostgreSqlTaskQueueConsumer : ITaskQueueConsumer, IAppMetricsProvider, IDisposable { private static readonly IStakhanoviseLogger mLogger = StakhanoviseLogManager .GetLogger( MethodBase .GetCurrentMethod() .DeclaringType ); public event EventHandler<ClearForDequeueEventArgs> ClearForDequeue; private bool mIsDisposed; private TaskQueueConsumerOptions mOptions; private PostgreSqlTaskQueueNotificationListener mNotificationListener; private string mTaskDequeueSql; private string mTaskAcquireSql; private string mTaskResultUpdateSql; private ITimestampProvider mTimestampProvider; private AppMetricsCollection mMetrics = new AppMetricsCollection ( new AppMetric( AppMetricId.QueueConsumerDequeueCount, 0 ), new AppMetric( AppMetricId.QueueConsumerMaximumDequeueDuration, long.MinValue ), new AppMetric( AppMetricId.QueueConsumerMinimumDequeueDuration, long.MaxValue ), new AppMetric( AppMetricId.QueueConsumerTotalDequeueDuration, 0 ) ); public PostgreSqlTaskQueueConsumer( TaskQueueConsumerOptions options, ITimestampProvider timestampProvider ) { if ( options == null ) throw new ArgumentNullException( nameof( options ) ); if ( timestampProvider == null ) throw new ArgumentNullException( nameof( timestampProvider ) ); mOptions = options; mTimestampProvider = timestampProvider; mTaskDequeueSql = GetTaskDequeueSql( options.Mapping ); mTaskAcquireSql = GetTaskAcquireSql( options.Mapping ); mTaskResultUpdateSql = GetTaskResultUpdateSql( options.Mapping ); SetupNotificationListener( options ); } private void SetupNotificationListener( TaskQueueConsumerOptions options ) { string signalingConnectionString = options.DeriveSignalingConnectionString(); mNotificationListener = new PostgreSqlTaskQueueNotificationListener( signalingConnectionString, options.Mapping.NewTaskNotificationChannelName ); mNotificationListener.ListenerConnectionRestored += HandleListenerConnectionRestored; mNotificationListener.NewTaskPosted += HandleNewTaskUpdateReceived; mNotificationListener.ListenerTimedOutWhileWaiting += HandleListenerTimedOut; } private async Task<NpgsqlConnection> OpenQueueConnectionAsync() { return await mOptions .ConnectionOptions .TryOpenConnectionAsync(); } private void NotifyClearForDequeue( ClearForDequeReason reason ) { EventHandler<ClearForDequeueEventArgs> eventHandler = ClearForDequeue; if ( eventHandler != null ) eventHandler( this, new ClearForDequeueEventArgs( reason ) ); } private void HandleNewTaskUpdateReceived( object sender, NewTaskPostedEventArgs e ) { NotifyClearForDequeue( ClearForDequeReason .NewTaskPostedNotificationReceived ); } private void HandleListenerConnectionRestored( object sender, ListenerConnectionRestoredEventArgs e ) { NotifyClearForDequeue( ClearForDequeReason .NewTaskListenerConnectionStateChange ); } private void HandleListenerTimedOut( object sender, ListenerTimedOutEventArgs e ) { NotifyClearForDequeue( ClearForDequeReason .ListenerTimedOut ); } private void CheckNotDisposedOrThrow() { if ( mIsDisposed ) throw new ObjectDisposedException( nameof( PostgreSqlTaskQueueConsumer ), "Cannot reuse a disposed postgre sql task queue consumer" ); } private string GetTaskDequeueSql( QueuedTaskMapping mapping ) { //See https://dba.stackexchange.com/questions/69471/postgres-update-limit-1/69497#69497 return $@"SELECT tq.* FROM { mapping.DequeueFunctionName }(@types, @excluded, @ref_now) tq"; } private string GetTaskAcquireSql( QueuedTaskMapping mapping ) { return $@"DELETE FROM {mapping.QueueTableName} WHERE task_id = @t_id"; } private string GetTaskResultUpdateSql( QueuedTaskMapping mapping ) { return $@"UPDATE {mapping.ResultsQueueTableName} SET task_status = @t_status, task_first_processing_attempted_at_ts = COALESCE(task_first_processing_attempted_at_ts, NOW()), task_last_processing_attempted_at_ts = NOW() WHERE task_id = @t_id RETURNING *"; } private void IncrementDequeueCount( TimeSpan duration ) { long durationMilliseconds = ( long ) Math.Ceiling( duration .TotalMilliseconds ); mMetrics.UpdateMetric( AppMetricId.QueueConsumerDequeueCount, m => m.Increment() ); mMetrics.UpdateMetric( AppMetricId.QueueConsumerTotalDequeueDuration, m => m.Add( durationMilliseconds ) ); mMetrics.UpdateMetric( AppMetricId.QueueConsumerMinimumDequeueDuration, m => m.Min( durationMilliseconds ) ); mMetrics.UpdateMetric( AppMetricId.QueueConsumerMaximumDequeueDuration, m => m.Max( durationMilliseconds ) ); } public async Task<IQueuedTaskToken> DequeueAsync( params string[] selectTaskTypes ) { NpgsqlConnection conn = null; QueuedTask dequeuedTask = null; QueuedTaskResult dequeuedTaskResult = null; PostgreSqlQueuedTaskToken dequeuedTaskToken = null; MonotonicTimestamp startDequeue; DateTimeOffset refNow = mTimestampProvider.GetNow(); CheckNotDisposedOrThrow(); try { mLogger.DebugFormat( "Begin dequeue task. Looking for types: {0}.", string.Join<string>( ",", selectTaskTypes ) ); startDequeue = MonotonicTimestamp .Now(); conn = await OpenQueueConnectionAsync(); if ( conn == null ) return null; using ( NpgsqlTransaction tx = conn.BeginTransaction( IsolationLevel.ReadCommitted ) ) { //1. Dequeue means that we acquire lock on a task in the queue // with the guarantee that nobody else did, and respecting // the priority and static locks (basically the task_locked_until which says // that it should not be pulled out of the queue until the // current abstract time reaches that tick value) dequeuedTask = await TryDequeueTaskAsync( selectTaskTypes, refNow, conn, tx ); if ( dequeuedTask != null ) { //2. Mark the task as being "Processing" and pull result info // The result is stored separately and it's what allows us to remove // the task from the queue at step #2, // whils also tracking its processing status and previous results dequeuedTaskResult = await TryUpdateTaskResultAsync( dequeuedTask, conn, tx ); if ( dequeuedTaskResult != null ) { await tx.CommitAsync(); dequeuedTaskToken = new PostgreSqlQueuedTaskToken( dequeuedTask, dequeuedTaskResult, refNow ); } } if ( dequeuedTaskToken != null ) IncrementDequeueCount( MonotonicTimestamp.Since( startDequeue ) ); else await tx.RollbackAsync(); } } finally { if ( conn != null ) { await conn.CloseAsync(); conn.Dispose(); } } return dequeuedTaskToken; } private async Task<QueuedTask> TryDequeueTaskAsync( string[] selectTaskTypes, DateTimeOffset refNow, NpgsqlConnection conn, NpgsqlTransaction tx ) { QueuedTask dequeuedTask; using ( NpgsqlCommand dequeueCmd = new NpgsqlCommand( mTaskDequeueSql, conn, tx ) ) { dequeueCmd.Parameters.AddWithValue( "types", parameterType: NpgsqlDbType.Array | NpgsqlDbType.Varchar, value: selectTaskTypes ); dequeueCmd.Parameters.AddWithValue( "excluded", parameterType: NpgsqlDbType.Array | NpgsqlDbType.Uuid, value: NoExcludedTaskIds ); dequeueCmd.Parameters.AddWithValue( "ref_now", parameterType: NpgsqlDbType.TimestampTz, value: refNow ); await dequeueCmd.PrepareAsync(); using ( NpgsqlDataReader taskRdr = await dequeueCmd.ExecuteReaderAsync() ) { dequeuedTask = await taskRdr.ReadAsync() ? await taskRdr.ReadQueuedTaskAsync() : null; } } return dequeuedTask; } private async Task<QueuedTaskResult> TryUpdateTaskResultAsync( QueuedTask dequeuedTask, NpgsqlConnection conn, NpgsqlTransaction tx ) { QueuedTaskResult dequeuedTaskResult = null; using ( NpgsqlCommand addOrUpdateResultCmd = new NpgsqlCommand( mTaskResultUpdateSql, conn, tx ) ) { addOrUpdateResultCmd.Parameters.AddWithValue( "t_id", NpgsqlDbType.Uuid, dequeuedTask.Id ); addOrUpdateResultCmd.Parameters.AddWithValue( "t_status", NpgsqlDbType.Integer, ( int ) QueuedTaskStatus.Processing ); await addOrUpdateResultCmd.PrepareAsync(); using ( NpgsqlDataReader resultRdr = await addOrUpdateResultCmd.ExecuteReaderAsync() ) { if ( await resultRdr.ReadAsync() ) dequeuedTaskResult = await resultRdr.ReadQueuedTaskResultAsync(); if ( dequeuedTaskResult != null ) mLogger.Debug( "Successfully dequeued, acquired and initialized/updated task result." ); else mLogger.Debug( "Failed to initialize or update task result. Will release lock..." ); } } return dequeuedTaskResult; } public IQueuedTaskToken Dequeue( params string[] supportedTypes ) { Task<IQueuedTaskToken> asyncTask = DequeueAsync( supportedTypes ); return asyncTask.Result; } public async Task StartReceivingNewTaskUpdatesAsync() { CheckNotDisposedOrThrow(); await mNotificationListener.StartAsync(); } public async Task StopReceivingNewTaskUpdatesAsync() { CheckNotDisposedOrThrow(); await mNotificationListener.StopAsync(); } protected void Dispose( bool disposing ) { if ( !mIsDisposed ) { if ( disposing ) { ClearForDequeue = null; StopReceivingNewTaskUpdatesAsync() .Wait(); mNotificationListener.ListenerConnectionRestored -= HandleListenerConnectionRestored; mNotificationListener.NewTaskPosted -= HandleNewTaskUpdateReceived; mNotificationListener.ListenerTimedOutWhileWaiting -= HandleListenerTimedOut; mNotificationListener.Dispose(); mNotificationListener = null; } mIsDisposed = true; } } public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } public AppMetric QueryMetric( AppMetricId metricId ) { return AppMetricsCollection.JoinQueryMetric( metricId, mMetrics, mNotificationListener ); } public IEnumerable<AppMetric> CollectMetrics() { return AppMetricsCollection.JoinCollectMetrics( mMetrics, mNotificationListener ); } public bool IsReceivingNewTaskUpdates { get { CheckNotDisposedOrThrow(); return mNotificationListener.IsStarted; } } public ITimestampProvider TimestampProvider { get { CheckNotDisposedOrThrow(); return mTimestampProvider; } } public IEnumerable<AppMetricId> ExportedMetrics { get { return AppMetricsCollection.JoinExportedMetrics( mMetrics, mNotificationListener ); } } private Guid[] NoExcludedTaskIds => new Guid[ 0 ]; } }
using Syn.Speech.Linguist.Language.Grammar; //REFACTORED namespace Syn.Speech.Linguist.Flat { /// <summary> /// Represents a non-emitting sentence hmm state /// </summary> public class GrammarState : SentenceHMMState { /** /// Creates a GrammarState * /// @param node the GrammarNode associated with this state */ public GrammarState(GrammarNode node) :base("G", null, node.ID) { GrammarNode = node; SetFinalState(GrammarNode.IsFinalNode); } /** /// Gets the grammar node associated with this state * /// @return the grammar node */ public GrammarNode GrammarNode { get; private set; } /** /// Retrieves a short label describing the type of this state. Typically, subclasses of SentenceHMMState will /// implement this method and return a short (5 chars or less) label * /// @return the short label. */ public override string TypeLabel { get { return "Gram"; } } /** /// Returns the state order for this state type * /// @return the state order */ public override int Order { get { return 3; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BLSystem { public partial class formAddressBookType : Form { PMModel contxt; AddressBookType bookType; List<AddressBookType> bookTypes; CompanyMaster company; List<CompanyMaster> companies; bool isNew=false, isEdit= false; enum FORMSTATE { ADD,EDIT,VIEW,DELETE,NOOP}; FORMSTATE state; public formAddressBookType() { InitializeComponent(); } private void formAddressBookType_Load(object sender, EventArgs e) { contxt = new PMModel(); bookType = new AddressBookType(); bookTypes = new List<AddressBookType>(); company = new CompanyMaster(); companies = new List<CompanyMaster>(); state = FORMSTATE.NOOP; SetButtons(); panelMid.Enabled = false; GetAddressBookTypeList(); GetCompanyList(); } private void GetCompanyList() { if (contxt.CompanyMasters.ToList().Count > 0) { companies = contxt.CompanyMasters.ToList(); cboCom.DataSource = companies; cboCom.DisplayMember = "CompanyName"; cboCom.ValueMember = "id"; } //throw new NotImplementedException(); } private void GetAddressBookTypeList() { if (contxt.AddressBookTypes.ToList().Count > 0) { bookTypes = contxt.AddressBookTypes.ToList(); dgvType.AutoGenerateColumns = false; dgvType.DataSource = bookTypes; } } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } /// <summary> /// Saving/updating form data to the database /// </summary> private void Save() { if(isNew) { bookType.CreatedBy = 1; bookType.CreatedDate = DateTime.Now; contxt.AddressBookTypes.Add(bookType); contxt.SaveChanges(); } if (isEdit) { AddressBookType type = contxt.AddressBookTypes.Where (o => o.id == bookType.id).FirstOrDefault(); if ( type != null) { type.BookTypeName = bookType.BookTypeName; type.Category01 = bookType.Category01; type.Category02 = bookType.Category02; type.Category03 = bookType.Category03; type.Category04 = bookType.Category04; type.Category05 = bookType.Category05; type.ModifiedBy = 1; type.ModifiedDate = DateTime.Now; contxt.SaveChanges(); } } } private void btnAdd_Click(object sender, EventArgs e) { isNew = true; isEdit = false; state = FORMSTATE.ADD; SetButtons(); panelMid.Enabled = true; ClearContents(); tbABTypeName.Focus(); } private void ClearContents() { tbABTypeName.Text = ""; tbCat01.Text = ""; tbCat02.Text = ""; tbCat03.Text = ""; //throw new NotImplementedException(); } private void btnSave_Click(object sender, EventArgs e) { UpdateValues(); try { Save(); isNew = false; isEdit = false; state = FORMSTATE.NOOP; SetButtons(); ClearContents(); panelMid.Enabled = false; MessageBox.Show(" Record Saved "); } catch( Exception ex) { MessageBox.Show(" Record Not Saved \n" + ex.Message); } } private void UpdateValues() { bookType.BookTypeName = tbABTypeName.Text; bookType.Category01 = tbCat01.Text; bookType.Category02 = tbCat02.Text; bookType.Category03 = tbCat03.Text; bookType.CompanyId = company.id; //throw new NotImplementedException(); } private void dgvType_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { bookType =(AddressBookType) dgvType.Rows[e.RowIndex].DataBoundItem; ShowRowContents(); btnEdit_Click(sender, new EventArgs()); } private void ShowRowContents() { tbABTypeName.Text = bookType.BookTypeName; tbCat01.Text = bookType.Category01; tbCat02.Text = bookType.Category02; tbCat03.Text = bookType.Category03; if (bookType.CompanyId != null) { company = companies.Where(o => o.id == bookType.CompanyId).FirstOrDefault(); cboCom.SelectedItem = company; } } private void btnEdit_Click(object sender, EventArgs e) { isEdit = true; isNew = false; state = FORMSTATE.EDIT; SetButtons(); panelMid.Enabled = true; tbABTypeName.Focus(); } private void btnRefresh_Click(object sender, EventArgs e) { dgvType.DataSource = null; dgvType.Refresh(); GetAddressBookTypeList(); } private void tbABTypeName_Enter(object sender, EventArgs e) { tbABTypeName.Select(0, tbABTypeName.Text.Length); } private void btnCancel_Click(object sender, EventArgs e) { isEdit = false;isNew = false; state = FORMSTATE.NOOP; SetButtons(); ClearContents(); panelMid.Enabled = false; } private void cboCom_SelectedIndexChanged(object sender, EventArgs e) { company =(CompanyMaster) cboCom.SelectedItem; } /// <summary> /// Setting up command buttons based on the form state /// </summary> private void SetButtons() { switch (state) { case FORMSTATE.NOOP: btnAdd.Enabled = true; btnEdit.Enabled = true; btnDelete.Enabled = true; btnRefresh.Enabled = true; btnSave.Enabled = false; break; case FORMSTATE.ADD: btnAdd.Enabled = false; btnEdit.Enabled = false; btnDelete.Enabled = false; btnRefresh.Enabled = true; btnSave.Enabled = true; break; case FORMSTATE.EDIT: btnAdd.Enabled = false; btnEdit.Enabled = false; btnDelete.Enabled = false; btnRefresh.Enabled = true; btnSave.Enabled = true; break; case FORMSTATE.DELETE: btnAdd.Enabled = false; btnEdit.Enabled = false; btnDelete.Enabled = false; btnRefresh.Enabled = true; btnSave.Enabled = false; break; default: btnAdd.Enabled = true; btnEdit.Enabled = true; btnDelete.Enabled = true; btnRefresh.Enabled = true; btnSave.Enabled = false; break; } } } }
using System; using System.Web; namespace Yahoo.Samples.CSharp { public partial class BBAuth4 { // This is only required for the sample to compile System.Web.SessionState.HttpSessionState Session = null; System.Web.UI.HtmlControls.HtmlGenericControl Div1 = new System.Web.UI.HtmlControls.HtmlGenericControl("div"); public void CallAuthenticatedWebService() { // Retrieve this user's authentication object we've stored in the session state Yahoo.Authentication auth = Session["Auth"] as Yahoo.Authentication; if (auth != null) { // Call web service and output result into a DIV tag Div1.InnerHtml = auth.GetAuthenticatedServiceString( new System.Uri("http://photos.yahooapis.com/V1.0/listServices")); } } } }
using System; using System.Globalization; using System.Xml; using Iviz.Urdf; namespace Iviz.Sdf { public sealed class Pose { public string? RelativeTo { get; } public Vector3d Position { get; } = Vector3d.Zero; public Vector3d Orientation { get; } = Vector3d.Zero; Pose() { } internal Pose(XmlNode node) { RelativeTo = node.Attributes?["relative_to"]?.Value; if (node.InnerText is null) { throw new MalformedSdfException(); } string[] elems = node.InnerText.Split(Vector3d.Separator, StringSplitOptions.RemoveEmptyEntries); if (elems.Length != 6) { throw new MalformedSdfException(node); } double x = double.Parse(elems[0], NumberStyles.Any, Utils.Culture); double y = double.Parse(elems[1], NumberStyles.Any, Utils.Culture); double z = double.Parse(elems[2], NumberStyles.Any, Utils.Culture); double rr = double.Parse(elems[3], NumberStyles.Any, Utils.Culture); double rp = double.Parse(elems[4], NumberStyles.Any, Utils.Culture); double ry = double.Parse(elems[5], NumberStyles.Any, Utils.Culture); Position = new Vector3d(x, y, z); Orientation = new Vector3d(rr, rp, ry); } public static readonly Pose Identity = new Pose(); } }
using DragonSpark.Compose; using DragonSpark.Model.Selection; using System; namespace DragonSpark.Model.Sequences.Collections.Groups; public readonly struct GroupName : IEquatable<GroupName> { public static bool operator ==(GroupName left, GroupName right) => left.Equals(right); public static bool operator !=(GroupName left, GroupName right) => !left.Equals(right); public GroupName(string name) => Name = name; public string Name { get; } public bool Equals(GroupName other) => string.Equals(Name, other.Name); public override bool Equals(object? obj) => obj is GroupName phase && Equals(phase); public override int GetHashCode() => Name.GetHashCode(); } sealed class GroupName<T> : Select<T, GroupName>, IGroupName<T> { public GroupName(GroupName defaultName, ISelect<string, GroupName> names) : base(Start.A.Selection<T>() .By.Returning(defaultName) .Unless.Using(new MetadataGroupName<T>(names)) .ResultsInAssigned()) {} }
using System; using System.Collections.Generic; using System.Text; namespace OutOfOrderCpuSimulator { class LoadStoreUnit : FunctionalUnit { private Dictionary<byte, int> OpCycleCost = new Dictionary<byte, int>() { { (byte)0x0, 1 }, // LW { (byte)0x2, 1 }, // LB { (byte)0x3, 1 }, // LBU { (byte)0x4, 1 }, // LH { (byte)0x5, 1 }, // LHU { (byte)0x6, 1 }, // SW { (byte)0x7, 1 }, // SB { (byte)0x8, 1 }, // SH { (byte)0x9, 1 }, // LDI { (byte)0xA, 1 }, // LDHI }; public LoadStoreUnit(CPU c) : base(c) { } public override bool AcceptsOp(byte op) { return OpCycleCost.ContainsKey(op); } protected override uint GetResult() { switch ((OpCodes.Op)this.Op) { case OpCodes.Op.LDI: return Const; case OpCodes.Op.LDHI: return (Const & 0x7ff) << 21; default: throw new Exception("Invalid instruction for IntegerUnit op=" + (int)this.Op); } } protected override int GetCycleCount(byte op, uint src1, uint src2, byte dst) { // Could depend on operands for cycle count return OpCycleCost[op]; } } }
using Application.Interfaces.DBContextInterfaces; using Domain.Entities; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Application.Repositories { public interface IOrderRepository : IBaseRepository<Order> { Task<List<OrderItem>> GetAllOrderItems(int orderId); Task<OrderItem> GetOrderOrderItemById(int orderId, int orderItemsId); } class OrderRepository : BaseRepository<Order>, IOrderRepository { private readonly IAppDbContext _context; public OrderRepository(IAppDbContext context) : base(context) { _context = context; } #region Order-item public async Task<List<OrderItem>> GetAllOrderItems(int tOneId) { return await _context.OrderItems.Where(x => x.OrderId.Equals(tOneId)) .Include(p => p.Product).ToListAsync(); } public async Task<OrderItem> GetOrderOrderItemById(int tOneId, int tTwoId) { return await _context.OrderItems.Where(x => x.OrderId.Equals(tOneId) && x.Id.Equals(tTwoId)) .Include(p => p.Product).FirstOrDefaultAsync(); } #endregion } }
namespace Com.Ericmas001.Windows.Validations { public class MinDigitValidationAttribute : DigitValidationAttribute { private readonly int m_Min; public MinDigitValidationAttribute(int min) { m_Min = min; } public override string Validate(string value) { if (string.IsNullOrEmpty(value)) return null; if (string.IsNullOrEmpty(base.Validate(value))) return null; return int.Parse(value) < m_Min ? $"The number must be >= {m_Min}!" : null; } } }
using SkiaSharp; using System.Collections.Generic; /* * Copyright 2017 Google, 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. */ /* * Copyright 2017 Google 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. */ //C++ TO C# CONVERTER WARNING: The following #include directive was ignored: //#include "third_party/skia/include/core/SkColor.h" //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_NOTHING_ARG1(arg1) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_NOTHING_ARG2(arg1, arg2) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_NOTHING_ARG3(arg1, arg2, arg3) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_RESTRICT __restrict //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_RESTRICT __restrict__ //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX512 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE42 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE41 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSSE3 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE3 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_AVX //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE2 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_CPU_SSE_LEVEL SK_CPU_SSE_LEVEL_SSE1 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_API __declspec(dllexport) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_API __declspec(dllimport) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_HAS_COMPILER_FEATURE(x) __has_feature(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_HAS_COMPILER_FEATURE(x) 0 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ATTRIBUTE(attr) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ATTRIBUTE(attr) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkNO_RETURN_HINT() do {} while (false) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_DUMP_GOOGLE3_STACK() DumpStackTrace(0, SkDebugfForDumpStackTrace, nullptr) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_DUMP_GOOGLE3_STACK() //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_DUMP_LINE_FORMAT(message) SkDebugf("%s(%d): fatal error: \"%s\"\n", __FILE__, __LINE__, message) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_DUMP_LINE_FORMAT(message) SkDebugf("%s:%d: fatal error: \"%s\"\n", __FILE__, __LINE__, message) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ABORT(message) do { SkNO_RETURN_HINT(); SK_DUMP_LINE_FORMAT(message); SK_DUMP_GOOGLE3_STACK(); sk_abort_no_print(); } while (false) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_COLOR_MATCHES_PMCOLOR_BYTE_ORDER (SK_A32_SHIFT == 24 && SK_R32_SHIFT == 16 && SK_G32_SHIFT == 8 && SK_B32_SHIFT == 0) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_PMCOLOR_BYTE_ORDER(C0, C1, C2, C3) (SK_ ## C3 ## 32_SHIFT == 0 && SK_ ## C2 ## 32_SHIFT == 8 && SK_ ## C1 ## 32_SHIFT == 16 && SK_ ## C0 ## 32_SHIFT == 24) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_PMCOLOR_BYTE_ORDER(C0, C1, C2, C3) (SK_ ## C0 ## 32_SHIFT == 0 && SK_ ## C1 ## 32_SHIFT == 8 && SK_ ## C2 ## 32_SHIFT == 16 && SK_ ## C3 ## 32_SHIFT == 24) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_UNUSED __pragma(warning(suppress:4189)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_UNUSED SK_ATTRIBUTE(unused) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ALWAYS_INLINE __forceinline //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ALWAYS_INLINE SK_ATTRIBUTE(always_inline) inline //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_NEVER_INLINE __declspec(noinline) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_NEVER_INLINE SK_ATTRIBUTE(noinline) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_PREFETCH(ptr) _mm_prefetch(reinterpret_cast<const char*>(ptr), _MM_HINT_T0) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_WRITE_PREFETCH(ptr) _mm_prefetch(reinterpret_cast<const char*>(ptr), _MM_HINT_T0) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_PREFETCH(ptr) __builtin_prefetch(ptr) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_WRITE_PREFETCH(ptr) __builtin_prefetch(ptr, 1) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_PREFETCH(ptr) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_WRITE_PREFETCH(ptr) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_PRINTF_LIKE(A, B) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_PRINTF_LIKE(A, B) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_GAMMA_EXPONENT (0.0f) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_HISTOGRAM_BOOLEAN(name, value) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_HISTOGRAM_ENUMERATION(name, value, boundary_value) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkASSERT_RELEASE(cond) static_cast<void>( (cond) ? (void)0 : []{ SK_ABORT("assert(" #cond ")"); }() ) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkASSERT(cond) SkASSERT_RELEASE(cond) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkASSERTF(cond, fmt, ...) static_cast<void>( (cond) ? (void)0 : [&]{ SkDebugf(fmt"\n", __VA_ARGS__); SK_ABORT("assert(" #cond ")"); }() ) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDEBUGFAIL(message) SK_ABORT(message) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDEBUGFAILF(fmt, ...) SkASSERTF(false, fmt, ##__VA_ARGS__) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDEBUGCODE(...) __VA_ARGS__ //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDEBUGF(...) SkDebugf(__VA_ARGS__) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkAssertResult(cond) SkASSERT(cond) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkASSERT(cond) static_cast<void>(0) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkASSERTF(cond, fmt, ...) static_cast<void>(0) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDEBUGFAIL(message) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDEBUGFAILF(fmt, ...) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDEBUGCODE(...) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDEBUGF(...) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkAssertResult(cond) if (cond) {} do {} while(false) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ARRAY_COUNT(array) (sizeof(SkArrayCountHelper(array))) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_MACRO_CONCAT(X, Y) SK_MACRO_CONCAT_IMPL_PRIV(X, Y) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_MACRO_CONCAT_IMPL_PRIV(X, Y) X ## Y //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_MACRO_APPEND_LINE(name) SK_MACRO_CONCAT(name, __LINE__) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_REQUIRE_LOCAL_VAR(classname) static_assert(false, "missing name for " #classname) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_BEGIN_REQUIRE_DENSE _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic error \"-Wpadded\"") //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_END_REQUIRE_DENSE _Pragma("GCC diagnostic pop") //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_INIT_TO_AVOID_WARNING = 0 //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define __inline static __inline //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarAs2sCompliment(x) SkFloatAs2sCompliment(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_sqrt(x) sqrtf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_sin(x) sinf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_cos(x) cosf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_tan(x) tanf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_floor(x) floorf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_ceil(x) ceilf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_trunc(x) truncf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_acos(x) static_cast<float>(acos(x)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_asin(x) static_cast<float>(asin(x)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_acos(x) acosf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_asin(x) asinf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_atan2(y,x) atan2f(y,x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_abs(x) fabsf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_copysign(x, y) copysignf(x, y) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_mod(x,y) fmodf(x,y) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_exp(x) expf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_log(x) logf(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_round(x) sk_float_floor((x) + 0.5f) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_log2(x) log2f(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_double_isnan(a) sk_float_isnan(a) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_MinS32FitsInFloat -SK_MaxS32FitsInFloat //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_MaxS64FitsInFloat (SK_MaxS64 >> (63-24) << (63-24)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_MinS64FitsInFloat -SK_MaxS64FitsInFloat //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_floor2int(x) sk_float_saturate2int(sk_float_floor(x)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_round2int(x) sk_float_saturate2int(sk_float_floor((x) + 0.5f)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_ceil2int(x) sk_float_saturate2int(sk_float_ceil(x)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_floor2int_no_saturate(x) (int)sk_float_floor(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_round2int_no_saturate(x) (int)sk_float_floor((x) + 0.5f) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_float_ceil2int_no_saturate(x) (int)sk_float_ceil(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_double_floor(x) floor(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_double_round(x) floor((x) + 0.5) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_double_ceil(x) ceil(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_double_floor2int(x) (int)floor(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_double_round2int(x) (int)floor((x) + 0.5) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define sk_double_ceil2int(x) (int)ceil(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_FloatNaN NAN //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_FloatInfinity (+INFINITY) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_FloatNegativeInfinity (-INFINITY) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_FLT_DECIMAL_DIG FLT_DECIMAL_DIG //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ScalarMax 3.402823466e+38f //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ScalarInfinity SK_FloatInfinity //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ScalarNegativeInfinity SK_FloatNegativeInfinity //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ScalarNaN SK_FloatNaN //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarFloorToScalar(x) sk_float_floor(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarCeilToScalar(x) sk_float_ceil(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarRoundToScalar(x) sk_float_floor((x) + 0.5f) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarTruncToScalar(x) sk_float_trunc(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarFloorToInt(x) sk_float_floor2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarCeilToInt(x) sk_float_ceil2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarRoundToInt(x) sk_float_round2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarAbs(x) sk_float_abs(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarCopySign(x, y) sk_float_copysign(x, y) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarMod(x, y) sk_float_mod(x,y) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarSqrt(x) sk_float_sqrt(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarPow(b, e) sk_float_pow(b, e) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarSin(radians) (float)sk_float_sin(radians) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarCos(radians) (float)sk_float_cos(radians) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarTan(radians) (float)sk_float_tan(radians) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarASin(val) (float)sk_float_asin(val) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarACos(val) (float)sk_float_acos(val) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarATan2(y, x) (float)sk_float_atan2(y,x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarExp(x) (float)sk_float_exp(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarLog(x) (float)sk_float_log(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarLog2(x) (float)sk_float_log2(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkIntToScalar(x) static_cast<SkScalar>(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkIntToFloat(x) static_cast<float>(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarTruncToInt(x) sk_float_saturate2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarToFloat(x) static_cast<float>(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkFloatToScalar(x) static_cast<SkScalar>(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarToDouble(x) static_cast<double>(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDoubleToScalar(x) sk_double_to_float(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ScalarMin (-SK_ScalarMax) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarDiv(numer, denom) sk_ieee_float_divide(numer, denom) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarInvert(x) sk_ieee_float_divide(SK_Scalar1, (x)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarFastInvert(x) sk_ieee_float_divide(SK_Scalar1, (x)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarAve(a, b) (((a) + (b)) * SK_ScalarHalf) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarHalf(a) ((a) * SK_ScalarHalf) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkDegreesToRadians(degrees) ((degrees) * (SK_ScalarPI / 180)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkRadiansToDegrees(radians) ((radians) * (180 / SK_ScalarPI)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SK_ScalarNearlyZero (SK_Scalar1 / (1 << 12)) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarFloor(x) sk_double_floor(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarCeil(x) sk_double_ceil(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarRound(x) sk_double_round(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarFloorToInt(x) sk_double_floor2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarCeilToInt(x) sk_double_ceil2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarRoundToInt(x) sk_double_round2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarFloor(x) sk_float_floor(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarCeil(x) sk_float_ceil(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarRound(x) sk_float_round(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarFloorToInt(x) sk_float_floor2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarCeilToInt(x) sk_float_ceil2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarRoundToInt(x) sk_float_round2int(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkIntToMScalar(n) static_cast<SkMScalar>(n) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkMScalarToScalar(x) SkMScalarToFloat(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkScalarToMScalar(x) SkFloatToMScalar(x) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkColorSetRGB(r, g, b) SkColorSetARGB(0xFF, r, g, b) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkColorGetA(color) (((color) >> 24) & 0xFF) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkColorGetR(color) (((color) >> 16) & 0xFF) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkColorGetG(color) (((color) >> 8) & 0xFF) //C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line: //ORIGINAL LINE: #define SkColorGetB(color) (((color) >> 0) & 0xFF) namespace FlutterBinding.Txt { public class TextStyle { public uint color = SK_ColorWHITE; public int decoration = (int)TextDecoration.kNone; // Does not make sense to draw a transparent object, so we use it as a default // value to indicate no decoration color was set. public uint decoration_color = SK_ColorTRANSPARENT; public TextDecorationStyle decoration_style = TextDecorationStyle.kSolid; // Thickness is applied as a multiplier to the default thickness of the font. public double decoration_thickness_multiplier = 1.0; public FontWeight font_weight = FontWeight.w400; public FontStyle font_style = FontStyle.normal; public TextBaseline text_baseline = TextBaseline.kAlphabetic; public string font_family; public double font_size = 14.0; public double letter_spacing = 0.0; public double word_spacing = 0.0; public double height = 1.0; public string locale; public bool has_background = false; public SKPaint background = new SKPaint(); public bool has_foreground = false; public SKPaint foreground = new SKPaint(); public List<TextShadow> text_shadows = new List<TextShadow>(); public TextStyle() { this.font_family = GetDefaultFontFamily(); } //C++ TO C# CONVERTER WARNING: 'const' methods are not available in C#: //ORIGINAL LINE: bool equals(const TextStyle& other) const public bool equals(TextStyle other) { if (color != other.color) { return false; } if (decoration != other.decoration) { return false; } if (decoration_color != other.decoration_color) { return false; } if (decoration_style != other.decoration_style) { return false; } if (decoration_thickness_multiplier != other.decoration_thickness_multiplier) { return false; } if (font_weight != other.font_weight) { return false; } if (font_style != other.font_style) { return false; } if (font_family != other.font_family) { return false; } if (letter_spacing != other.letter_spacing) { return false; } if (word_spacing != other.word_spacing) { return false; } if (height != other.height) { return false; } if (locale != other.locale) { return false; } if (foreground != other.foreground) { return false; } if (text_shadows.Count != other.text_shadows.Count) { return false; } for (int shadow_index = 0; shadow_index < text_shadows.Count; ++shadow_index) { if (text_shadows[shadow_index] != other.text_shadows[shadow_index]) { return false; } } return true; } } } // namespace FlutterBinding.Txt //C++ TO C# CONVERTER WARNING: The following #include directive was ignored: //#include "third_party/skia/include/core/SkColor.h"
using System; using System.Collections.Generic; using System.Linq; class Program { public static void Main() { var sequence = new[] { "A", "B", "C", "D" }; foreach (var subset in Subsets(sequence.Length).Where(s => !IsContinuous(s))) { Console.WriteLine(string.Join(" ", subset.Select(i => sequence[i]))); } } static IEnumerable<List<int>> Subsets(int length) { int[] values = Enumerable.Range(0, length).ToArray(); var stack = new Stack<int>(length); for (int i = 0; stack.Count > 0 || i < length; ) { if (i < length) { stack.Push(i++); yield return (from index in stack.Reverse() select values[index]).ToList(); } else { i = stack.Pop() + 1; if (stack.Count > 0) i = stack.Pop() + 1; } } } static bool IsContinuous(List<int> list) => list[list.Count - 1] - list[0] + 1 == list.Count; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace DuelBots { public class TypeSelectorWindow:Window { public TypeSelectorWindow(Rectangle MyRectangle, Rectangle HoverRectangle,bool ScrollLR,bool ScrollUD) : base(MyRectangle,HoverRectangle,false,false) { int PlaceX=40; int PlaceY=40; int SizeX = 48; int SizeY = 48; AddForm( new Button(Game1.contentManager.Load<Texture2D>("Editor/MouseModeSelect"), new Rectangle(PlaceX, PlaceY, SizeX, SizeY), new Rectangle(PlaceX, PlaceY, SizeX+16,SizeY+16), 4, SelectMouseSelect) ); PlaceX += 64; Button NewButton = null; AddForm( NewButton= new Button(Game1.contentManager.Load<Texture2D>("Editor/MouseModePlace"), new Rectangle(PlaceX, PlaceY, SizeX, SizeY), new Rectangle(PlaceX, PlaceY, SizeX + 16, SizeY + 16), 4, SelectMousePlace) ); NewButton.Selected = true; PlaceX += 64; AddForm( new Button(Game1.contentManager.Load<Texture2D>("Editor/MouseModeMove"), new Rectangle(PlaceX, PlaceY, SizeX, SizeY), new Rectangle(PlaceX, PlaceY, SizeX + 16, SizeY + 16), 4, SelectMouseMove) ); PlaceX += 64; AddForm( new Button(Game1.contentManager.Load<Texture2D>("Editor/MouseModeSquare"), new Rectangle(PlaceX, PlaceY, SizeX, SizeY), new Rectangle(PlaceX, PlaceY, SizeX + 16, SizeY + 16), 4, SelectMouseSquare) ); } public void SelectMouseMove(Button button) { DeselectButtons(); button.Selected = true; MasterEditor.mouseMode = MouseMode.Move; } public void SelectMousePlace(Button button) { DeselectButtons(); button.Selected = true; MasterEditor.mouseMode = MouseMode.Place; } public void SelectMouseSelect(Button button) { DeselectButtons(); button.Selected = true; MasterEditor.mouseMode = MouseMode.Select; } public void SelectMouseSquare(Button button) { DeselectButtons(); button.Selected = true; MasterEditor.mouseMode = MouseMode.Square; } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace ElmSampleApp { /// <summary> /// Simple page that displays "Hello World". Navigate to localhost/foo to see the elm logs /// </summary> public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddElm(options => { options.Path = new PathString("/foo"); // defaults to "/Elm" options.Filter = (name, level) => level >= LogLevel.Information; }); } public void Configure(IApplicationBuilder app, ILoggerFactory factory) { app.UseElmPage(); // Shows the logs at the specified path app.UseElmCapture(); // Adds the ElmLoggerProvider var logger = factory.CreateLogger<Startup>(); using (logger.BeginScope("startup")) { logger.LogWarning("Starting up"); } app.Run(async context => { await context.Response.WriteAsync("Hello world"); using (logger.BeginScope("world")) { logger.LogInformation("Hello world!"); logger.LogError("Mort"); } // This will not get logged because the filter has been set to LogLevel.Information and above using (logger.BeginScope("debug")) { logger.LogDebug("some debug stuff"); } }); logger.LogInformation("This message is not in a scope"); } public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using Sitecore.Diagnostics; namespace Rainbow.Storage.Yaml { public class YamlReader : IDisposable { private readonly StreamReader _reader; private const int IndentSpaces = 2; private const char IndentCharacter = ' '; private readonly PeekableStreamReaderAdapter _readerAdapter; private KeyValuePair<string, string>? _peek; public YamlReader(Stream stream, int bufferSize, bool leaveStreamOpen) { _reader = new StreamReader(stream, Encoding.UTF8, false, bufferSize, leaveStreamOpen); _readerAdapter = new PeekableStreamReaderAdapter(_reader); Assert.AreEqual("---", _readerAdapter.ReadLine(), "Invalid YAML format, missing expected --- header."); } public virtual Guid ReadExpectedGuidMap(string expectedKey) { return GetExpectedGuid(expectedKey, ReadExpectedMap); } public virtual string ReadExpectedMap(string expectedKey) { return GetExpectedMap(expectedKey, ReadMap); } public virtual KeyValuePair<string, string>? PeekMap() { if (_peek != null) return _peek.Value; var map = ReadMapInternal(); _peek = map; return map; } public virtual KeyValuePair<string, string>? ReadMap() { if (_peek != null) { var value = _peek.Value; _peek = null; return value; } return ReadMapInternal(); } protected virtual Guid GetExpectedGuid(string expectedKey, Func<string, string> mapFunction) { var guidString = mapFunction(expectedKey); Guid result; if (!Guid.TryParseExact(guidString, "D", out result)) throw new InvalidOperationException(CreateErrorMessage("YAML map value was not the valid GUID that was expected. Got " + guidString)); return result; } protected internal string GetExpectedMap(string expectedKey, Func<KeyValuePair<string, string>?> mapFunction) { var map = mapFunction(); if (map == null) throw new InvalidOperationException(CreateErrorMessage("Unable to read expected YAML map '" + expectedKey + "'; found end of file instead.")); if (!map.Value.Key.Equals(expectedKey, StringComparison.Ordinal)) throw new InvalidOperationException(CreateErrorMessage("Expected YAML map key '" + expectedKey + "' was not found. Instead found '" + map.Value.Key + "'")); return map.Value.Value; } protected virtual KeyValuePair<string, string>? ReadMapInternal() { var initialValue = ReadNextDataLine(); if (initialValue == null) return null; var mapIndex = initialValue.IndexOf(':'); Assert.IsTrue(mapIndex > 0, CreateErrorMessage("Invalid YAML map value (no : found) " + initialValue)); var currentIndent = GetIndent(initialValue); var mapKey = initialValue.Substring(currentIndent, mapIndex - currentIndent); // if the map has no value return it without parsing if (initialValue.Length < mapIndex + 2) return new KeyValuePair<string, string>(mapKey, string.Empty); var mapValue = initialValue.Substring(mapIndex + 2); mapValue = mapValue.Equals("|") ? ReadMultilineString(currentIndent + IndentSpaces) : Decode(mapValue); return new KeyValuePair<string, string>(mapKey, mapValue); } protected virtual string Decode(string value) { if (value.StartsWith("\"") && value.EndsWith("\"")) { return value.Substring(1, value.Length - 2).Replace(@"\""", "\""); } return value; } protected virtual string ReadMultilineString(int indent) { var lines = new List<string>(); do { string currentLine = _readerAdapter.PeekLine(); if (currentLine == null) break; var currentIndent = GetIndent(currentLine); if (currentIndent >= indent) { lines.Add(currentLine.Substring(indent)); _readerAdapter.ReadLine(); // consume the line we peeked } else break; } while (true); return string.Join(Environment.NewLine, lines); } protected int GetIndent(string line) { for (int i = 0; i < line.Length; i++) { // '-' = a list. for our DSL YAML that's for your visual reference only. if (line[i] != IndentCharacter && line[i] != '-') return i; } return line.Length; } protected string ReadNextDataLine() { do { string currentLine = _readerAdapter.ReadLine(); if (currentLine == null) return null; // blank line if (string.IsNullOrWhiteSpace(currentLine)) continue; var indent = GetIndent(currentLine); // comment line if (currentLine.Length > indent && currentLine[indent] == '#') continue; return currentLine; } while (true); } public string CreateErrorMessage(string message) { return "Line " + _readerAdapter.CurrentLine + ": " + message; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) _reader.Dispose(); } protected class PeekableStreamReaderAdapter { private readonly StreamReader _underlying; private string _peekedLine; private int _currentLine; public PeekableStreamReaderAdapter(StreamReader underlying) { _underlying = underlying; } public string PeekLine() { if (_peekedLine != null) return _peekedLine; string line = _underlying.ReadLine(); if (line == null) return null; _peekedLine = line; return line; } public int CurrentLine => _currentLine; public string ReadLine() { _currentLine++; if (_peekedLine != null) { var value = _peekedLine; _peekedLine = null; return value; } return _underlying.ReadLine(); } } } }
using System; using MediatR.AspNet; namespace WizardWorld.Application.Requests.Houses.Queries.GetHouseById { public class GetHouseByIdQuery : IQuery<HouseDto> { public Guid Id { get; set; } } }
using MarketDataViewer.Controls.ViewModels; using Moq; using NUnit.Framework; using Shouldly; namespace MarketDataViewer.Controls.Tests.ViewModels { [TestFixture] public class AddSymbolViewModelTests { private Mock<IStockSymbolService> _stockSymbolService; [SetUp] public void Setup() { _stockSymbolService = new Mock<IStockSymbolService>(); } [Test] [TestCase(true, false, "AAA", "")] // hide [TestCase(false, true, "AAA", "")] // show public void Changing_IsVisible_ShouldResetSymbol(bool isVisibleInitialValue, bool isVisibleNextValue, string symbolInitialValue, string symbolExpectedValue) { // arrange var vm = new AddSymbolViewModel { IsVisible = isVisibleInitialValue, Symbol = symbolInitialValue }; // act vm.IsVisible = isVisibleNextValue; // assert vm.Symbol.ShouldBe(symbolExpectedValue); } [Test] [TestCase("AAA", true)] [TestCase("", false)] public void CanAddSymbol_ShouldBeCorrect(string symbol, bool expected) { // arrange // act var vm = new AddSymbolViewModel { Symbol = symbol }; // assert vm.AddSymbolCommand.CanExecute().ShouldBe(expected); } [Test] [TestCase("AAA")] public void AddSymbol_ShouldCorrectlyAddSymbol(string symbol) { // arrange _stockSymbolService.Setup(x => x.AddSymbolAsync(It.Is<string>(s => s == symbol))); // act var vm = new AddSymbolViewModel { Symbol = symbol, StockSymbolService = _stockSymbolService.Object }; vm.AddSymbolCommand.Execute(); // assert _stockSymbolService.Verify(x => x.AddSymbolAsync(It.Is<string>(s => s == symbol))); vm.IsVisible.ShouldBe(false); } } }
// // LinkLabelTest.cs: MWF LinkLabel unit tests. // // Author: // Everaldo Canuto (ecanuto@novell.com) // // (C) 2007 Novell, Inc. (http://www.novell.com) // using System; using NUnit.Framework; using System.Windows.Forms; using System.Drawing; namespace MonoTests.System.Windows.Forms { [TestFixture] public class LinkLabelTest : TestHelper { [Test] public void LinkLabelAccessibility () { LinkLabel l = new LinkLabel (); Assert.IsNotNull (l.AccessibilityObject, "#1"); } [Test] public void TestTabStop () { LinkLabel l = new LinkLabel(); Assert.IsFalse (l.TabStop, "#1"); l.Text = "Hello"; Assert.IsTrue (l.TabStop, "#2"); l.Text = ""; Assert.IsFalse (l.TabStop, "#3"); } [Test] public void TestLinkArea () { LinkLabel l = new LinkLabel(); Assert.AreEqual (0, l.LinkArea.Start, "#1"); Assert.AreEqual (0, l.LinkArea.Length, "#2"); l.Text = "Hello"; Assert.AreEqual (0, l.LinkArea.Start, "#3"); Assert.AreEqual (5, l.LinkArea.Length, "#4"); l.Text = ""; Assert.AreEqual (0, l.LinkArea.Start, "#5"); Assert.AreEqual (0, l.LinkArea.Length, "#6"); } [Test] // bug #344012 public void InvalidateManualLinks () { Form form = new Form (); form.ShowInTaskbar = false; LinkLabel l = new LinkLabel (); l.Text = "linkLabel1"; form.Controls.Add (l); #if NET_2_0 LinkLabel.Link link = new LinkLabel.Link (2, 5); l.Links.Add (link); #else l.Links.Add (2, 5); #endif form.Show (); form.Dispose (); } [Test] // bug 410709 public void LinkAreaSetter () { // Basically this test is to show that setting LinkArea erased // any previous links LinkLabel l = new LinkLabel (); l.Text = "Really long text"; Assert.AreEqual (1, l.Links.Count, "A1"); l.Links.Clear (); l.Links.Add (0, 3); l.Links.Add (5, 3); Assert.AreEqual (2, l.Links.Count, "A2"); l.LinkArea = new LinkArea (1, 7); Assert.AreEqual (1, l.Links.Count, "A3"); Assert.AreEqual (1, l.LinkArea.Start, "A4"); Assert.AreEqual (7, l.LinkArea.Length, "A5"); } } #if NET_2_0 [TestFixture] public class LinkTest : TestHelper { [Test] public void Constructor () { LinkLabel.Link l = new LinkLabel.Link (); Assert.AreEqual (null, l.Description, "A1"); Assert.AreEqual (true, l.Enabled, "A2"); Assert.AreEqual (0, l.Length, "A3"); Assert.AreEqual (null, l.LinkData, "A4"); Assert.AreEqual (string.Empty, l.Name, "A5"); Assert.AreEqual (0, l.Start, "A6"); Assert.AreEqual (null, l.Tag, "A7"); Assert.AreEqual (false, l.Visited, "A8"); l = new LinkLabel.Link (5, 20); Assert.AreEqual (null, l.Description, "A9"); Assert.AreEqual (true, l.Enabled, "A10"); Assert.AreEqual (20, l.Length, "A11"); Assert.AreEqual (null, l.LinkData, "A12"); Assert.AreEqual (string.Empty, l.Name, "A13"); Assert.AreEqual (5, l.Start, "A14"); Assert.AreEqual (null, l.Tag, "A15"); Assert.AreEqual (false, l.Visited, "A16"); l = new LinkLabel.Link (3, 7, "test"); Assert.AreEqual (null, l.Description, "A17"); Assert.AreEqual (true, l.Enabled, "A18"); Assert.AreEqual (7, l.Length, "A19"); Assert.AreEqual ("test", l.LinkData, "A20"); Assert.AreEqual (string.Empty, l.Name, "A21"); Assert.AreEqual (3, l.Start, "A22"); Assert.AreEqual (null, l.Tag, "A23"); Assert.AreEqual (false, l.Visited, "A24"); } } #endif [TestFixture] public class LinkCollectionTest : TestHelper { [Test] // ctor (LinkLabel) public void Constructor1 () { LinkLabel l = new LinkLabel (); l.Text = "Managed Windows Forms"; LinkLabel.LinkCollection links1 = new LinkLabel.LinkCollection ( l); LinkLabel.LinkCollection links2 = new LinkLabel.LinkCollection ( l); Assert.AreEqual (1, links1.Count, "#A1"); Assert.IsFalse (links1.IsReadOnly, "#A2"); #if NET_2_0 Assert.IsFalse (links1.LinksAdded, "#A3"); #endif LinkLabel.Link link = links1 [0]; #if NET_2_0 Assert.IsNull (link.Description, "#B1"); #endif Assert.IsTrue (link.Enabled, "#B2"); Assert.AreEqual (21, link.Length, "#B3"); Assert.IsNull (link.LinkData, "#B4"); #if NET_2_0 Assert.IsNotNull (link.Name, "#B5"); Assert.AreEqual (string.Empty, link.Name, "#B6"); #endif Assert.AreEqual (0, link.Start, "#B7"); #if NET_2_0 Assert.IsNull (link.Tag, "#B8"); #endif Assert.IsFalse (link.Visited, "#B9"); Assert.AreEqual (1, links2.Count, "#C1"); Assert.IsFalse (links2.IsReadOnly, "#C2"); #if NET_2_0 Assert.IsFalse (links2.LinksAdded, "#C3"); #endif Assert.AreSame (link, links2 [0], "#C4"); } [Test] // ctor (LinkLabel) public void Constructor1_Owner_Null () { try { new LinkLabel.LinkCollection ((LinkLabel) null); Assert.Fail ("#1"); } catch (ArgumentNullException ex) { Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2"); Assert.IsNull (ex.InnerException, "#3"); Assert.IsNotNull (ex.Message, "#4"); Assert.IsNotNull (ex.ParamName, "#5"); Assert.AreEqual ("owner", ex.ParamName, "#6"); } } #if NET_2_0 [Test] // Add (LinkLabel.Link) public void Add1 () { LinkLabel l = new LinkLabel (); l.Text = "Managed Windows Forms"; LinkLabel.LinkCollection links1 = new LinkLabel.LinkCollection ( l); LinkLabel.LinkCollection links2 = new LinkLabel.LinkCollection ( l); LinkLabel.Link linkA = new LinkLabel.Link (0, 7); Assert.AreEqual (0, links1.Add (linkA), "#A1"); Assert.AreEqual (1, links1.Count, "#A2"); Assert.AreEqual (1, links2.Count, "#A3"); Assert.IsTrue (links1.LinksAdded, "#A4"); Assert.IsFalse (links2.LinksAdded, "#A5"); Assert.AreSame (linkA, links1 [0], "#A6"); Assert.AreSame (linkA, links2 [0], "#A7"); LinkLabel.Link linkB = new LinkLabel.Link (8, 7); Assert.AreEqual (1, links1.Add (linkB), "#B1"); Assert.AreEqual (2, links1.Count, "#B2"); Assert.AreEqual (2, links2.Count, "#B3"); Assert.IsTrue (links1.LinksAdded, "#B4"); Assert.IsFalse (links2.LinksAdded, "#B5"); Assert.AreSame (linkA, links1 [0], "#B6"); Assert.AreSame (linkA, links2 [0], "#B7"); Assert.AreSame (linkB, links1 [1], "#B8"); Assert.AreSame (linkB, links2 [1], "#B9"); LinkLabel.LinkCollection links3 = new LinkLabel.LinkCollection ( l); Assert.AreEqual (2, links3.Count, "#C1"); Assert.IsFalse (links3.LinksAdded, "#C2"); Assert.AreSame (linkA, links3 [0], "#C3"); Assert.AreSame (linkB, links3 [1], "#C4"); } [Test] // Add (LinkLabel.Link) public void Add1_Overlap () { LinkLabel l = new LinkLabel (); l.Text = "Managed Windows Forms"; LinkLabel.LinkCollection links = new LinkLabel.LinkCollection ( l); LinkLabel.Link linkA = new LinkLabel.Link (0, 7); links.Add (linkA); Assert.AreEqual (1, links.Count, "#A1"); Assert.IsTrue (links.LinksAdded, "#A2"); Assert.AreSame (linkA, links [0], "#A3"); LinkLabel.Link linkB = new LinkLabel.Link (5, 4); try { links.Add (linkB); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Overlapping link regions Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } Assert.AreEqual (2, links.Count, "#B5"); Assert.IsTrue (links.LinksAdded, "#B6"); Assert.AreSame (linkA, links [0], "#B7"); Assert.AreSame (linkB, links [1], "#B8"); Assert.AreEqual (0, linkA.Start, "#B9"); Assert.AreEqual (7, linkA.Length, "#B10"); Assert.AreEqual (5, linkB.Start, "#B11"); Assert.AreEqual (4, linkB.Length, "#B12"); LinkLabel.Link linkC = new LinkLabel.Link (14, 3); try { links.Add (linkC); Assert.Fail ("#C1"); } catch (InvalidOperationException ex) { // Overlapping link regions Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2"); Assert.IsNull (ex.InnerException, "#C3"); Assert.IsNotNull (ex.Message, "#C4"); } Assert.AreEqual (3, links.Count, "#C5"); Assert.IsTrue (links.LinksAdded, "#C6"); Assert.AreSame (linkA, links [0], "#C7"); Assert.AreSame (linkB, links [1], "#C8"); Assert.AreSame (linkC, links [2], "#C9"); Assert.AreEqual (0, linkA.Start, "#C10"); Assert.AreEqual (7, linkA.Length, "#C11"); Assert.AreEqual (5, linkB.Start, "#C12"); Assert.AreEqual (4, linkB.Length, "#C13"); Assert.AreEqual (14, linkC.Start, "#C14"); Assert.AreEqual (3, linkC.Length, "#C15"); } [Test] // Add (LinkLabel.Link) public void Add1_Value_Null () { LinkLabel l = new LinkLabel (); l.Text = "Managed Windows Forms"; LinkLabel.LinkCollection links = new LinkLabel.LinkCollection ( l); try { links.Add ((LinkLabel.Link) null); Assert.Fail ("#1"); } catch (NullReferenceException) { } } #endif [Test] // Add (int, int) public void Add2 () { LinkLabel l = new LinkLabel (); l.Text = "Managed Windows Forms"; LinkLabel.LinkCollection links1 = new LinkLabel.LinkCollection ( l); LinkLabel.LinkCollection links2 = new LinkLabel.LinkCollection ( l); LinkLabel.Link linkA = links1.Add (0, 7); Assert.AreEqual (1, links1.Count, "#A1"); Assert.AreEqual (1, links2.Count, "#A2"); #if NET_2_0 Assert.IsTrue (links1.LinksAdded, "#A3"); Assert.IsFalse (links2.LinksAdded, "#A4"); #endif Assert.AreSame (linkA, links1 [0], "#A5"); Assert.AreSame (linkA, links2 [0], "#A6"); LinkLabel.Link linkB = links1.Add (8, 7); Assert.AreEqual (2, links1.Count, "#B1"); Assert.AreEqual (2, links2.Count, "#B2"); #if NET_2_0 Assert.IsTrue (links1.LinksAdded, "#B3"); Assert.IsFalse (links2.LinksAdded, "#B4"); #endif Assert.AreSame (linkA, links1 [0], "#B5"); Assert.AreSame (linkA, links2 [0], "#B6"); Assert.AreSame (linkB, links1 [1], "#B7"); Assert.AreSame (linkB, links2 [1], "#B8"); LinkLabel.LinkCollection links3 = new LinkLabel.LinkCollection ( l); Assert.AreEqual (2, links3.Count, "#C1"); #if NET_2_0 Assert.IsFalse (links3.LinksAdded, "#C2"); #endif Assert.AreSame (linkA, links3 [0], "#C3"); Assert.AreSame (linkB, links3 [1], "#C4"); } [Test] // Add (int, int) public void Add2_Overlap () { LinkLabel l = new LinkLabel (); l.Text = "Managed Windows Forms"; LinkLabel.LinkCollection links = new LinkLabel.LinkCollection ( l); LinkLabel.Link linkA = links.Add (0, 7); Assert.AreEqual (1, links.Count, "#A1"); #if NET_2_0 Assert.IsTrue (links.LinksAdded, "#A2"); #endif Assert.AreSame (linkA, links [0], "#A3"); try { links.Add (5, 4); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Overlapping link regions Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNull (ex.InnerException, "#B3"); Assert.IsNotNull (ex.Message, "#B4"); } Assert.AreEqual (2, links.Count, "#B5"); #if NET_2_0 Assert.IsTrue (links.LinksAdded, "#B6"); #endif Assert.AreSame (linkA, links [0], "#B7"); Assert.IsNotNull (links [1], "#B8"); Assert.AreEqual (0, linkA.Start, "#B9"); Assert.AreEqual (7, linkA.Length, "#B10"); Assert.AreEqual (5, links [1].Start, "#B11"); Assert.AreEqual (4, links [1].Length, "#B12"); try { links.Add (14, 3); Assert.Fail ("#C1"); } catch (InvalidOperationException ex) { // Overlapping link regions Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2"); Assert.IsNull (ex.InnerException, "#C3"); Assert.IsNotNull (ex.Message, "#C4"); } Assert.AreEqual (3, links.Count, "#C5"); #if NET_2_0 Assert.IsTrue (links.LinksAdded, "#C6"); #endif Assert.AreSame (linkA, links [0], "#C7"); Assert.IsNotNull (links [1], "#C8"); Assert.IsNotNull (links [2], "#C9"); Assert.AreEqual (0, linkA.Start, "#C10"); Assert.AreEqual (7, linkA.Length, "#C11"); Assert.AreEqual (5, links [1].Start, "#C12"); Assert.AreEqual (4, links [1].Length, "#C13"); Assert.AreEqual (14, links [2].Start, "#C14"); Assert.AreEqual (3, links [2].Length, "#C15"); } } }
namespace BlueSun.Services.NFTCollections.Models { public class NFTCollectionQueryServiceModel { public int CurrentPage { get; init; } public int CollectionsPerPage { get; init; } public int TotalCollections { get; set; } public IEnumerable<NFTCollectionServiceModel> Collections { get; init; } } }
// // Copyright (C) 2012 DataStax 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; using System.Collections.Generic; namespace Cassandra.Data.Linq { public abstract class Batch : Statement { protected readonly ISession _session; protected BatchType _batchType = BatchType.Logged; protected DateTimeOffset? _timestamp = null; public abstract bool IsEmpty { get; } public override RoutingKey RoutingKey { get { return null; } } public QueryTrace QueryTrace { get; private set; } internal Batch(ISession session) { _session = session; } public abstract void Append(CqlCommand cqlCommand); public new Batch SetConsistencyLevel(ConsistencyLevel? consistencyLevel) { base.SetConsistencyLevel(consistencyLevel); return this; } public Batch SetTimestamp(DateTimeOffset timestamp) { _timestamp = timestamp; return this; } public void Append(IEnumerable<CqlCommand> cqlCommands) { foreach (CqlCommand cmd in cqlCommands) Append(cmd); } public void Execute() { EndExecute(BeginExecute(null, null)); } public abstract IAsyncResult BeginExecute(AsyncCallback callback, object state); public void EndExecute(IAsyncResult ar) { InternalEndExecute(ar); } private RowSet InternalEndExecute(IAsyncResult ar) { var tag = (CqlQueryTag) Session.GetTag(ar); var ctx = tag.Session; RowSet outp = ctx.EndExecute(ar); QueryTrace = outp.Info.QueryTrace; return outp; } protected struct CqlQueryTag { public ISession Session; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using DinnerSpinner.Domain.Model; namespace DinnerSpinner.Domain.Repositories { public interface ISpinnerRepository { Task<IList<Spinner>> GetAll(); Task<Spinner> GetById(Guid id); Task Save(Spinner s); Task<Spinner> RemoveById(Guid id); } }
using ServiceMonitor.Common.Contracts; namespace ServiceMonitor.Common { public class WatchResponse : IWatchResponse { public bool Successful { get; set; } public string ShortMessage { get; set; } public string FullMessage { get; set; } } }
using Microsoft.AspNetCore.Http; using System.Collections.Generic; namespace GovITHub.Auth.Common.Infrastructure.Localization { public class CsvImportDescription { public string Information { get; set; } public ICollection<IFormFile> File { get; set; } } }
namespace Unicorn.Internal { internal enum uc_query_type { // From unicorn.h /// <summary> /// Dynamically query current hardware mode. /// </summary> UC_QUERY_MODE = 1, /// <summary> /// query pagesize of engine /// </summary> UC_QUERY_PAGE_SIZE, /// <summary> /// query architecture of engine (for ARM to query Thumb mode) /// </summary> UC_QUERY_ARCH, /// <summary> /// query if emulation stops due to timeout (indicated if result = True) /// </summary> UC_QUERY_TIMEOUT } }
using System; namespace Barak.VersionPatcher.Engine { public enum VersionPart { Major, Minor, Build, Revision } public class PatchInfo { public string ForceVersionControlType { get; set; } public Uri SourceControlUrl { get; set; } public string VersionControlPath { get; set; } public string Revision { get; set; } public string FileSystemPath { get; set; } public bool Commit { get; set; } public string Comment { get; set; } public string[] ProjectFiles { get; set; } public bool Recursive { get; set; } public VersionPart VersionPart { get; set; } public string Username { get; set; } public string Passowrd { get; set; } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JdaTools.Studio.Models { public class MocaDirectory : IMocaFile { public string Type { get; set; } public string PathName { get; set; } public string FileName { get; set; } public string Description { get; set; } public List<IMocaFile> Files { get { if (_files == null) { RefreshFiles().ConfigureAwait(false); } return _files; } } public delegate Task<IEnumerable<IMocaFile>> RefreshFilesDelegate(); private readonly RefreshFilesDelegate _refreshFilesHandler; private List<IMocaFile> _files; public MocaDirectory(MocaFile mocaFile, RefreshFilesDelegate refreshFilesDelegate) { Type = "D"; PathName = mocaFile.PathName; FileName = mocaFile.FileName; _refreshFilesHandler = refreshFilesDelegate; } public async Task<List<IMocaFile>> RefreshFiles() { if (_refreshFilesHandler == null) { return null; } var files = await _refreshFilesHandler.Invoke(); _files = files.ToList(); return _files; } public override string ToString() { return FileName; } } // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0. }
private sealed class OrInstruction.OrBoolean : OrInstruction // TypeDefIndex: 2657 { // Methods // RVA: 0x191ACC0 Offset: 0x191ADC1 VA: 0x191ACC0 Slot: 8 public override int Run(InterpretedFrame frame) { } // RVA: 0x191ACB0 Offset: 0x191ADB1 VA: 0x191ACB0 public void .ctor() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace WebAddressbookTests { [TestFixture] public class DeleteContacts : AuthTestBase { [Test] public void DeleteContactByEditForm() { app.Contact.CheckForAvailabilityСontact(); List<ContactData> oldContacts = ContactData.GetAll(); ContactData toBeRemovedContact = oldContacts[0]; app.Contact.DeleteContactOnEdit(toBeRemovedContact); app.Navigator.GoToHomePage(); List<ContactData> newContacts = ContactData.GetAll(); oldContacts.RemoveAt(0); oldContacts.Sort(); newContacts.Sort(); Assert.AreEqual(oldContacts, newContacts); foreach (ContactData contact in newContacts) { Assert.AreNotEqual(contact.Id, toBeRemovedContact.Id); } } [Test] public void DeleteContactByHomePage() { app.Contact.CheckForAvailabilityСontact(); List<ContactData> oldContact = ContactData.GetAll(); ContactData toBeRemovedContact = oldContact[0]; app.Contact.SelectContactOnHomePage(toBeRemovedContact.Id); app.Contact.DeleteContOnHome(); app.Navigator.GoToHomePage(); List<ContactData> newContact = ContactData.GetAll(); oldContact.RemoveAt(0); oldContact.Sort(); newContact.Sort(); Assert.AreEqual(oldContact, newContact); foreach(ContactData contact in newContact) { Assert.AreNotEqual(contact.Id, toBeRemovedContact.Id); } } } }
namespace Castle.Services.Transaction.IO { ///<summary> /// Small interface for the map path functionality. ///</summary> public interface IMapPath { ///<summary> /// Gets the absolute path given a string formatted /// as a map path, for example: /// "~/plugins" or "plugins/integrated" or "C:\a\b\c.txt" or "\\?\C:\a\b" /// would all be valid map paths. ///</summary> ///<param name="path"></param> ///<returns></returns> string MapPath(string path); } }
using System.IO; namespace Dalamud.Divination.Common.Api.Definition { public static class DefinitionProviderFactory<TContainer> where TContainer : DefinitionContainer, new() { public static IDefinitionProvider<TContainer> Create(string url) { var filename = Path.GetFileName(url); #if DEBUG return new LocalDefinitionProvider<TContainer>(filename, url); #else return new RemoteDefinitionProvider<TContainer>(url, filename); #endif } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Orleans; using Squidex.Areas.Api.Controllers.Backups.Models; using Squidex.Domain.Apps.Entities.Backup; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.Orleans; using Squidex.Infrastructure.Security; using Squidex.Pipeline; using Squidex.Shared; namespace Squidex.Areas.Api.Controllers.Backups { /// <summary> /// Manages backups for apps. /// </summary> [ApiExplorerSettings(GroupName = nameof(Backups))] public class RestoreController : ApiController { private readonly IGrainFactory grainFactory; public RestoreController(ICommandBus commandBus, IGrainFactory grainFactory) : base(commandBus) { this.grainFactory = grainFactory; } /// <summary> /// Get current restore status. /// </summary> /// <returns> /// 200 => Status returned. /// </returns> [HttpGet] [Route("apps/restore/")] [ProducesResponseType(typeof(RestoreJobDto), 200)] [ApiPermission(Permissions.AdminRestoreRead)] public async Task<IActionResult> GetJob() { var restoreGrain = grainFactory.GetGrain<IRestoreGrain>(SingleGrain.Id); var job = await restoreGrain.GetJobAsync(); if (job.Value == null) { return NotFound(); } var response = RestoreJobDto.FromJob(job.Value); return Ok(response); } /// <summary> /// Restore a backup. /// </summary> /// <param name="request">The backup to restore.</param> /// <returns> /// 204 => Restore operation started. /// </returns> [HttpPost] [Route("apps/restore/")] [ApiPermission(Permissions.AdminRestoreCreate)] public async Task<IActionResult> PostRestore([FromBody] RestoreRequest request) { var restoreGrain = grainFactory.GetGrain<IRestoreGrain>(SingleGrain.Id); await restoreGrain.RestoreAsync(request.Url, User.Token(), request.Name); return NoContent(); } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.InteropServices; namespace _10._Multiply_Even_By_Odds { class Program { static void Main(string[] args) { int number = int.Parse(Console.ReadLine()); int result = GetResult(number); Console.WriteLine(result); } private static int GetResult(int number) { int result = GetEvenNumbers(number) * GetOddNumbers(number); return result; } private static int GetOddNumbers(int number) { number = Math.Abs(number); string input = number.ToString(); int sumOdd = 0; foreach (var currentDigit in input) { int currentNumber = int.Parse(currentDigit.ToString()); if (currentNumber % 2 != 0) { sumOdd += currentNumber; } } return sumOdd; } private static int GetEvenNumbers(int number) { number = Math.Abs(number); string input = number.ToString(); int sumEven = 0; foreach (var currentDigit in input) { int currentNumber = int.Parse(currentDigit.ToString()); if (currentDigit % 2 == 0) { sumEven += currentNumber; } } return sumEven; } } }
using System; namespace Norml.Common.Helpers { public delegate void ExceptionOccurredHandler(object sender, ExceptionEventArgs e); public interface IRetryHelper { event ExceptionOccurredHandler ExceptionOccurred; void Retry(Action action, RetryPolicy retryPolicy = RetryPolicy.ThrowException, int numberOfRetries = 3); TItem Retry<TItem>(Func<TItem> action, RetryPolicy retryPolicy = RetryPolicy.ThrowException, int numberOfRetries = 3); } }
namespace SharpScript { #region public ScriptType public enum ScriptType { CSharp, VB, } #endregion #region internal CompilerType internal enum CompilerType { CodeDom, Roslyn, } #endregion #region internal ExitCode internal enum ExitCode { Success = 0, InvalidArg = 1, Exception = 2, Cancelled = 3, UnhandledException = 4, } #endregion }
@model WebStatus.ViewModels.HealthStatusViewModel @{ ViewData["Title"] = "System Status"; } <div class="row"> <div class="col-md-12"> <h2 class="overall-status-title">Overall Status: @Model.OverallStatus</h2> </div> </div> <div class="list-group-status"> @foreach (var result in Model.Results) { <div class="row list-group-status-item"> <div class="col-md-10"> <h4 class="list-group-status-item-title">@result.Name</h4> <p class="list-group-item-text"> @if (result.Result.Data.ContainsKey("url")) { <p>@result.Result.Data["url"]</p> } @result.Result.Description </p> </div> <div class="col-md-2 list-group-status-item-label"> @if (@result.Result.CheckStatus == Microsoft.Extensions.HealthChecks.CheckStatus.Healthy) { <span class="label label-success">@result.Result.CheckStatus</span> } else if (@result.Result.CheckStatus == Microsoft.Extensions.HealthChecks.CheckStatus.Unhealthy) { <span class="label label-danger">@result.Result.CheckStatus</span> } else if (@result.Result.CheckStatus == Microsoft.Extensions.HealthChecks.CheckStatus.Warning) { <span class="label label-warning">@result.Result.CheckStatus</span> } else { <span class="label label-default">@result.Result.CheckStatus</span> } </div> </div> } </div>
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZEGO { public class ZegoMediaPlayerImpl:ZegoMediaPlayer { public override void LoadResource(string path, OnLoadResourceCallback onLoadResourceCallback) { this.onLoadResourceCallback = onLoadResourceCallback; ZegoExpressEngineImpl.LoadResource(this, path); } public override void EnableRepeat(bool enable) { ZegoExpressEngineImpl.EnableRepeat(this, enable); } public override void Start() { ZegoExpressEngineImpl.Start(this); } public override void Pause() { ZegoExpressEngineImpl.Pause(this); } public override void Resume() { ZegoExpressEngineImpl.Resume(this); } public override void Stop() { ZegoExpressEngineImpl.Stop(this); } public override ZegoMediaPlayerState GetCurrentState() { return ZegoExpressEngineImpl.GetCurrentState(this); } public override void SeekTo(ulong millisecond, OnSeekToTimeCallback onSeekToTimeCallback) { ZegoExpressEngineImpl.SeekTo(this, millisecond, onSeekToTimeCallback); } public override void EnableAux(bool enable) { ZegoExpressEngineImpl.EnableAux(this, enable); } public override void MuteLocal(bool mute) { ZegoExpressEngineImpl.MuteLocal(this, mute); } public override void SetPlayerCanvas(ZegoCanvas canvas) { ZegoExpressEngineImpl.SetPlayerCanvas(this, canvas); } public override void SetVolume(int volume) { ZegoExpressEngineImpl.SetVolume(this, volume); } public override void SetProgressInterval(ulong millisecond) { ZegoExpressEngineImpl.SetProgressInterval(this, millisecond); } public override ulong GetTotalDuration() { return ZegoExpressEngineImpl.GetTotalDuration(this); } public override ulong GetCurrentProgress() { return ZegoExpressEngineImpl.GetCurrentProgress(this); } public override int GetIndex() { return ZegoExpressEngineImpl.GetIndex(this); } public override void SetVideoHandler(OnVideoFrame onVideoFrame, ZegoVideoFrameFormat format) { this.onVideoFrame = onVideoFrame; ZegoExpressEngineImpl.SetVideoHandler(this, format, onVideoFrame); } public override void SetAudioHandler(OnAudioFrame onAudioFrame) { this.onAudioFrame = onAudioFrame; ZegoExpressEngineImpl.SetAudioHandler(this, onAudioFrame); } public override void SetPlayVolume(int volume) { ZegoExpressEngineImpl.SetMediaPlayerPlayVolume(this, volume); } public override void SetPublishVolume(int volume) { ZegoExpressEngineImpl.SetMediaPlayerPublishVolume(this, volume); } public override int GetPlayVolume() { return ZegoExpressEngineImpl.GetMediaPlayerPlayVolume(this); } public override int GetPublishVolume() { return ZegoExpressEngineImpl.GetMediaPlayerPublishVolume(this); } } }
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.471/blob/master/LICENSE * */ #endregion using System.Windows.Forms; namespace ExtendedMenuToolbarItems.Controls { public class ClearClipboard : MenuItem { #region Variables #endregion #region Constructor public ClearClipboard() { Text = "Clear &&Clipboard"; } #endregion #region Methods private bool IsClipboardEmpty() => Clipboard.ContainsText(); #endregion } }
using System.Collections.Generic; using System.Text.RegularExpressions; using ReviewApp.Location.Core.Application.Wikipedia; using ReviewApp.Location.Infrastructure.Extensions; using ReviewApp.Location.Infrastructure.Services; namespace ReviewApp.Location.Infrastructure.Handlers.WikiTableHandlers { public sealed class TableRowHeadersHandler : TableBaseHandler { protected override void HandlerRequestInternal(ref string content, List<WikiTableRowBase> rows) { var collections = RegexExtension.GetMatches(content, RegexPattern.TableHeaderMatchPattern); var header = new WikiTableRowBaseHeader(); foreach (Match collection in collections) { header.Content.Add(GetHeaderContent(collection.Value)); } rows.Add(header); } private static string GetHeaderContent(string @string) { var matches = RegexExtension.GetMatches(@string, RegexPattern.TableTextHeaderMatchPattern); var contentValue = matches[0].Value; RegexExtension.Replace(ref contentValue, RegexPattern.BracesReplacePattern); return contentValue; } } }
using EnvDTE; using Xunit; namespace NuGet.VisualStudio.Test { public class ProjectExtensionsTest { [Fact] public void GetOutputPathForWebSite() { // Arrange Project project = TestUtils.GetProject("WebProject", VsConstants.WebSiteProjectTypeGuid); // Act string path = project.GetOutputPath(); // Assert Assert.Equal(@"WebProject\Bin", path); } } }
using social_journal.BL.DTO; using System.Collections.Generic; using System.Threading.Tasks; namespace social_journal.BL.Services.Interfaces { public interface IJournalProfileService { Task<ProfileDTO> GetUserProfile(); Task<IEnumerable<AchievementDTO>> GetUserAchievements(); Task<IEnumerable<PostDTO>> GetUserPosts(); } }
// Add Method in ItemType (e.g. Part) -> Server Events -> Event: onAfterGet for (int i = 0; i < this.getItemCount()-1; i++) { string bg_color_state; string myCss = ""; Item thisItem = this.getItemByIndex(i); string thisStatus = thisItem.getProperty("state",""); // Choose color for 'State' switch (thisStatus) { case "Preliminary": case "In Review": case "In Change": bg_color_state = "#FFFFBB"; // light yellow break; case "Released": bg_color_state = "#90EE90"; // light green break; case "Superseded": case "Obsolete" : bg_color_state = "#FFBBBB"; // light red break; default: bg_color_state = ""; // none break; } // set background color if (bg_color_state != "") { myCss = ".state { background-color: " + bg_color_state + " }" ; } thisItem.setProperty("css",myCss); } return this;
using KeyManagement.Repository; using KeyManagement.Repository.Entities; using KeyManagment.Bus; using KeyManagment.Bus.Queries; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace KeyManagement.Logic.Queries { public class GetKey : BaseQuery<Key> { public GetKeyParams QueryParams { get; private set; } public static GetKey Create(GetKeyParams queryParams) { return new GetKey { QueryParams = queryParams }; } protected async override Task<Key> ExecuteInternal(IQueryContext queryContext) { var context = ((BusContext)queryContext).DataContext; return await context.Keys.FirstOrDefaultAsync(e => e.Id == QueryParams.KeyId); } } }
using System; using System.Collections.Generic; using System.Net; using EzSurvey.Core.Application; using EzSurvey.Core.Domain; using EzSurvey.Core.Shared.Converters; using EzSurvey.Infrastructure.Authentication; using EzSurvey.Infrastructure.JobQueue; using EzSurvey.Infrastructure.Logging.Extensions; using EzSurvey.Infrastructure.Mail; using EzSurvey.Infrastructure.Persistence; using EzSurvey.Presentation.WebApi.Auth; using EzSurvey.Presentation.WebApi.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace EzSurvey.Presentation.WebApi { internal sealed class Startup { private IConfiguration Configuration { get; } private IWebHostEnvironment HostEnvironment { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; } /// <summary> /// This method gets called by the runtime. /// Use this method to configure the HTTP request pipeline. /// </summary> public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { HostEnvironment = env; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseServiceOverview(); app.UseCustomizedSwagger(); } else { app.UseExceptionHandler("/error"); app.UseHsts(); } app.UseEzLogging(); app.UseMiddleware(typeof(ExceptionHandlingMiddleware)); // todo: if Dev allowAnyOrigin else allow app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/_health"); endpoints.MapControllers(); endpoints.MapFallback(async req => { req.Response.StatusCode = (int) HttpStatusCode.NotFound; await req.Response.WriteAsJsonAsync("unknown endpoint"); }); }); } /// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddControllers() .ConfigureApiBehaviorOptions(o => { if (HostEnvironment.IsDevelopment()) { o.InvalidModelStateResponseFactory = ctx => new BadRequestObjectResult(ctx.ToString()); } // don't leak internal exceptions else { o.InvalidModelStateResponseFactory = _ => new BadRequestObjectResult("Internal Server Error"); } }) .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new SurveyQuestionConverter()); }); // Add Custom Layers services.AddApplicationLayer(); services.AddPersistenceLayer(Configuration.GetConnectionString("DefaultConnection")); services.AddDomainLayer(); services.AddEmailTemplates(); services.AddJobQueue(Configuration.GetConnectionString("HangfireConnection")); services.AddIdentity(); services.AddAuthenticationLayer(Configuration); // Timespan for different tokens services.Configure<DataProtectionTokenProviderOptions>(opt => opt.TokenLifespan = TimeSpan.FromHours(8)); services.Configure<EmailConfirmationTokenProviderOptions>(opt => opt.TokenLifespan = TimeSpan.FromDays(3)); // Add Other services.AddSwagger(); services.Configure<ServiceOverviewConfiguration>(cfg => { cfg.Services = new List<ServiceDescriptor>(services); }); services.AddHttpContextAccessor(); services.AddHealthChecks(); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DAL.Core; using DAL.Repositories; using Domain; using Microsoft.EntityFrameworkCore; namespace DAL.EF.Repositories { public class ContactEFRepository : EFRepository<Contact>, IContactRepository { public ContactEFRepository(IDataContext dataContext) : base(dataContext) { } public override IEnumerable<Contact> All() { return RepositoryDbSet.Include(a => a.Person).Include(b => b.ContactType).ToList(); } public override async Task<IEnumerable<Contact>> AllAsync() { return await RepositoryDbSet.Include(a => a.Person).Include(b => b.ContactType).ToListAsync(); } public override Contact Find(params object[] id) { var entity = base.Find(id); if (entity == null) return null; RepositoryDbContext.Entry(entity).Reference(a => a.Person).Load(); RepositoryDbContext.Entry(entity).Reference(a => a.ContactType).Load(); return entity; } public override async Task<Contact> FindAsync(params object[] id) { var entity = await base.FindAsync(id); if (entity == null) return null; RepositoryDbContext.Entry(entity).Reference(a => a.Person).Load(); RepositoryDbContext.Entry(entity).Reference(a => a.ContactType).Load(); return entity; } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; namespace SpaceGraphicsToolkit { [CanEditMultipleObjects] [CustomEditor(typeof(SgtProceduralScale))] public class SgtProceduralScale_Editor : SgtProcedural_Editor<SgtProceduralScale> { protected override void OnInspector() { base.OnInspector(); BeginError(Any(t => t.BaseScale == Vector3.zero)); DrawDefault("BaseScale", "The default scale of your object."); EndError(); DrawDefault("ScaleMultiplierMin", "The minimum multiplication of the BaseScale."); DrawDefault("ScaleMultiplierMax", "The maximum multiplication of the BaseScale."); } } } #endif namespace SpaceGraphicsToolkit { /// <summary>This component rotates the current GameObject along a random axis, with a random speed.</summary> [HelpURL(SgtHelper.HelpUrlPrefix + "SgtProceduralScale")] [AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Procedural Scale")] public class SgtProceduralScale : SgtProcedural { /// <summary>The default scale of your object.</summary> public Vector3 BaseScale = Vector3.one; /// <summary>The minimum multiplication of the BaseScale.</summary> public float ScaleMultiplierMin = 1.0f; /// <summary>The maximum multiplication of the BaseScale.</summary> public float ScaleMultiplierMax = 2.0f; protected override void DoGenerate() { transform.localScale = BaseScale * Mathf.Lerp(ScaleMultiplierMin, ScaleMultiplierMax, Random.value); } } }
#nullable enable using System; using System.Linq; using MSFramework.Domain; using MSFramework.Extensions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace MSFramework.AspNetCore.Infrastructure { public class EnumerationConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); } else if (value.GetType().IsSubclassOf(typeof(Enumeration))) { writer.WriteValue(((Enumeration) value).Id); } else { throw new MSFrameworkException(122, " no support json output"); } } public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { JToken token = JToken.Load(reader); var value = token?.ToString(); var isNullable = objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Nullable<>); var enumType = objectType; if (isNullable) { enumType = objectType.GetGenericArguments().FirstOrDefault(); } if (value.IsNullOrEmpty()) { if (isNullable) { return null; } throw new MSFrameworkException(122, $" {reader.Path} 不支持空值"); } try { var enumeration = Enumeration.GetAll(enumType).FirstOrDefault(i => i.Id == value); if (enumeration != null) { return enumeration; } } catch (Exception) { // 异常数据,不允许绑定 throw new MSFrameworkException(122, $" {reader.Path} 不支持绑定值 {value}"); } // 异常数据,不允许绑定 throw new MSFrameworkException(122, $" {reader.Path} 不支持绑定值 {value}"); } public override bool CanConvert(Type objectType) { return objectType.IsSubclassOf(typeof(Enumeration)); } } }
using Cirilla.Core.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Cirilla.Core.Test.Tests { [TestClass] public class ITMTests { [TestMethod] public void Load__itemData() { ITM itm = new ITM(Utility.GetFullPath(@"chunk0/common/item/itemData.itm")); } } }
/* * Copyright 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 location-2020-11-19.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.LocationService.Model { /// <summary> /// Container for the parameters to the GetMapTile operation. /// Retrieves a vector data tile from the map resource. Map tiles are used by clients /// to render a map. they're addressed using a grid arrangement with an X coordinate, /// Y coordinate, and Z (zoom) level. /// /// /// <para> /// The origin (0, 0) is the top left of the map. Increasing the zoom level by 1 doubles /// both the X and Y dimensions, so a tile containing data for the entire world at (0/0/0) /// will be split into 4 tiles at zoom 1 (1/0/0, 1/0/1, 1/1/0, 1/1/1). /// </para> /// </summary> public partial class GetMapTileRequest : AmazonLocationServiceRequest { private string _mapName; private string _x; private string _y; private string _z; /// <summary> /// Gets and sets the property MapName. /// <para> /// The map resource to retrieve the map tiles from. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=100)] public string MapName { get { return this._mapName; } set { this._mapName = value; } } // Check to see if MapName property is set internal bool IsSetMapName() { return this._mapName != null; } /// <summary> /// Gets and sets the property X. /// <para> /// The X axis value for the map tile. /// </para> /// </summary> [AWSProperty(Required=true)] public string X { get { return this._x; } set { this._x = value; } } // Check to see if X property is set internal bool IsSetX() { return this._x != null; } /// <summary> /// Gets and sets the property Y. /// <para> /// The Y axis value for the map tile. /// </para> /// </summary> [AWSProperty(Required=true)] public string Y { get { return this._y; } set { this._y = value; } } // Check to see if Y property is set internal bool IsSetY() { return this._y != null; } /// <summary> /// Gets and sets the property Z. /// <para> /// The zoom value for the map tile. /// </para> /// </summary> [AWSProperty(Required=true)] public string Z { get { return this._z; } set { this._z = value; } } // Check to see if Z property is set internal bool IsSetZ() { return this._z != null; } } }
namespace Sudoku.Core.Test { using FluentAssertions; using Xunit; public class PuzzleSolverTest { private readonly PuzzleSolver testee; public PuzzleSolverTest() { this.testee = new PuzzleSolver(); } [Fact] public void ParsesPuzzle() { var puzzle = SudokuPuzzle.Parse(@" 534 678 912 672 195 348 198 342 567 859 761 423 426 853 791 713 924 856 961 537 284 287 419 635 345 286 179 "); puzzle[1, 1].Should().Be(5); puzzle[1, 2].Should().Be(3); puzzle[1, 3].Should().Be(4); puzzle[1, 4].Should().Be(6); puzzle[1, 5].Should().Be(7); puzzle[1, 6].Should().Be(8); puzzle[1, 7].Should().Be(9); puzzle[1, 8].Should().Be(1); puzzle[1, 9].Should().Be(2); puzzle[2, 1].Should().Be(6); puzzle[2, 2].Should().Be(7); puzzle[2, 3].Should().Be(2); puzzle[2, 4].Should().Be(1); puzzle[2, 5].Should().Be(9); puzzle[2, 6].Should().Be(5); puzzle[2, 7].Should().Be(3); puzzle[2, 8].Should().Be(4); puzzle[2, 9].Should().Be(8); puzzle[3, 1].Should().Be(1); puzzle[3, 2].Should().Be(9); puzzle[3, 3].Should().Be(8); puzzle[3, 4].Should().Be(3); puzzle[3, 5].Should().Be(4); puzzle[3, 6].Should().Be(2); puzzle[3, 7].Should().Be(5); puzzle[3, 8].Should().Be(6); puzzle[3, 9].Should().Be(7); puzzle[4, 1].Should().Be(8); puzzle[4, 2].Should().Be(5); puzzle[4, 3].Should().Be(9); puzzle[4, 4].Should().Be(7); puzzle[4, 5].Should().Be(6); puzzle[4, 6].Should().Be(1); puzzle[4, 7].Should().Be(4); puzzle[4, 8].Should().Be(2); puzzle[4, 9].Should().Be(3); puzzle[5, 1].Should().Be(4); puzzle[5, 2].Should().Be(2); puzzle[5, 3].Should().Be(6); puzzle[5, 4].Should().Be(8); puzzle[5, 5].Should().Be(5); puzzle[5, 6].Should().Be(3); puzzle[5, 7].Should().Be(7); puzzle[5, 8].Should().Be(9); puzzle[5, 9].Should().Be(1); puzzle[6, 1].Should().Be(7); puzzle[6, 2].Should().Be(1); puzzle[6, 3].Should().Be(3); puzzle[6, 4].Should().Be(9); puzzle[6, 5].Should().Be(2); puzzle[6, 6].Should().Be(4); puzzle[6, 7].Should().Be(8); puzzle[6, 8].Should().Be(5); puzzle[6, 9].Should().Be(6); puzzle[7, 1].Should().Be(9); puzzle[7, 2].Should().Be(6); puzzle[7, 3].Should().Be(1); puzzle[7, 4].Should().Be(5); puzzle[7, 5].Should().Be(3); puzzle[7, 6].Should().Be(7); puzzle[7, 7].Should().Be(2); puzzle[7, 8].Should().Be(8); puzzle[7, 9].Should().Be(4); puzzle[8, 1].Should().Be(2); puzzle[8, 2].Should().Be(8); puzzle[8, 3].Should().Be(7); puzzle[8, 4].Should().Be(4); puzzle[8, 5].Should().Be(1); puzzle[8, 6].Should().Be(9); puzzle[8, 7].Should().Be(6); puzzle[8, 8].Should().Be(3); puzzle[8, 9].Should().Be(5); puzzle[9, 1].Should().Be(3); puzzle[9, 2].Should().Be(4); puzzle[9, 3].Should().Be(5); puzzle[9, 4].Should().Be(2); puzzle[9, 5].Should().Be(8); puzzle[9, 6].Should().Be(6); puzzle[9, 7].Should().Be(1); puzzle[9, 8].Should().Be(7); puzzle[9, 9].Should().Be(9); } [Fact] public void SolvesVeryEasyPuzzle() { var puzzle = SudokuPuzzle.Parse(@" 534 678 912 672 195 348 198 342 567 859 761 423 426 853 791 713 924 856 961 537 284 287 419 635 345 286 179 "); var result = this.testee.Solve(puzzle); Assert.False(true, "Not yet implemented"); } [Fact] public void GetsValueOfABox() { byte?[] expectedBox1 = { 5, 3, 4, 6, 7, 2, 1, 9, 8 }; byte?[] expectedBox2 = { 6, 7, 8, 1, 9, 5, 3, 4, 2 }; byte?[] expectedBox3 = { 9, 1, 2, 3, 4, 8, 5, 6, 7 }; byte?[] expectedBox4 = { 8, 5, 9, 4, 2, 6, 7, 1, 3 }; byte?[] expectedBox5 = { 7, 6, 1, 8, 5, 3, 9, 2, 4 }; byte?[] expectedBox6 = { 4, 2, 3, 7, 9, 1, 8, 5, 6 }; byte?[] expectedBox7 = { 9, 6, 1, 2, 8, 7, 3, 4, 5 }; byte?[] expectedBox8 = { 5, 3, 7, 4, 1, 9, 2, 8, 6 }; byte?[] expectedBox9 = { 2, 8, 4, 6, 3, 5, 1, 7, 9 }; var puzzle = SudokuPuzzle.Parse(@" 534 678 912 672 195 348 198 342 567 859 761 423 426 853 791 713 924 856 961 537 284 287 419 635 345 286 179 "); var box1 = puzzle.GetValuesOfBox(1); var box2 = puzzle.GetValuesOfBox(2); var box3 = puzzle.GetValuesOfBox(3); var box4 = puzzle.GetValuesOfBox(4); var box5 = puzzle.GetValuesOfBox(5); var box6 = puzzle.GetValuesOfBox(6); var box7 = puzzle.GetValuesOfBox(7); var box8 = puzzle.GetValuesOfBox(8); var box9 = puzzle.GetValuesOfBox(9); Assert.Equal(expectedBox1, box1); Assert.Equal(expectedBox2, box2); Assert.Equal(expectedBox3, box3); Assert.Equal(expectedBox4, box4); Assert.Equal(expectedBox5, box5); Assert.Equal(expectedBox6, box6); Assert.Equal(expectedBox7, box7); Assert.Equal(expectedBox8, box8); Assert.Equal(expectedBox9, box9); } } }
namespace Gtk.Core { public interface Container : Widget { void Add(GWidget widget); } }
namespace AnimalRescue.DataAccess.Mongodb.QueryBuilders { internal interface IAliasStore { Alias GetAlias<T>(string aliasePropertyName); } }
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Maverick.WebSockets { internal sealed class WebSocketStream : IWebSocketStream { public WebSocketStream( HttpContext context, Stream stream ) { m_context = context; m_stream = stream; } public Boolean CloseAfterWrite { get; set; } public ValueTask<Int32> ReadAsync( Memory<Byte> buffer ) => m_stream.ReadAsync( buffer ); public ValueTask WriteAsync( ReadOnlyMemory<Byte> buffer ) => m_stream.WriteAsync( buffer ); public void Close( Boolean abort ) { if ( abort ) { m_context.Abort(); } m_stream.Dispose(); } private readonly HttpContext m_context; private readonly Stream m_stream; } }
using Havit.Blazor.Components.Web // <------ ADD THIS LINE using Havit.Blazor.Components.Web.Bootstrap // <------ ADD THIS LINE public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("app"); // ... shortened for brevity builder.Services.AddHxServices(); // <------ ADD THIS LINE await builder.Build().RunAsync(); }
using RePacker.Buffers; namespace RePacker.Builder { internal class TypeResolver<TPacker, T> where TPacker : IPacker<T> { static TPacker defaultPacker = default(TPacker); public static TPacker Packer { get => defaultPacker; set => defaultPacker = value; } public void Pack(ReBuffer buffer, ref T value) { defaultPacker.Pack(buffer, ref value); } public void Unpack(ReBuffer buffer, out T value) { defaultPacker.Unpack(buffer, out value); } public void UnpackInto(ReBuffer buffer, ref T value) { defaultPacker.UnpackInto(buffer, ref value); } } }
using System.ComponentModel.DataAnnotations; namespace COMOEQEPROFESSORAMIGRACAOPONTODEINTERRROGACAO.Models { public class Cartas { [Key] public int ID { get; set; } public Mana mana_ { get; set; } public Atributos atributos_ { get; set; } public ValorDanoResistencia valorDanores_ { get; set; } public string descricao { get; set; } public Cartas(int id ,string descricao, int incolor, int vermelho, int verde, int azul, int preto, int branco, bool ameacar, bool vinculovida, bool toquemortifero, bool indestrutivel, bool voar, bool defensor, int dano, int resistencia ) { this.ID = id; this.descricao = descricao; this.mana_ = new Mana(incolor,vermelho,verde,azul,preto,branco); this.atributos_ =new Atributos(ameacar,vinculovida,toquemortifero,indestrutivel, voar,defensor); this.valorDanores_ = new ValorDanoResistencia( dano,resistencia); } /* public bool VerTerreno() { if (this.mana_ == null) { return true; } else { return false; } } public bool VerDifCreature() { if (this.valorDanores_ == null) { return true; } else { return false; } }*/ } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Dns.Models; namespace Azure.ResourceManager.Dns { /// <summary> The RecordSets service client. </summary> public partial class RecordSetsOperations { private readonly ClientDiagnostics _clientDiagnostics; private readonly HttpPipeline _pipeline; internal RecordSetsRestOperations RestClient { get; } /// <summary> Initializes a new instance of RecordSetsOperations for mocking. </summary> protected RecordSetsOperations() { } /// <summary> Initializes a new instance of RecordSetsOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="subscriptionId"> Specifies the Azure subscription ID, which uniquely identifies the Microsoft Azure subscription. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> internal RecordSetsOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string subscriptionId, Uri endpoint = null, string apiVersion = "2018-05-01") { RestClient = new RecordSetsRestOperations(clientDiagnostics, pipeline, subscriptionId, endpoint, apiVersion); _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } /// <summary> Updates a record set within a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="relativeRecordSetName"> The name of the record set, relative to the name of the zone. </param> /// <param name="recordType"> The type of DNS record in this record set. </param> /// <param name="parameters"> Parameters supplied to the Update operation. </param> /// <param name="ifMatch"> The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent changes. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<RecordSet>> UpdateAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.Update"); scope.Start(); try { return await RestClient.UpdateAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Updates a record set within a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="relativeRecordSetName"> The name of the record set, relative to the name of the zone. </param> /// <param name="recordType"> The type of DNS record in this record set. </param> /// <param name="parameters"> Parameters supplied to the Update operation. </param> /// <param name="ifMatch"> The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting concurrent changes. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<RecordSet> Update(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.Update"); scope.Start(); try { return RestClient.Update(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates or updates a record set within a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="relativeRecordSetName"> The name of the record set, relative to the name of the zone. </param> /// <param name="recordType"> The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). </param> /// <param name="parameters"> Parameters supplied to the CreateOrUpdate operation. </param> /// <param name="ifMatch"> The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent changes. </param> /// <param name="ifNoneMatch"> Set to &apos;*&apos; to allow a new record set to be created, but to prevent updating an existing record set. Other values will be ignored. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<RecordSet>> CreateOrUpdateAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = null, string ifNoneMatch = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.CreateOrUpdate"); scope.Start(); try { return await RestClient.CreateOrUpdateAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Creates or updates a record set within a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="relativeRecordSetName"> The name of the record set, relative to the name of the zone. </param> /// <param name="recordType"> The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). </param> /// <param name="parameters"> Parameters supplied to the CreateOrUpdate operation. </param> /// <param name="ifMatch"> The etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag value to prevent accidentally overwriting any concurrent changes. </param> /// <param name="ifNoneMatch"> Set to &apos;*&apos; to allow a new record set to be created, but to prevent updating an existing record set. Other values will be ignored. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<RecordSet> CreateOrUpdate(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = null, string ifNoneMatch = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.CreateOrUpdate"); scope.Start(); try { return RestClient.CreateOrUpdate(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Deletes a record set from a DNS zone. This operation cannot be undone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="relativeRecordSetName"> The name of the record set, relative to the name of the zone. </param> /// <param name="recordType"> The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). </param> /// <param name="ifMatch"> The etag of the record set. Omit this value to always delete the current record set. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response> DeleteAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.Delete"); scope.Start(); try { return await RestClient.DeleteAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Deletes a record set from a DNS zone. This operation cannot be undone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="relativeRecordSetName"> The name of the record set, relative to the name of the zone. </param> /// <param name="recordType"> The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). </param> /// <param name="ifMatch"> The etag of the record set. Omit this value to always delete the current record set. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response Delete(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = null, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.Delete"); scope.Start(); try { return RestClient.Delete(resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets a record set. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="relativeRecordSetName"> The name of the record set, relative to the name of the zone. </param> /// <param name="recordType"> The type of DNS record in this record set. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<RecordSet>> GetAsync(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.Get"); scope.Start(); try { return await RestClient.GetAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets a record set. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="relativeRecordSetName"> The name of the record set, relative to the name of the zone. </param> /// <param name="recordType"> The type of DNS record in this record set. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<RecordSet> Get(string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.Get"); scope.Start(); try { return RestClient.Get(resourceGroupName, zoneName, relativeRecordSetName, recordType, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Lists the record sets of a specified type in a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="recordType"> The type of record sets to enumerate. </param> /// <param name="top"> The maximum number of record sets to return. If not specified, returns up to 100 record sets. </param> /// <param name="recordsetnamesuffix"> The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .&lt;recordSetNameSuffix&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="zoneName"/> is null. </exception> public virtual AsyncPageable<RecordSet> ListByTypeAsync(string resourceGroupName, string zoneName, RecordType recordType, int? top = null, string recordsetnamesuffix = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (zoneName == null) { throw new ArgumentNullException(nameof(zoneName)); } async Task<Page<RecordSet>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListByType"); scope.Start(); try { var response = await RestClient.ListByTypeAsync(resourceGroupName, zoneName, recordType, top, recordsetnamesuffix, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<RecordSet>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListByType"); scope.Start(); try { var response = await RestClient.ListByTypeNextPageAsync(nextLink, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Lists the record sets of a specified type in a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="recordType"> The type of record sets to enumerate. </param> /// <param name="top"> The maximum number of record sets to return. If not specified, returns up to 100 record sets. </param> /// <param name="recordsetnamesuffix"> The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .&lt;recordSetNameSuffix&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="zoneName"/> is null. </exception> public virtual Pageable<RecordSet> ListByType(string resourceGroupName, string zoneName, RecordType recordType, int? top = null, string recordsetnamesuffix = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (zoneName == null) { throw new ArgumentNullException(nameof(zoneName)); } Page<RecordSet> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListByType"); scope.Start(); try { var response = RestClient.ListByType(resourceGroupName, zoneName, recordType, top, recordsetnamesuffix, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<RecordSet> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListByType"); scope.Start(); try { var response = RestClient.ListByTypeNextPage(nextLink, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Lists all record sets in a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="top"> The maximum number of record sets to return. If not specified, returns up to 100 record sets. </param> /// <param name="recordsetnamesuffix"> The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .&lt;recordSetNameSuffix&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="zoneName"/> is null. </exception> public virtual AsyncPageable<RecordSet> ListByDnsZoneAsync(string resourceGroupName, string zoneName, int? top = null, string recordsetnamesuffix = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (zoneName == null) { throw new ArgumentNullException(nameof(zoneName)); } async Task<Page<RecordSet>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListByDnsZone"); scope.Start(); try { var response = await RestClient.ListByDnsZoneAsync(resourceGroupName, zoneName, top, recordsetnamesuffix, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<RecordSet>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListByDnsZone"); scope.Start(); try { var response = await RestClient.ListByDnsZoneNextPageAsync(nextLink, resourceGroupName, zoneName, top, recordsetnamesuffix, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Lists all record sets in a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="top"> The maximum number of record sets to return. If not specified, returns up to 100 record sets. </param> /// <param name="recordsetnamesuffix"> The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .&lt;recordSetNameSuffix&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="zoneName"/> is null. </exception> public virtual Pageable<RecordSet> ListByDnsZone(string resourceGroupName, string zoneName, int? top = null, string recordsetnamesuffix = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (zoneName == null) { throw new ArgumentNullException(nameof(zoneName)); } Page<RecordSet> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListByDnsZone"); scope.Start(); try { var response = RestClient.ListByDnsZone(resourceGroupName, zoneName, top, recordsetnamesuffix, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<RecordSet> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListByDnsZone"); scope.Start(); try { var response = RestClient.ListByDnsZoneNextPage(nextLink, resourceGroupName, zoneName, top, recordsetnamesuffix, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Lists all record sets in a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="top"> The maximum number of record sets to return. If not specified, returns up to 100 record sets. </param> /// <param name="recordSetNameSuffix"> The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .&lt;recordSetNameSuffix&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="zoneName"/> is null. </exception> public virtual AsyncPageable<RecordSet> ListAllByDnsZoneAsync(string resourceGroupName, string zoneName, int? top = null, string recordSetNameSuffix = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (zoneName == null) { throw new ArgumentNullException(nameof(zoneName)); } async Task<Page<RecordSet>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListAllByDnsZone"); scope.Start(); try { var response = await RestClient.ListAllByDnsZoneAsync(resourceGroupName, zoneName, top, recordSetNameSuffix, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<RecordSet>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListAllByDnsZone"); scope.Start(); try { var response = await RestClient.ListAllByDnsZoneNextPageAsync(nextLink, resourceGroupName, zoneName, top, recordSetNameSuffix, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Lists all record sets in a DNS zone. </summary> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="zoneName"> The name of the DNS zone (without a terminating dot). </param> /// <param name="top"> The maximum number of record sets to return. If not specified, returns up to 100 record sets. </param> /// <param name="recordSetNameSuffix"> The suffix label of the record set name that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will return only records that end with .&lt;recordSetNameSuffix&gt;. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="resourceGroupName"/> or <paramref name="zoneName"/> is null. </exception> public virtual Pageable<RecordSet> ListAllByDnsZone(string resourceGroupName, string zoneName, int? top = null, string recordSetNameSuffix = null, CancellationToken cancellationToken = default) { if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (zoneName == null) { throw new ArgumentNullException(nameof(zoneName)); } Page<RecordSet> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListAllByDnsZone"); scope.Start(); try { var response = RestClient.ListAllByDnsZone(resourceGroupName, zoneName, top, recordSetNameSuffix, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<RecordSet> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope("RecordSetsOperations.ListAllByDnsZone"); scope.Start(); try { var response = RestClient.ListAllByDnsZoneNextPage(nextLink, resourceGroupName, zoneName, top, recordSetNameSuffix, cancellationToken); return Page.FromValues(response.Value.Value, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } } }
//--------------------------------------------------------------------- // <copyright file="DefaultServiceWrapper.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.Test.OData.Tests.Client { /// <summary> /// Implementation is mostly in ServiceWrapper base class. /// </summary> public class DefaultServiceWrapper : ServiceWrapper { /// <summary> /// Initializes a new instance of the DefaultServiceWrapper class. /// </summary> /// <param name="descriptor">Descriptor for the service to wrap.</param> public DefaultServiceWrapper(ServiceDescriptor descriptor) { ServiceProcess.StartInfo.Arguments = string.Format("{0} {1} a", (int)descriptor.IPCCommand, (int)IPCCommandMap.ServiceType.Default); } } }
using System; namespace Accord.Domain.Model { public class VoiceSession { public int Id { get; set; } public ulong UserId { get; set; } public virtual User User { get; set; } = null!; public string DiscordSessionId { get; set; } = null!; public ulong DiscordChannelId { get; set; } public DateTimeOffset StartDateTime { get; set; } public DateTimeOffset? EndDateTime { get; set; } public double? MinutesInVoiceChannel { get; set; } public bool HasBeenCountedToXp { get; set; } } }
using System; using Microsoft.EntityFrameworkCore; namespace DGAuthServer.ModelsDB; /// <summary> /// /// </summary> public class DgAuthDbContext : DbContext { #pragma warning disable CS8618 // 생성자를 종료할 때 null을 허용하지 않는 필드에 null이 아닌 값을 포함해야 합니다. null 허용으로 선언해 보세요. public DgAuthDbContext(DbContextOptions<DgAuthDbContext> options) #pragma warning restore CS8618 // 생성자를 종료할 때 null을 허용하지 않는 필드에 null이 아닌 값을 포함해야 합니다. null 허용으로 선언해 보세요. : base(options) { } #pragma warning disable CS8618 // 생성자를 종료할 때 null을 허용하지 않는 필드에 null이 아닌 값을 포함해야 합니다. null 허용으로 선언해 보세요. public DgAuthDbContext() #pragma warning restore CS8618 // 생성자를 종료할 때 null을 허용하지 않는 필드에 null이 아닌 값을 포함해야 합니다. null 허용으로 선언해 보세요. { } protected override void OnConfiguring(DbContextOptionsBuilder options) { if (null != DGAuthServerGlobal.ActDbContextOnConfiguring) { DGAuthServerGlobal.ActDbContextOnConfiguring(options); } } /// <summary> /// 엑세스 토큰 /// </summary> public DbSet<DgAuthAccessToken> DGAuthServer_AccessToken { get; set; } /// <summary> /// 리플레시 토큰 /// </summary> public DbSet<DgAuthRefreshToken> DGAuthServer_RefreshToken { get; set; } /// <summary> /// /// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(ModelBuilder modelBuilder) { } }
using LazuriteUI.Windows.Controls; using System; using System.Windows.Controls; namespace LazuriteUI.Windows.Main.Constructors { /// <summary> /// Логика взаимодействия для SelectCoreActionView.xaml /// </summary> public partial class SelectCoreActionView : UserControl { public SelectCoreActionView() { InitializeComponent(); listItems.SelectionChanged += (o, e) => { var selectedItem = listItems.SelectedItem; if (selectedItem!=null) { Selected?.Invoke(((ItemView)selectedItem).Tag as Type); } }; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1009:DeclareEventHandlersCorrectly")] public event Action<Type> Selected; public static void Show(Action<Type> callback) { var control = new SelectCoreActionView(); var dialog = new DialogView(control); control.Selected += (type) => { callback(type); dialog.Close(); }; dialog.ShowUnderCursor = true; dialog.Show(); } } }
using System; namespace Zoey.Quartz.Domain.Model { public class Log { /// <summary> /// 执行时间 /// </summary> public DateTime ExecutionTime { get; set; } /// <summary> /// IP /// </summary> public string ClientIpAddress { get; set; } /// <summary> /// 浏览器信息 /// </summary> public string BrowserInfo { get; set; } /// <summary> /// 用户信息 /// </summary> public string UserName { get; set; } /// <summary> /// 内容 /// </summary> public string Content { get; set; } } }
using Gma.QrCodeNet.Encoding.Positioning.Stencils; namespace Gma.QrCodeNet.Encoding.Positioning; internal static class PositioningPatternBuilder { internal static void EmbedBasicPatterns(int version, TriStateMatrix matrix) { new PositionDetectionPattern(version).ApplyTo(matrix); new DarkDotAtLeftBottom(version).ApplyTo(matrix); new AlignmentPattern(version).ApplyTo(matrix); new TimingPattern(version).ApplyTo(matrix); } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Hangfire.Common; using Hangfire.Console.Serialization; using Hangfire.Console.Storage; using Hangfire.Dashboard; using Hangfire.States; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Hangfire.Console.Dashboard { /// <summary> /// Provides progress for jobs. /// </summary> internal class JobProgressDispatcher : IDashboardDispatcher { internal static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() }; // ReSharper disable once NotAccessedField.Local private readonly ConsoleOptions _options; public JobProgressDispatcher(ConsoleOptions options) { _options = options ?? throw new ArgumentNullException(nameof(options)); } public async Task Dispatch(DashboardContext context) { if (!"POST".Equals(context.Request.Method, StringComparison.OrdinalIgnoreCase)) { context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; return; } var result = new Dictionary<string, double>(); var jobIds = await context.Request.GetFormValuesAsync("jobs[]"); if (jobIds.Count > 0) { // there are some jobs to process using (var connection = context.Storage.GetConnection()) using (var storage = new ConsoleStorage(connection)) { foreach (var jobId in jobIds) { var state = connection.GetStateData(jobId); if (state != null && string.Equals(state.Name, ProcessingState.StateName, StringComparison.OrdinalIgnoreCase)) { var consoleId = new ConsoleId(jobId, JobHelper.DeserializeDateTime(state.Data["StartedAt"])); var progress = storage.GetProgress(consoleId); if (progress.HasValue) result[jobId] = progress.Value; } else { // return -1 to indicate the job is not in Processing state result[jobId] = -1; } } } } var serialized = JsonConvert.SerializeObject(result, JsonSettings); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(serialized); } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Xap { [Serializable] [DebuggerDisplay( "{m_waveBanks.Count} WaveBanks, {m_soundBanks.Count} SoundBanks")] public class Project { // Xap.Project does NOT inherit from Xap.Entity, as it lacks the curly braces, // but is otherwise very similar (and everything it contains is an Entity) /// <summary> /// Parses in a XAP file. /// </summary> /// <param name="source">A collection of the strings in the XAP file, for example /// as received from System.IO.File.ReadAllLines().</param> public void Parse( string[] source ) { int line = 0; string property; string value; while ( line < source.Length ) { if ( Parser.TokeniseLine( source[line], out property, out value ) ) { if ( !SetProperty( property, value, source, ref line ) ) { throw new InvalidContentException( "Line " + line.ToString() + " is unexpected ('" + property + "', '" + value + "')" ); } } ++line; } } public bool SetProperty( string propertyName, string value, string[] source, ref int line ) { if ( Parser.TokeniseLine( source[line], out propertyName, out value ) ) { switch ( propertyName ) { case "Signature": m_signature = value; break; case "Version": m_version = Parser.ParseInt( value, line ); break; case "Content Version": m_contentVersion = Parser.ParseInt( value, line ); break; case "Release": m_release = value; break; case "Options": m_options = new Options(); m_options.Parse( source, ref line, this ); break; case "Global Settings": m_globalSettings = new GlobalSettings(); m_globalSettings.Parse( source, ref line, this ); break; case "Wave Bank": WaveBank waveBank = new WaveBank(); waveBank.Parse( source, ref line, this ); m_waveBanks.Add( waveBank ); break; case "Sound Bank": SoundBank soundBank = new SoundBank(); soundBank.Parse( source, ref line, this ); m_soundBanks.Add( soundBank ); break; case "Workspace": Workspace workspace = new Workspace(); workspace.Parse( source, ref line, this ); m_workspaces.Add( workspace ); break; default: return false; } } return true; } #region Member variables public string m_sourceXactFileName; // Full path including .xap // TODO could later use this information to change how we parse projects, as they change over time public string m_signature; // eg. "XACT2" public int m_version; // eg. 16 public int m_contentVersion; // eg. 43 public string m_release; // eg. "August 2007" public Options m_options = new Options(); public GlobalSettings m_globalSettings = new GlobalSettings(); public List<WaveBank> m_waveBanks = new List<WaveBank>(); public List<SoundBank> m_soundBanks = new List<SoundBank>(); public List<Workspace> m_workspaces = new List<Workspace>(); #endregion } }
namespace Rebus.HttpGateway { public class RebusHttpHeaders { public const string CustomHeaderPrefix = "rebus-x-"; public const string Id = "rebus-message-ID"; } }
using System; namespace _11.UnderstandingDelegates { public class MainListing1X75 { public delegate int Calculate(int x, int y); public int Add(int x, int y) => x + y; public int Multiply(int x, int y) => x * y; // Using Delegate public MainListing1X75() { Calculate calc = Add; Console.WriteLine(calc(3,4)); // Displays 7 calc = Multiply; Console.WriteLine(calc(3,4)); // Displays 12 Console.ReadLine(); } } }