content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 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 System; using System.Collections.Generic; using System.Threading; using Moq; using NUnit.Framework; using XenAdmin.Actions; using XenAPI; namespace XenAdminTests.XenModelTests { [TestFixture, Category(TestCategories.UICategoryB)] public class DestroyPolicyActionTests:ActionTestBase { private readonly AutoResetEvent _autoResetEvent=new AutoResetEvent(false); [Test] public void TestEmptyList() { var action = new DestroyPolicyAction(mockConnection.Object, new List<VMPP>()); action.Completed += action_Completed; action.RunAsync(); _autoResetEvent.WaitOne(); Assert.True(action.Succeeded); mockProxy.VerifyAll(); } void action_Completed(ActionBase sender) { _autoResetEvent.Set(); } [Test] public void TestOneInList() { mockProxy.Setup(x => x.vmpp_destroy(It.IsAny<string>(), "1")).Returns(new Response<string>("")); mockProxy.Setup(x => x.vm_set_protection_policy(It.IsAny<string>(), "1", It.IsAny<string>())).Returns(new Response<string>("")); var action = new DestroyPolicyAction(mockConnection.Object, new List<VMPP>() {new VMPP(){opaque_ref = "1",VMs = new List<XenRef<VM>>(){new XenRef<VM>("1")}}}); action.Completed += action_Completed; action.RunAsync(); _autoResetEvent.WaitOne(); Assert.True(action.Succeeded,action.Exception!=null?action.Exception.ToString():""); mockProxy.VerifyAll(); mockProxy.Verify(x => x.vm_set_protection_policy(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once()); } [Test] public void TestOneWithTwonVMsInList() { mockProxy.Setup(x => x.vmpp_destroy(It.IsAny<string>(),"1")).Returns(new Response<string>("")); mockProxy.Setup(x => x.vm_set_protection_policy(It.IsAny<string>(), It.Is<string>(s=>s=="1"||s=="2"), It.IsAny<string>())).Returns(new Response<string>("")); var action = new DestroyPolicyAction(mockConnection.Object, new List<VMPP>() { new VMPP() { opaque_ref = "1", VMs = new List<XenRef<VM>>() { new XenRef<VM>("1"), new XenRef<VM>("2") } } }); action.Completed += action_Completed; action.RunAsync(); _autoResetEvent.WaitOne(); Assert.True(action.Succeeded, action.Exception != null ? action.Exception.ToString() : ""); mockProxy.Verify(x => x.vm_set_protection_policy(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(2)); mockProxy.VerifyAll(); } } }
44.37234
170
0.65428
[ "BSD-2-Clause" ]
wdxgy136/xenadmin-yeesan
XenAdminTests/XenModelTests/DestroyPolicyActionTests.cs
4,173
C#
namespace Antlr4CodeCompletion.CoreUnitTest.Grammar { public partial class ExprLexer { } public partial class ANTLRv4Lexer { } public partial class ANTLRv4Parser { } }
19
52
0.715789
[ "MIT" ]
kaby76/antlr4-c3
ports/c#/test/Antlr4CodeCompletion.CoreUnitTest/Grammar/Expr.g4.lexer.cs
192
C#
using System.Diagnostics.CodeAnalysis; using Content.Shared.Physics; using Robust.Shared.GameObjects; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Physics.Broadphase; namespace Content.Shared.Spawning { public static class EntitySystemExtensions { public static EntityUid? SpawnIfUnobstructed( this IEntityManager entityManager, string? prototypeName, EntityCoordinates coordinates, CollisionGroup collisionLayer, in Box2? box = null, SharedPhysicsSystem? physicsManager = null) { physicsManager ??= EntitySystem.Get<SharedPhysicsSystem>(); var mapCoordinates = coordinates.ToMap(entityManager); return entityManager.SpawnIfUnobstructed(prototypeName, mapCoordinates, collisionLayer, box, physicsManager); } public static EntityUid? SpawnIfUnobstructed( this IEntityManager entityManager, string? prototypeName, MapCoordinates coordinates, CollisionGroup collisionLayer, in Box2? box = null, SharedPhysicsSystem? collision = null) { var boxOrDefault = box.GetValueOrDefault(Box2.UnitCentered).Translated(coordinates.Position); collision ??= EntitySystem.Get<SharedPhysicsSystem>(); foreach (var body in collision.GetCollidingEntities(coordinates.MapId, in boxOrDefault)) { if (!body.Hard) { continue; } // TODO: wtf fix this if (collisionLayer == 0 || (body.CollisionMask & (int) collisionLayer) == 0) { continue; } return null; } return entityManager.SpawnEntity(prototypeName, coordinates); } public static bool TrySpawnIfUnobstructed( this IEntityManager entityManager, string? prototypeName, EntityCoordinates coordinates, CollisionGroup collisionLayer, [NotNullWhen(true)] out EntityUid? entity, Box2? box = null, SharedPhysicsSystem? physicsManager = null) { entity = entityManager.SpawnIfUnobstructed(prototypeName, coordinates, collisionLayer, box, physicsManager); return entity != null; } public static bool TrySpawnIfUnobstructed( this IEntityManager entityManager, string? prototypeName, MapCoordinates coordinates, CollisionGroup collisionLayer, [NotNullWhen(true)] out EntityUid? entity, in Box2? box = null, SharedPhysicsSystem? physicsManager = null) { entity = entityManager.SpawnIfUnobstructed(prototypeName, coordinates, collisionLayer, box, physicsManager); return entity != null; } } }
35.104651
121
0.613117
[ "MIT" ]
A-Box-12/space-station-14
Content.Shared/Spawning/EntitySystemExtensions.cs
3,021
C#
using System; using UnityEditor; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [CustomEditor(typeof(Tonemapping))] class TonemappingEditor : Editor { SerializedObject serObj; SerializedProperty type; // CURVE specific parameter SerializedProperty remapCurve; SerializedProperty exposureAdjustment; // REINHARD specific parameter SerializedProperty middleGrey; SerializedProperty white; SerializedProperty adaptionSpeed; SerializedProperty adaptiveTextureSize; void OnEnable() { serObj = new SerializedObject(target); type = serObj.FindProperty("type"); remapCurve = serObj.FindProperty("remapCurve"); exposureAdjustment = serObj.FindProperty("exposureAdjustment"); middleGrey = serObj.FindProperty("middleGrey"); white = serObj.FindProperty("white"); adaptionSpeed = serObj.FindProperty("adaptionSpeed"); adaptiveTextureSize = serObj.FindProperty("adaptiveTextureSize"); } public override void OnInspectorGUI() { serObj.Update(); GUILayout.Label("Mapping HDR to LDR ranges since 1982", EditorStyles.miniLabel); Camera cam = (target as Tonemapping).GetComponent<Camera>(); if (cam != null) { if (!cam.hdr) { EditorGUILayout.HelpBox("The camera is not HDR enabled. This will likely break the Tonemapper.", MessageType.Warning); } else if (!(target as Tonemapping).validRenderTextureFormat) { EditorGUILayout.HelpBox( "The input to Tonemapper is not in HDR. Make sure that all effects prior to this are executed in HDR.", MessageType.Warning); } } EditorGUILayout.PropertyField(type, new GUIContent("Technique")); if (type.enumValueIndex == (int) Tonemapping.TonemapperType.UserCurve) { EditorGUILayout.PropertyField(remapCurve, new GUIContent("Remap curve", "Specify the mapping of luminances yourself")); } else if (type.enumValueIndex == (int) Tonemapping.TonemapperType.SimpleReinhard) { EditorGUILayout.PropertyField(exposureAdjustment, new GUIContent("Exposure", "Exposure adjustment")); } else if (type.enumValueIndex == (int) Tonemapping.TonemapperType.Hable) { EditorGUILayout.PropertyField(exposureAdjustment, new GUIContent("Exposure", "Exposure adjustment")); } else if (type.enumValueIndex == (int) Tonemapping.TonemapperType.Photographic) { EditorGUILayout.PropertyField(exposureAdjustment, new GUIContent("Exposure", "Exposure adjustment")); } else if (type.enumValueIndex == (int) Tonemapping.TonemapperType.OptimizedHejiDawson) { EditorGUILayout.PropertyField(exposureAdjustment, new GUIContent("Exposure", "Exposure adjustment")); } else if (type.enumValueIndex == (int) Tonemapping.TonemapperType.AdaptiveReinhard) { EditorGUILayout.PropertyField(middleGrey, new GUIContent("Middle grey", "Middle grey defines the average luminance thus brightening or darkening the entire image.")); EditorGUILayout.PropertyField(white, new GUIContent("White", "Smallest luminance value that will be mapped to white")); EditorGUILayout.PropertyField(adaptionSpeed, new GUIContent("Adaption Speed", "Speed modifier for the automatic adaption")); EditorGUILayout.PropertyField(adaptiveTextureSize, new GUIContent("Texture size", "Defines the amount of downsamples needed.")); } else if (type.enumValueIndex == (int) Tonemapping.TonemapperType.AdaptiveReinhardAutoWhite) { EditorGUILayout.PropertyField(middleGrey, new GUIContent("Middle grey", "Middle grey defines the average luminance thus brightening or darkening the entire image.")); EditorGUILayout.PropertyField(adaptionSpeed, new GUIContent("Adaption Speed", "Speed modifier for the automatic adaption")); EditorGUILayout.PropertyField(adaptiveTextureSize, new GUIContent("Texture size", "Defines the amount of downsamples needed.")); } GUILayout.Label("All following effects will use LDR color buffers", EditorStyles.miniBoldLabel); serObj.ApplyModifiedProperties(); } } }
44.375
127
0.608853
[ "BSD-3-Clause" ]
dudemancart456/HedgePhysics
HedgePhysics/Assets/Editor/ImageEffects/TonemappingEditor.cs
4,970
C#
using VocaDb.Model.Domain.Songs; namespace VocaDb.Model.DataContracts.Songs { public class ArchivedSongVersionContract : ArchivedObjectVersionContract { public ArchivedSongVersionContract() { } public ArchivedSongVersionContract(ArchivedSongVersion archivedVersion) : base(archivedVersion) { ChangedFields = (archivedVersion.Diff != null ? archivedVersion.Diff.ChangedFields : SongEditableFields.Nothing); Reason = archivedVersion.Reason; } public SongEditableFields ChangedFields { get; set; } public SongArchiveReason Reason { get; set; } } }
24.041667
116
0.778163
[ "MIT" ]
cazzar/VocaDbTagger
VocaDbModel/DataContracts/Songs/ArchivedSongVersionContract.cs
579
C#
using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.AspNetCore.Http; using System.Net; using Tesseract; using System.IO; using ElasticsearchOCRServiceExample.Services; namespace ElasticsearchOCRServiceExample.Controllers { [ApiController] [Route("[controller]")] public class UploadController : ControllerBase { private ElasticsearchService _elasticsearchService { get; set; } private OCRService _ocrService { get; set; } public UploadController(ElasticsearchService elasticsearchService, OCRService ocrService) { _elasticsearchService = elasticsearchService; _ocrService = ocrService; } [HttpPost] public async Task<ActionResult> UploadDocument(List<IFormFile> files) { foreach (var file in files) { using MemoryStream ms = new MemoryStream(); await file.CopyToAsync(ms); byte[] imageData = ms.ToArray(); string fileTextContent = _ocrService.GetTextFromImage(imageData); await _elasticsearchService.IndexScannedDocument(file.FileName, fileTextContent); } return StatusCode((int)HttpStatusCode.OK); } } }
29.288889
97
0.663885
[ "MIT" ]
GalenHealthcare/Elasticsearch-OCR-Service-Example
ElasticsearchOCRServiceExample/Controllers/UploadController.cs
1,320
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AngleSharp.Dom; using AngleSharp.Html; using AngleSharp.Html.Dom; using AngleSharp.Html.Parser; using Statiq.Common; namespace Statiq.Html { /// <summary> /// Queries HTML content of the input documents and adds a metadata value that contains it's headings. /// </summary> /// <remarks> /// A new document is created for each heading, all of which are placed into a <c>IReadOnlyList&lt;IDocument&gt;</c> /// in the metadata of each input document. The new heading documents contain metadata with the level of the heading, /// the children of the heading (the following headings with one deeper level) and optionally the heading content, which /// is also set as the content of each document. The output of this module is the input documents with the additional /// metadata value containing the documents that present each heading. /// </remarks> /// <metadata cref="HtmlKeys.Headings" usage="Output"/> /// <metadata cref="HtmlKeys.Level" usage="Output"/> /// <metadata cref="HtmlKeys.HeadingId" usage="Output"/> /// <metadata cref="Keys.Children" usage="Output"> /// The child heading documents of the current heading document. /// </metadata> /// <category>Metadata</category> public class GatherHeadings : ParallelConfigModule<int> { private bool _nesting; private string _metadataKey = HtmlKeys.Headings; private string _levelKey = HtmlKeys.Level; private string _idKey = HtmlKeys.HeadingId; private string _childrenKey = Keys.Children; private string _headingKey; public GatherHeadings() : this(1) { } public GatherHeadings(Config<int> level) : base(level, true) { } /// <summary> /// Sets the key to use in the heading documents to store the level. /// </summary> /// <param name="levelKey">The key to use for the level.</param> /// <returns>The current module instance.</returns> public GatherHeadings WithLevelKey(string levelKey) { _levelKey = levelKey; return this; } /// <summary> /// Sets the key to use in the heading documents to store the heading /// <c>id</c> attribute (if it has one). /// </summary> /// <param name="idKey">The key to use for the <c>id</c>.</param> /// <returns>The current module instance.</returns> public GatherHeadings WithIdKey(string idKey) { _idKey = idKey; return this; } /// <summary> /// Sets the key to use in the heading documents to store the children /// of a given heading. In other words, the metadata for this key will /// contain all the headings following the one in the document with a /// level one deeper than the current heading. /// </summary> /// <param name="childrenKey">The key to use for children.</param> /// <returns>The current module instance.</returns> public GatherHeadings WithChildrenKey(string childrenKey) { _childrenKey = childrenKey; return this; } /// <summary> /// Sets the key to use for storing the heading content in the heading documents. /// The default is <c>null</c> which means only store the heading content in the /// content of the heading document. Setting this can be useful when you want /// to use the heading documents in downstream modules, setting their content /// to something else while maintaining the heading content in metadata. /// </summary> /// <param name="headingKey">The key to use for the heading content.</param> /// <returns>The current module instance.</returns> public GatherHeadings WithHeadingKey(string headingKey) { _headingKey = headingKey; return this; } /// <summary> /// Controls whether the heading documents are nested. If nesting is /// used, only the level 1 headings will be in the root set of documents. /// The rest of the heading documents will only be accessible via the /// metadata of the root heading documents. /// </summary> /// <param name="nesting"><c>true</c> to turn on nesting</param> /// <returns>The current module instance.</returns> public GatherHeadings WithNesting(bool nesting = true) { _nesting = true; return this; } /// <summary> /// Allows you to specify an alternate metadata key for the heading documents. /// </summary> /// <param name="metadataKey">The metadata key to store the heading documents in.</param> /// <returns>The current module instance.</returns> public GatherHeadings WithMetadataKey(string metadataKey) { _metadataKey = metadataKey; return this; } protected override async Task<IEnumerable<Common.IDocument>> ExecuteConfigAsync(Common.IDocument input, IExecutionContext context, int value) { // Return the original document if no metadata key if (string.IsNullOrWhiteSpace(_metadataKey)) { return input.Yield(); } // Parse the HTML content IHtmlDocument htmlDocument = await HtmlHelper.ParseHtmlAsync(input, false); if (htmlDocument is null) { return input.Yield(); } // Validate the level if (value < 1) { throw new ArgumentException("Heading level cannot be less than 1"); } if (value > 6) { throw new ArgumentException("Heading level cannot be greater than 6"); } // Evaluate the query and create the holding nodes Heading previousHeading = null; List<Heading> headings = htmlDocument .QuerySelectorAll(GetHeadingQuery(value)) .Select(x => { previousHeading = new Heading { Element = x, Previous = previousHeading, Level = int.Parse(x.NodeName.Substring(1)) }; return previousHeading; }) .ToList(); // Build the tree from the bottom-up for (int level = value; level >= 1; level--) { int currentLevel = level; foreach (Heading heading in headings.Where(x => x.Level == currentLevel)) { // Get the parent Heading parent = null; if (currentLevel > 1) { parent = heading.Previous; while (parent is object && parent.Level >= currentLevel) { parent = parent.Previous; } } // Create the document MetadataItems metadata = new MetadataItems(); if (_levelKey is object) { metadata.Add(_levelKey, heading.Level); } if (_idKey is object && heading.Element.HasAttribute("id")) { metadata.Add(_idKey, heading.Element.GetAttribute("id")); } if (_headingKey is object) { metadata.Add(_headingKey, heading.Element.TextContent); } if (_childrenKey is object) { metadata.Add(_childrenKey, heading.Children.AsReadOnly()); } heading.Document = context.CreateDocument(metadata, heading.Element.TextContent); // Add to parent parent?.Children.Add(heading.Document); } } return input .Clone(new MetadataItems { { _metadataKey, _nesting ? headings .Where(x => x.Level == headings.Min(y => y.Level)) .Select(x => x.Document) .ToArray() : headings .Select(x => x.Document) .ToArray() } }) .Yield(); } public static string GetHeadingQuery(int level) { StringBuilder query = new StringBuilder(); for (int l = 1; l <= level; l++) { if (l > 1) { query.Append(","); } query.Append("h"); query.Append(l); } return query.ToString(); } private class Heading { public IElement Element { get; set; } public Heading Previous { get; set; } public int Level { get; set; } public Common.IDocument Document { get; set; } public List<Common.IDocument> Children { get; } = new List<Common.IDocument>(); } } }
38.511811
149
0.527908
[ "MIT" ]
JoshClose/Statiq.Framework
src/extensions/Statiq.Html/GatherHeadings.cs
9,784
C#
/* * Copyright 2018 Sage Intacct, 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 * * 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. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using Intacct.SDK.Functions.AccountsReceivable; using Intacct.SDK.Functions; using Intacct.SDK.Tests.Xml; using Intacct.SDK.Xml; using Xunit; namespace Intacct.SDK.Tests.Functions.AccountsReceivable { public class InvoiceSummaryCreateTest : XmlObjectTestHelper { [Fact] public void GetXmlTest() { string expected = @"<?xml version=""1.0"" encoding=""utf-8""?> <function controlid=""unittest""> <create_invoicebatch> <batchtitle>unit test</batchtitle> <datecreated> <year>2015</year> <month>06</month> <day>30</day> </datecreated> </create_invoicebatch> </function>"; InvoiceSummaryCreate record = new InvoiceSummaryCreate("unittest") { Title = "unit test", GlPostingDate = new DateTime(2015, 06, 30) }; this.CompareXml(expected, record); } } }
29.4
80
0.653061
[ "Apache-2.0" ]
ILya-Lev/intacct-sdk-net
Intacct.SDK.Tests/Functions/AccountsReceivable/InvoiceSummaryCreateTest.cs
1,619
C#
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace Microsoft.Azure.Cosmos.ChangeFeed.FeedManagement { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Azure.Cosmos.ChangeFeed.LeaseManagement; using Microsoft.Azure.Documents; internal sealed class EqualPartitionsBalancingStrategy : LoadBalancingStrategy { internal static int DefaultMinLeaseCount = 0; internal static int DefaultMaxLeaseCount = 0; private readonly string hostName; private readonly int minPartitionCount; private readonly int maxPartitionCount; private readonly TimeSpan leaseExpirationInterval; public EqualPartitionsBalancingStrategy(string hostName, int minPartitionCount, int maxPartitionCount, TimeSpan leaseExpirationInterval) { if (hostName == null) throw new ArgumentNullException(nameof(hostName)); this.hostName = hostName; this.minPartitionCount = minPartitionCount; this.maxPartitionCount = maxPartitionCount; this.leaseExpirationInterval = leaseExpirationInterval; } public override IEnumerable<DocumentServiceLease> SelectLeasesToTake(IEnumerable<DocumentServiceLease> allLeases) { var workerToPartitionCount = new Dictionary<string, int>(); var expiredLeases = new List<DocumentServiceLease>(); var allPartitions = new Dictionary<string, DocumentServiceLease>(); this.CategorizeLeases(allLeases, allPartitions, expiredLeases, workerToPartitionCount); int partitionCount = allPartitions.Count; int workerCount = workerToPartitionCount.Count; if (partitionCount <= 0) return Enumerable.Empty<DocumentServiceLease>(); int target = this.CalculateTargetPartitionCount(partitionCount, workerCount); int myCount = workerToPartitionCount[this.hostName]; int partitionsNeededForMe = target - myCount; DefaultTrace.TraceInformation( "Host '{0}' {1} partitions, {2} hosts, {3} available leases, target = {4}, min = {5}, max = {6}, mine = {7}, will try to take {8} lease(s) for myself'.", this.hostName, partitionCount, workerCount, expiredLeases.Count, target, this.minPartitionCount, this.maxPartitionCount, myCount, Math.Max(partitionsNeededForMe, 0)); if (partitionsNeededForMe <= 0) return Enumerable.Empty<DocumentServiceLease>(); if (expiredLeases.Count > 0) { return expiredLeases.Take(partitionsNeededForMe); } DocumentServiceLease stolenLease = GetLeaseToSteal(workerToPartitionCount, target, partitionsNeededForMe, allPartitions); return stolenLease == null ? Enumerable.Empty<DocumentServiceLease>() : new[] { stolenLease }; } private static DocumentServiceLease GetLeaseToSteal( Dictionary<string, int> workerToPartitionCount, int target, int partitionsNeededForMe, Dictionary<string, DocumentServiceLease> allPartitions) { KeyValuePair<string, int> workerToStealFrom = FindWorkerWithMostPartitions(workerToPartitionCount); if (workerToStealFrom.Value > target - (partitionsNeededForMe > 1 ? 1 : 0)) { return allPartitions.Values.First(partition => string.Equals(partition.Owner, workerToStealFrom.Key, StringComparison.OrdinalIgnoreCase)); } return null; } private static KeyValuePair<string, int> FindWorkerWithMostPartitions(Dictionary<string, int> workerToPartitionCount) { KeyValuePair<string, int> workerToStealFrom = default(KeyValuePair<string, int>); foreach (KeyValuePair<string, int> kvp in workerToPartitionCount) { if (workerToStealFrom.Value <= kvp.Value) { workerToStealFrom = kvp; } } return workerToStealFrom; } private int CalculateTargetPartitionCount(int partitionCount, int workerCount) { var target = 1; if (partitionCount > workerCount) { target = (int)Math.Ceiling((double)partitionCount / workerCount); } if (this.maxPartitionCount > 0 && target > this.maxPartitionCount) { target = this.maxPartitionCount; } if (this.minPartitionCount > 0 && target < this.minPartitionCount) { target = this.minPartitionCount; } return target; } private void CategorizeLeases( IEnumerable<DocumentServiceLease> allLeases, Dictionary<string, DocumentServiceLease> allPartitions, List<DocumentServiceLease> expiredLeases, Dictionary<string, int> workerToPartitionCount) { foreach (DocumentServiceLease lease in allLeases) { Debug.Assert(lease.CurrentLeaseToken != null, "TakeLeasesAsync: lease.PartitionId cannot be null."); allPartitions.Add(lease.CurrentLeaseToken, lease); if (string.IsNullOrWhiteSpace(lease.Owner) || this.IsExpired(lease)) { DefaultTrace.TraceVerbose("Found unused or expired lease: {0}", lease); expiredLeases.Add(lease); } else { var count = 0; string assignedTo = lease.Owner; if (workerToPartitionCount.TryGetValue(assignedTo, out count)) { workerToPartitionCount[assignedTo] = count + 1; } else { workerToPartitionCount.Add(assignedTo, 1); } } } if (!workerToPartitionCount.ContainsKey(this.hostName)) { workerToPartitionCount.Add(this.hostName, 0); } } private bool IsExpired(DocumentServiceLease lease) { return lease.Timestamp.ToUniversalTime() + this.leaseExpirationInterval < DateTime.UtcNow; } } }
40.842424
169
0.58985
[ "MIT" ]
JohnLTaylor/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/ChangeFeedProcessor/FeedManagement/EqualPartitionsBalancingStrategy.cs
6,741
C#
public class Direction { }
8
23
0.625
[ "MIT" ]
harjup/ChillTreasureTime
src/ChillTeasureTime/Assets/src/scripts/Interaction/Direction.cs
34
C#
using System; using System.Collections.Generic; using Golconda.Models; using Golconda.Services.Contracts; using Microsoft.Xna.Framework; namespace Golconda.Services { /// <summary> /// Contains the list of projections used to project nested local coordinates onto the screen. /// </summary> public class Projector : IProjector { private readonly List<Projection> _projections = new List<Projection>(); public float ScaleToScreenFactor { get; set; } public float ScaleToLocalFactor { get; set; } private bool ContainsRotation { get; set; } /// <inheritdoc /> public Vector2 ProjectToScreen(Vector2 localCoordinates) { return ProjectToScreen(localCoordinates, 0, _projections.Count - 1); } /// <summary> /// Recursively projects local coordinates throughout all the coordinates systems until it reaches the screen system. /// </summary> /// <param name="coordinates">The coordinates.</param> /// <param name="index">The index of the projection.</param> /// <returns>The resulting coordinates.</returns> private Vector2 ProjectToScreen(Vector2 coordinates, int index, int lastIndex) { if (index > lastIndex) { return coordinates; } Projection currentProjection = _projections[index]; var result = currentProjection._coordinates + currentProjection._scale * ProjectToScreen(coordinates, index + 1, lastIndex); //if (currentProjection._rotation._angle != 0) //{ // result = Rotate(currentProjection._rotation._origin, currentProjection._rotation._angle, result); //} return result; } private Vector2 Rotate(Vector2 origin, double angle, Vector2 point) { double s = Math.Sin(angle); double c = Math.Cos(angle); // translate point back to origin: var po = point - origin; // rotate point var r = new Vector2((float)(po.X * c - po.Y * s), (float)(po.X * s + po.Y * c)); // translate point back: return r + origin; } /// <inheritdoc /> public Vector2 ProjectToLocal(Vector2 screenCoordinates) { return ProjectToLocal(screenCoordinates, 0, _projections.Count - 1); } /// <summary> /// Recursively projects screen coordinates throughout all the coordinates systems until it reaches the last local system. /// </summary> /// <param name="coordinates">The coordinates.</param> /// <param name="index">The index of the projection.</param> /// <returns>The resulting coordinates.</returns> private Vector2 ProjectToLocal(Vector2 coordinates, int index, int lastIndex) { if (index > lastIndex) { return coordinates; } Projection currentProjection = _projections[index]; var result = ProjectToLocal((coordinates - currentProjection._coordinates) / _projections[index]._scale, index + 1, lastIndex); //if (currentProjection._rotation._angle != 0) //{ // result = Rotate(currentProjection._rotation._origin, -currentProjection._rotation._angle, result); //} return result; } /// <inheritdoc /> public Rotation2 GetScreenRotation() { return !ContainsRotation ? Rotation2.Zero : _projections[_projections.Count - 1]._rotation; // the rotation is relative to the screen position of the sprite (which is already transformed), so we don't need to transform any coordinates! } /// <inheritdoc /> public Vector2 ScaleToScreen(Vector2 localSize) { return localSize * ScaleToScreenFactor; } /// <inheritdoc /> public float ScaleToScreen(float localSize) { return localSize * ScaleToScreenFactor; } /// <inheritdoc /> public Vector2 ScaleToLocal(Vector2 screenSize) { return screenSize / ScaleToScreenFactor; } /// <inheritdoc /> public float ScaleToLocal(float screenSize) { return screenSize / ScaleToScreenFactor; } /// <inheritdoc /> public void Push(Projection projection) { if (ContainsRotation) { throw new Exception("Cannot add projections after a rotation. Rotation must be final."); } if (projection._rotation._angle != 0) { ContainsRotation = true; } _projections.Add(projection); UpdateScales(); } /// <inheritdoc /> public void Pop() { ContainsRotation = false; // since a rotation (if any) is possible only on the last projection, it is necessarily removed as soon as we remove a projection _projections.RemoveAt(_projections.Count - 1); UpdateScales(); } private void UpdateScales() { ScaleToScreenFactor = 1f; ScaleToLocalFactor = 1f; foreach (var projection in _projections) { ScaleToScreenFactor *= projection._scale; ScaleToLocalFactor /= projection._scale; } } } }
35.128834
210
0.564792
[ "MIT" ]
lionel-panhaleux/yawp-court
Monogame/Golconda/Services/Projector.cs
5,728
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Media.V20190501Preview.Inputs { /// <summary> /// The HLS configuration. /// </summary> public sealed class HlsArgs : Pulumi.ResourceArgs { /// <summary> /// The amount of fragments per HTTP Live Streaming (HLS) segment. /// </summary> [Input("fragmentsPerTsSegment")] public Input<int>? FragmentsPerTsSegment { get; set; } public HlsArgs() { } } }
26.448276
81
0.647979
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Media/V20190501Preview/Inputs/HlsArgs.cs
767
C#
// Copyright 2018 Niklas K. // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Joveler.ZLibWrapper; using System.Security.Cryptography; namespace Craf { // I HAVE ONLY TESTED THIS WITH ONE ARCHIVE (datas/shaders/shadergen/autoexternal.earc) // Feel free to use as reference but keep in mind that it may not work out of the box. // The game's reader appears to be sensitive to alignment. I'm not sure *all* alignment // in this code is exactly what the original archiver does, but this does seem // to produce equivalent alignment for the archive mentioned above. // Signedness is down to what happened to be convenient. I don't know whether // the game uses signed or unsigned arithmetic for any of these fields. // Except for encryption, where it actually matters. // I do not know whether the game requires files of a certain size to be compressed or uncompressed. // This may or may not work with archives taken from the console version. // I do not have access to those files and have not looked into it. // The API is somewhat specific to what I'm actually using this for. // THIS NEEDS THE ENTIRE ARCHIVE LOADED INTO MEMORY to access or replace content. // So you probably don't want to use this code unmodified. // USAGE // var craf = Craf.Open("path/to/autoexternal.earc"); // now available: // craf.Count(); // craf.IndexOf("data://foo/bar.bin"); // => 12 // craf.VfsPath(12); // => "data://foo/bar.bin" // craf.VfsFilename(12); // => "bar.bin" // await craf.LoadAsync(progress); // 'progress' gets updated with file ID after each file is read // now available: // craf.Get(12); // => byte[] { ... } // craf.CloseReader(); // now available: // craf.Replace(12, new byte[] { ...}); // craf.Append("who/cares.bin", "data://baz/quux.bin", false, new byte[] { ... }); // You can overwrite the original file here, it's no longer locked since CloseReader() // await craf.SaveAsync("path/to/new/autoexternal.earc", progress); // progress gets updated with file ID after each file's body is written // struct HEADER { // /* 00 */ char magic[4]; // 'C','R','A','F' // /* 04 */ ushort minorVersion; // /* 06 */ char majorVersion; // /* 07 */ char encrypted; // 0x80 = yes // /* 08 */ int fileCount; // /* 0C */ uint unk0; // /* 10 */ uint firstEntryOffset; // /* 14 */ uint firstVfsPathOffset; // /* 18 */ uint firstPathOffset; // /* 1C */ uint firstDataOffset; // yeah, they're assuming this is always within the first 32 bit // /* 20 */ uint flags; // /* 24 */ char unk1[4]; // /* 28 */ int64 archiveKey; // /* 30 */ char unk2[16]; // } // sizeof(HEADER) = 0x40 // struct FILEENTRY { // /* 00 */ int64 fileKey; // /* 08 */ int uncompressedSize; // no padding! // /* 0C */ int totalCompressedSize; // including chunk headers / size of ENCRYPTEDFILE // /* 10 */ uint flags; // 2 = compressed // /* 14 */ uint vfsPathOffset; // /* 18 */ int64 dataOffset; // /* 20 */ uint pathOffset; // /* 24 */ ushort unk0; // /* 26 */ ushort chunkKey; // } // sizeof(FILEENTRY) = 0x28 // struct ENCRYPTEDFILE { // char data[]; // padded to 16 bytes with zeroes // char iv[16]; // char unk[17]; // 16 0's followed by 1 // } // The encryption code in the game is slightly more complicated than here. // The examples I've looked at have only used this parameter subset so that's // all that I reversed. // // These are the functions responsible for decrypting metadata in the game // VAs in Steam original retail release build and search signatures: // 140BCF1E0 - 48 8B C4 4C 89 48 20 4C 89 40 18 48 89 48 08 55 56 57 41 54 41 55 41 56 41 57 48 8D 68 B9 48 // 1488F4C80 - 48 89 5C 24 10 48 89 6C 24 18 48 89 74 24 20 57 41 54 41 55 41 56 41 57 48 83 EC 30 48 8D 41 68 // 142C77080 - 40 55 53 56 57 41 54 41 55 41 56 41 57 48 8D 6C 24 E1 48 ?? ?? ?? ?? ?? ?? 48 ?? ?? ?? ?? ?? ?? ?? 4C 8B F1 80 79 08 00 internal static class Extensions { public static string ReadNullTerminatedString(this BinaryReader reader) { var sb = new StringBuilder(); char lastRead; while ((int)(lastRead = reader.ReadChar()) != 0) { sb.Append(lastRead); } return sb.ToString(); } public static void WriteNullTerminatedString(this BinaryWriter writer, string str) { byte[] bstr = Encoding.ASCII.GetBytes(str); writer.Write(bstr); writer.Write('\0'); } } internal class ReuseCryptoStream : CryptoStream { public ReuseCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) : base(stream, transform, mode) { } protected override void Dispose(bool disposing) { if (!HasFlushedFinalBlock) FlushFinalBlock(); base.Dispose(false); } } public class CrafArchive { private class CrafEntry { public ushort unk0; public int uncompressedSize; public int totalCompressedSize; public uint flags; public bool UseCompression { get { return (flags & 2) != 0; } } public bool UseDataEncryption { get { return (flags & 0x40) != 0; } } public string path; public string vfsPath; public CrafChunk[] chunks; // if compressed public byte[] data; // if uncompressed public byte[] IV; // if encrypted public Int64 entryKey; public ushort chunkKey; // Only used before load and for writing public Int64 dataOffset; // Only used for writing public uint vfsPathOffset; public uint pathOffset; } private class CrafChunk { public int uncompressedSize; public byte[] compressedData; } public const int ChunkSize = 0x20000; public const Int64 MasterArchiveKey1 = unchecked((Int64)0xCBF29CE484222325); public const Int64 MasterArchiveKey2 = unchecked((Int64)0x40D4CCA269811DAF); public const Int64 MasterEntryKey = unchecked((Int64)0x100000001B3); public const Int64 MasterChunkKey1 = unchecked((Int64)0x10E64D70C2A29A69); public const Int64 MasterChunkKey2 = unchecked((Int64)0xC63D3dC167E); public readonly byte[] AESKey = new byte[] { 0x9C, 0x6C, 0x5D, 0x41, 0x15, 0x52, 0x3F, 0x17, 0x5A, 0xD3, 0xF8, 0xB7, 0x75, 0x58, 0x1E, 0xCF }; private byte _versionMajor; private ushort _versionMinor; private byte _metadataEncryption; // probably not the actual indicator private uint _flags; private uint _unk0; private byte[] _unk1; private byte[] _unk2; private Int64 _archiveKey; private List<CrafEntry> _files; private FileStream _inputStream; private bool _loaded; private Aes _aes; private CrafArchive() { } ~CrafArchive() { if (_inputStream != null) _inputStream.Close(); } public bool MetadataEncrypted { get { return _metadataEncryption == 0x80; } } public Int64 MasterArchiveKey { get { if ((_flags & 8) != 0) { return MasterArchiveKey2; } else { return MasterArchiveKey1; } } } public static CrafArchive Open(string Path) { var result = new CrafArchive(); result._loaded = false; result._inputStream = File.OpenRead(Path); result._aes = Aes.Create(); result._aes.Mode = CipherMode.CBC; result._aes.Padding = PaddingMode.Zeros; result.ReadMetadata(); return result; } private void ReadMetadata() { if (_inputStream is null) throw new Exception("Tried to read CRAF metadata after reader was closed"); using (BinaryReader bin = new BinaryReader(_inputStream, Encoding.Default, true)) { _inputStream.Seek(4, SeekOrigin.Begin); _versionMinor = bin.ReadUInt16(); _versionMajor = bin.ReadByte(); _metadataEncryption = bin.ReadByte(); var fileCount = bin.ReadInt32(); _files = new List<CrafEntry>(fileCount); _unk0 = bin.ReadUInt32(); uint firstEntryOffset = bin.ReadUInt32(); _inputStream.Seek(0x20, SeekOrigin.Begin); _flags = bin.ReadUInt32(); _unk1 = bin.ReadBytes(4); _archiveKey = bin.ReadInt64(); _unk2 = bin.ReadBytes(16); Int64 rollingKey = MasterArchiveKey ^ _archiveKey; _inputStream.Seek(firstEntryOffset, SeekOrigin.Begin); for (var i = 0; i < fileCount; i++) { var entry = new CrafEntry(); entry.entryKey = bin.ReadInt64(); entry.uncompressedSize = bin.ReadInt32(); entry.totalCompressedSize = bin.ReadInt32(); entry.flags = bin.ReadUInt32(); uint vfsPathOffset = bin.ReadUInt32(); entry.dataOffset = bin.ReadInt64(); uint pathOffset = bin.ReadUInt32(); entry.unk0 = bin.ReadUInt16(); entry.chunkKey = bin.ReadUInt16(); long entryEnd = _inputStream.Position; _inputStream.Seek(vfsPathOffset, SeekOrigin.Begin); entry.vfsPath = bin.ReadNullTerminatedString(); _inputStream.Seek(pathOffset, SeekOrigin.Begin); entry.path = bin.ReadNullTerminatedString(); _inputStream.Seek(entryEnd, SeekOrigin.Begin); _files.Add(entry); if (MetadataEncrypted) { Int64 fileSizeKey = (rollingKey * MasterEntryKey) ^ entry.entryKey; int uncompressedSizeKey = (int)(fileSizeKey >> 32); int compressedSizeKey = (int)(fileSizeKey & 0xFFFFFFFF); entry.uncompressedSize ^= uncompressedSizeKey; entry.totalCompressedSize ^= compressedSizeKey; Int64 dataOffsetKey = (fileSizeKey * MasterEntryKey) ^ ~(entry.entryKey); entry.dataOffset ^= dataOffsetKey; rollingKey = dataOffsetKey; } if (entry.UseDataEncryption) { var pos = _inputStream.Position; _inputStream.Seek(entry.dataOffset + entry.totalCompressedSize - 0x21, SeekOrigin.Begin); entry.IV = bin.ReadBytes(16); _inputStream.Seek(pos, SeekOrigin.Begin); } } } } public void CloseReader() { if (_inputStream is null) return; _inputStream.Close(); _inputStream = null; } private int ChunkCount(int uncompressedSize) { var result = uncompressedSize / ChunkSize; if (uncompressedSize % ChunkSize != 0) result++; return (int)result; } private int AlignTo(int offset, int align) { if (offset % align == 0) return offset; return ((offset / align) + 1) * align; } private uint AlignTo(uint offset, int align) { if (offset % align == 0) return offset; return (uint)(((offset / align) + 1) * align); } private long AlignTo(long offset, int align) { if (offset % align == 0) return offset; return ((offset / align) + 1) * align; } private void LoadEntry(int id) { if (id < 0 || id > _files.Count - 1) throw new Exception("Tried to read CRAF entry out of bounds"); if (_inputStream is null) throw new Exception("Tried to load CRAF entry after reader was closed"); using (BinaryReader bin = new BinaryReader(_inputStream, Encoding.Default, true)) { _inputStream.Seek(_files[id].dataOffset, SeekOrigin.Begin); if (_files[id].UseCompression) { var chunkCount = ChunkCount(_files[id].uncompressedSize); _files[id].chunks = new CrafChunk[chunkCount]; for (var j = 0; j < chunkCount; j++) { _files[id].chunks[j] = new CrafChunk(); var compressedSize = bin.ReadInt32(); _files[id].chunks[j].uncompressedSize = bin.ReadInt32(); if (MetadataEncrypted && j == 0) { Int64 chunkKey = (MasterChunkKey1 * _files[id].chunkKey) + MasterChunkKey2; int compressedSizeKey = (int)(chunkKey >> 32); int uncompressedSizeKey = (int)(chunkKey & 0xFFFFFFFF); compressedSize ^= compressedSizeKey; _files[id].chunks[j].uncompressedSize ^= uncompressedSizeKey; } _files[id].chunks[j].compressedData = bin.ReadBytes(compressedSize); } } else if (_files[id].UseDataEncryption) { var decryptor = _aes.CreateDecryptor(AESKey, _files[id].IV); using (var decryptorStream = new ReuseCryptoStream(_inputStream, decryptor, CryptoStreamMode.Read)) { _files[id].data = new byte[_files[id].uncompressedSize]; decryptorStream.Read(_files[id].data, 0, _files[id].uncompressedSize); } } else { _files[id].data = bin.ReadBytes(_files[id].uncompressedSize); } } } public int Count() { return _files.Count; } public Task LoadAsync(IProgress<int> progress) { if (_loaded) return Task.FromResult(0); if (_inputStream is null) throw new Exception("Tried to load CRAF data after reader was closed"); return Task.Run(() => { for (var i = 0; i < Count(); i++) { LoadEntry(i); progress.Report(i + 1); } _loaded = true; }); } public void Append(string path, string vfsPath, bool compress, byte[] content) { if (_inputStream != null) throw new Exception("Tried to add CRAF entry while still in read mode"); if (IndexOf(vfsPath) != -1) throw new Exception("Tried to add file to CRAF with same path as existing file"); var entry = new CrafEntry(); entry.path = path; entry.vfsPath = vfsPath; entry.flags = compress ? (uint)2 : 0; _files.Add(entry); Replace(_files.Count - 1, content); } public int IndexOf(string vfsPath) { return _files.FindIndex((entry) => { return entry.vfsPath == vfsPath; }); } public int IndexOfDiskPath(string path) { return _files.FindIndex((entry) => { return entry.path == path; }); } public void Replace(int id, byte[] content) { if (id < 0 || id > _files.Count - 1) throw new Exception("Tried to modify CRAF entry out of bounds"); if (_inputStream != null) throw new Exception("Tried to modify CRAF entry while still in read mode"); var uncompressedSize = content.Length; _files[id].uncompressedSize = uncompressedSize; if (_files[id].UseCompression) { var chunkCount = ChunkCount(content.Length); _files[id].chunks = new CrafChunk[chunkCount]; _files[id].totalCompressedSize = 8 * chunkCount; var pos = 0; var remaining = uncompressedSize; for (var j = 0; j < chunkCount; j++) { _files[id].chunks[j] = new CrafChunk(); var chunkUncompressedSize = Math.Min(ChunkSize, remaining); _files[id].chunks[j].uncompressedSize = chunkUncompressedSize; using (MemoryStream compressedStream = new MemoryStream()) { using (ZLibStream compressor = new ZLibStream(compressedStream, CompressionMode.Compress, CompressionLevel.Best, true)) { compressor.Write(content, pos, chunkUncompressedSize); } var chunkCompressedData = compressedStream.ToArray(); _files[id].totalCompressedSize += chunkCompressedData.Length; _files[id].chunks[j].compressedData = chunkCompressedData; } pos += chunkUncompressedSize; remaining -= chunkUncompressedSize; } _files[id].totalCompressedSize = AlignTo(_files[id].totalCompressedSize, 4); } else { if (_files[id].UseDataEncryption) { // align to AES blocks + IV + static 17 byte padding _files[id].totalCompressedSize = AlignTo(_files[id].uncompressedSize, 0x10) + 0x11; } else { _files[id].totalCompressedSize = uncompressedSize; } _files[id].data = content; } } public string VfsPath(int id) { if (id < 0 || id > _files.Count - 1) throw new Exception("Tried to read CRAF entry out of bounds"); return _files[id].vfsPath; } public string VfsFilename(int id) { if (id < 0 || id > _files.Count - 1) throw new Exception("Tried to read CRAF entry out of bounds"); var vfsPath = VfsPath(id); return vfsPath.Substring(vfsPath.LastIndexOfAny("/\\".ToCharArray()) + 1); } public string DiskPath(int id) { if (id < 0 || id > _files.Count - 1) throw new Exception("Tried to read CRAF entry out of bounds"); return _files[id].path; } public byte[] Get(int id) { if (id < 0 || id > _files.Count - 1) throw new Exception("Tried to read CRAF entry out of bounds"); if (!_loaded) throw new Exception("Tried to read CRAF entry before loading data"); if (_files[id].UseCompression) { byte[] result = new byte[_files[id].uncompressedSize]; var pos = 0; for (var j = 0; j < _files[id].chunks.Length; j++) { var chunkUncompressedSize = _files[id].chunks[j].uncompressedSize; using (MemoryStream compressedDataStream = new MemoryStream(_files[id].chunks[j].compressedData)) { using (ZLibStream decompressor = new ZLibStream(compressedDataStream, CompressionMode.Decompress)) { decompressor.Read(result, pos, chunkUncompressedSize); } } pos += chunkUncompressedSize; } return result; } else { return _files[id].data; } } public Task SaveAsync(string Path, IProgress<int> progress) { if (!_loaded) throw new Exception("Tried to save CRAF before loading data"); if (_inputStream != null) throw new Exception("Tried to save CRAF while still in read mode"); return Task.Run(() => { // Create mode is slow if (File.Exists(Path)) File.Delete(Path); using (FileStream file = File.OpenWrite(Path)) { using (BinaryWriter bin = new BinaryWriter(file)) { var magic = new char[] { 'C', 'R', 'A', 'F' }; bin.Write(magic); bin.Write(_versionMinor); bin.Write(_versionMajor); bin.Write(_metadataEncryption); bin.Write(_files.Count); bin.Write(_unk0); file.Seek(0x20, SeekOrigin.Begin); bin.Write(_flags); bin.Write(_unk1); bin.Write(_archiveKey); bin.Write(_unk2); uint firstEntryOffset = (uint)file.Position; file.Seek(firstEntryOffset + 0x28 * _files.Count, SeekOrigin.Begin); file.Seek(AlignTo(file.Position, 16), SeekOrigin.Begin); // don't ask me why, but it's normally padded like that file.Seek(8, SeekOrigin.Current); for (var i = 0; i < _files.Count; i++) { var vfsPathOffset = AlignTo(file.Position, 8); file.Seek(vfsPathOffset, SeekOrigin.Begin); bin.WriteNullTerminatedString(_files[i].vfsPath); _files[i].vfsPathOffset = (uint)vfsPathOffset; } // don't ask me why, but it's normally padded like that file.Seek(AlignTo(file.Position, 16), SeekOrigin.Begin); file.Seek(8, SeekOrigin.Current); for (var i = 0; i < _files.Count; i++) { var pathOffset = AlignTo(file.Position, 8); file.Seek(pathOffset, SeekOrigin.Begin); bin.WriteNullTerminatedString(_files[i].path); _files[i].pathOffset = (uint)pathOffset; } for (var i = 0; i < _files.Count; i++) { var dataOffset = AlignTo(file.Position, 0x200); file.Seek(dataOffset, SeekOrigin.Begin); if (_files[i].UseCompression) { for (var j = 0; j < _files[i].chunks.Length; j++) { var compressedSize = _files[i].chunks[j].compressedData.Length; var uncompressedSize = _files[i].chunks[j].uncompressedSize; if (MetadataEncrypted && j == 0) { Int64 chunkKey = (MasterChunkKey1 * _files[i].chunkKey) + MasterChunkKey2; int compressedSizeKey = (int)(chunkKey >> 32); int uncompressedSizeKey = (int)(chunkKey & 0xFFFFFFFF); compressedSize ^= compressedSizeKey; uncompressedSize ^= uncompressedSizeKey; } bin.Write(compressedSize); bin.Write(uncompressedSize); bin.Write(_files[i].chunks[j].compressedData); } file.Seek(dataOffset + _files[i].totalCompressedSize, SeekOrigin.Begin); // compressed files are padded; } else if (_files[i].UseDataEncryption) { var encryptor = _aes.CreateEncryptor(AESKey, _files[i].IV); using (var encryptorStream = new ReuseCryptoStream(file, encryptor, CryptoStreamMode.Write)) { encryptorStream.Write(_files[i].data, 0, _files[i].data.Length); } bin.Write(_files[i].IV); for (var j = 0; j < 16; j++) bin.Write((byte)0x00); bin.Write((byte)0x01); } else { bin.Write(_files[i].data); } _files[i].dataOffset = (uint)dataOffset; // files should not directly follow one another file.Seek(1, SeekOrigin.Current); progress.Report(i + 1); } // original files are padded at the end if (AlignTo(file.Position, 0x200) != file.Position) { file.Seek(AlignTo(file.Position, 0x200) - 1, SeekOrigin.Begin); // force filesize increase file.WriteByte(0); } file.Seek(0x10, SeekOrigin.Begin); bin.Write(firstEntryOffset); bin.Write(_files[0].vfsPathOffset); bin.Write(_files[0].pathOffset); bin.Write((int)(_files[0].dataOffset)); file.Seek(firstEntryOffset, SeekOrigin.Begin); Int64 rollingKey = MasterArchiveKey ^ _archiveKey; for (var i = 0; i < _files.Count; i++) { var uncompressedSize = _files[i].uncompressedSize; var totalCompressedSize = _files[i].totalCompressedSize; var dataOffset = _files[i].dataOffset; var entryKey = _files[i].entryKey; if (MetadataEncrypted) { Int64 fileSizeKey = (rollingKey * MasterEntryKey) ^ entryKey; int uncompressedSizeKey = (int)(fileSizeKey >> 32); int compressedSizeKey = (int)(fileSizeKey & 0xFFFFFFFF); uncompressedSize ^= uncompressedSizeKey; totalCompressedSize ^= compressedSizeKey; Int64 dataOffsetKey = (fileSizeKey * MasterEntryKey) ^ ~(entryKey); dataOffset ^= dataOffsetKey; rollingKey = dataOffsetKey; } bin.Write(entryKey); bin.Write(uncompressedSize); bin.Write(totalCompressedSize); bin.Write(_files[i].flags); bin.Write(_files[i].vfsPathOffset); bin.Write(dataOffset); bin.Write(_files[i].pathOffset); bin.Write(_files[i].unk0); bin.Write(_files[i].chunkKey); } } } }); } } }
42.71
150
0.497006
[ "MIT" ]
drdaxxy/ffxvDitherPatch
Craf/CrafArchive.cs
29,899
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Prism.Mvvm; #if HAS_UWP using Windows.UI.Xaml; #elif HAS_WINUI using Microsoft.UI.Xaml; #else using System.Windows; #endif namespace Prism.Common { /// <summary> /// Helper class for MVVM. /// </summary> public static class MvvmHelpers { #if HAS_WINUI && !HAS_UNO_WINUI /// <summary> /// Sets the AutoWireViewModel property to true for the <paramref name="viewOrViewModel"/>. /// </summary> /// <remarks> /// The AutoWireViewModel property will only be set to true if the view /// is a <see cref="FrameworkElement"/>, the DataContext of the view is null, and /// the AutoWireViewModel property of the view is null. /// </remarks> /// <param name="viewOrViewModel">The View or ViewModel.</param> [EditorBrowsable(EditorBrowsableState.Never)] public static void AutowireViewModel(object viewOrViewModel) { if (viewOrViewModel is FrameworkElement view && view.DataContext is null && ViewModelLocator.GetAutoWireViewModel(view) is null) { ViewModelLocator.SetAutoWireViewModel(view, true); } } #elif HAS_UWP || HAS_WINUI /// <summary> /// Sets the AutoWireViewModel property to true for the <paramref name="viewOrViewModel"/>. /// </summary> /// <remarks> /// The AutoWireViewModel property will only be set to true if the view /// is a <see cref="FrameworkElement"/>, the DataContext of the view is null, and /// the AutoWireViewModel property of the view is null. /// </remarks> /// <param name="viewOrViewModel">The View or ViewModel.</param> [EditorBrowsable(EditorBrowsableState.Never)] public static void AutowireViewModel(object viewOrViewModel) { if (viewOrViewModel is FrameworkElement view && view.DataContext is null && ViewModelLocator.GetAutowireViewModel(view) is null) { ViewModelLocator.SetAutowireViewModel(view, true); } } #else /// <summary> /// Sets the AutoWireViewModel property to true for the <paramref name="viewOrViewModel"/>. /// </summary> /// <remarks> /// The AutoWireViewModel property will only be set to true if the view /// is a <see cref="FrameworkElement"/>, the DataContext of the view is null, and /// the AutoWireViewModel property of the view is null. /// </remarks> /// <param name="viewOrViewModel">The View or ViewModel.</param> [EditorBrowsable(EditorBrowsableState.Never)] public static void AutowireViewModel(object viewOrViewModel) { if (viewOrViewModel is FrameworkElement view && view.DataContext is null && ViewModelLocator.GetAutoWireViewModel(view) is null) { ViewModelLocator.SetAutoWireViewModel(view, true); } } #endif /// <summary> /// Perform an <see cref="Action{T}"/> on a view and viewmodel. /// </summary> /// <remarks> /// The action will be performed on the view and its viewmodel if they implement <typeparamref name="T"/>. /// </remarks> /// <typeparam name="T">The <see cref="Action{T}"/> parameter type.</typeparam> /// <param name="view">The view to perform the <see cref="Action{T}"/> on.</param> /// <param name="action">The <see cref="Action{T}"/> to perform.</param> public static void ViewAndViewModelAction<T>(object view, Action<T> action) where T : class { if (view is T viewAsT) action(viewAsT); if (view is FrameworkElement element && element.DataContext is T viewModelAsT) { action(viewModelAsT); } } /// <summary> /// Get an implementer from a view or viewmodel. /// </summary> /// <remarks> /// If the view implements <typeparamref name="T"/> it will be returned. /// Otherwise if the view's <see cref="FrameworkElement.DataContext"/> implements <typeparamref name="T"/> it will be returned instead. /// </remarks> /// <typeparam name="T">The implementer type to get.</typeparam> /// <param name="view">The view to get <typeparamref name="T"/> from.</param> /// <returns>view or viewmodel as <typeparamref name="T"/>.</returns> public static T GetImplementerFromViewOrViewModel<T>(object view) where T : class { if (view is T viewAsT) { return viewAsT; } if (view is FrameworkElement element && element.DataContext is T vmAsT) { return vmAsT; } return null; } } }
40.146341
143
0.603483
[ "MIT" ]
bennoremec/PrismWinUi
src/Wpf/Prism.Wpf/Common/MvvmHelpers.cs
4,940
C#
namespace Ultraviolet.Presentation.Animations { partial class StoryboardInstance { /// <summary> /// Represents a dependency property which has been enlisted into the storyboard. /// </summary> private struct Enlistment { /// <summary> /// Initializes a new instance of the <see cref="Enlistment"/> structure. /// </summary> /// <param name="dpValue">The dependency property which has been enlisted.</param> /// <param name="animation">The animation to apply to the dependency property.</param> public Enlistment(IDependencyPropertyValue dpValue, AnimationBase animation) { this.dpValue = dpValue; this.animation = animation; } /// <summary> /// Gets the dependency property which has been enlisted. /// </summary> public IDependencyPropertyValue DependencyPropertyValue { get { return dpValue; } } /// <summary> /// Gets the animation to apply to the dependency property. /// </summary> public AnimationBase Animation { get { return animation; } } // Property values. private readonly IDependencyPropertyValue dpValue; private readonly AnimationBase animation; } } }
34.232558
98
0.550272
[ "Apache-2.0", "MIT" ]
MicroWorldwide/ultraviolet
Source/Ultraviolet.Presentation/Shared/Animations/StoryboardInstance.Enlistment.cs
1,474
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace messanger.Server.Data.Migrations { public partial class modified_file_relations_to_non_mandatory : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "User_AvatarFile", table: "AspNetUsers"); migrationBuilder.DropForeignKey( name: "Conversation_AvatarFile", table: "Conversation"); migrationBuilder.DropIndex( name: "IX_Conversation_IdAvatar", table: "Conversation"); migrationBuilder.DropIndex( name: "IX_AspNetUsers_IdAvatar", table: "AspNetUsers"); migrationBuilder.AlterColumn<int>( name: "IdAvatar", table: "Conversation", type: "int", nullable: true, oldClrType: typeof(int), oldType: "int"); migrationBuilder.AlterColumn<int>( name: "IdAvatar", table: "AspNetUsers", type: "int", nullable: true, oldClrType: typeof(int), oldType: "int"); migrationBuilder.CreateIndex( name: "IX_Conversation_IdAvatar", table: "Conversation", column: "IdAvatar", unique: true, filter: "[IdAvatar] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_IdAvatar", table: "AspNetUsers", column: "IdAvatar", unique: true, filter: "[IdAvatar] IS NOT NULL"); migrationBuilder.AddForeignKey( name: "User_AvatarFile", table: "AspNetUsers", column: "IdAvatar", principalTable: "File", principalColumn: "IdFile", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "Conversation_AvatarFile", table: "Conversation", column: "IdAvatar", principalTable: "File", principalColumn: "IdFile", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "User_AvatarFile", table: "AspNetUsers"); migrationBuilder.DropForeignKey( name: "Conversation_AvatarFile", table: "Conversation"); migrationBuilder.DropIndex( name: "IX_Conversation_IdAvatar", table: "Conversation"); migrationBuilder.DropIndex( name: "IX_AspNetUsers_IdAvatar", table: "AspNetUsers"); migrationBuilder.AlterColumn<int>( name: "IdAvatar", table: "Conversation", type: "int", nullable: false, defaultValue: 0, oldClrType: typeof(int), oldType: "int", oldNullable: true); migrationBuilder.AlterColumn<int>( name: "IdAvatar", table: "AspNetUsers", type: "int", nullable: false, defaultValue: 0, oldClrType: typeof(int), oldType: "int", oldNullable: true); migrationBuilder.CreateIndex( name: "IX_Conversation_IdAvatar", table: "Conversation", column: "IdAvatar", unique: true); migrationBuilder.CreateIndex( name: "IX_AspNetUsers_IdAvatar", table: "AspNetUsers", column: "IdAvatar", unique: true); migrationBuilder.AddForeignKey( name: "User_AvatarFile", table: "AspNetUsers", column: "IdAvatar", principalTable: "File", principalColumn: "IdFile", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "Conversation_AvatarFile", table: "Conversation", column: "IdAvatar", principalTable: "File", principalColumn: "IdFile", onDelete: ReferentialAction.Cascade); } } }
33.357143
77
0.501071
[ "Apache-2.0" ]
xlegodroit/blazor-messanger
Server/Data/Migrations/20210811184208_modified_file_relations_to_non_mandatory.cs
4,672
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using TygaSoft.Model; namespace TygaSoft.IDAL { public partial interface IFeatureUser { #region IFeatureUser Member FeatureUserInfo GetModel(Guid userId, string typeName); #endregion } }
18.05
63
0.725762
[ "MIT" ]
64075898/Asset
src/TygaSoft/IDAL/IFeatureUser.cs
363
C#
using System; using System.Collections.Generic; namespace Jannesen.Language.TypedTSql.Node { //https://msdn.microsoft.com/en-us/library/ms187373.aspx // Data_TableHints ::= // WITH ( tablehint [ [, ]...n ] ) public class Node_TableHints: Core.AstParseNode { [Flags] public enum Hint { FORCESCAN = 0x00000001, HOLDLOCK = 0x00000004, IGNORE_CONSTRAINTS = 0x00000008, IGNORE_TRIGGERS = 0x00000010, KEEPDEFAULTS = 0x00000020, KEEPIDENTITY = 0x00000040, NOEXPAND = 0x00000080, NOLOCK = 0x00000100, NOWAIT = 0x00000200, PAGLOCK = 0x00000400, READCOMMITTED = 0x00000800, READCOMMITTEDLOCK = 0x00001000, READPAST = 0x00002000, READUNCOMMITTED = 0x00004000, REPEATABLEREAD = 0x00008000, ROWLOCK = 0x00010000, SERIALIZABLE = 0x00020000, SNAPSHOT = 0x00040000, TABLOCK = 0x00080000, TABLOCKX = 0x00100000, UPDLOCK = 0x00200000, XLOCK = 0x00400000, _INDEX = 0x10000000 } public readonly Hint n_Hints; public readonly Core.TokenWithSymbol[] n_Indexes; public Node_TableHints(Core.ParserReader reader) { List<Core.TokenWithSymbol> indexes = null; ParseToken(reader, Core.TokenID.WITH); ParseToken(reader, Core.TokenID.LrBracket); do { Hint hint = ParseEnum<Hint>(reader, _parseEnum); n_Hints |= hint; switch(hint) { case Hint._INDEX: if (indexes == null) indexes = new List<Core.TokenWithSymbol>(); ParseToken(reader, Core.TokenID.Equal); indexes.Add(ParseName(reader)); break; } } while (ParseOptionalToken(reader, Core.TokenID.Comma) != null); ParseToken(reader, Core.TokenID.RrBracket); n_Indexes = indexes?.ToArray(); } public override void TranspileNode(Transpile.Context context) { } public void CheckIndexes(Transpile.Context context, DataModel.ISymbol entity) { if (n_Indexes != null) { if (entity is DataModel.ITable entityTable) { foreach(var index in n_Indexes) { if (entityTable.Indexes != null && entityTable.Indexes.TryGetValue(index.ValueString, out var tableIndex)) index.SetSymbol(tableIndex); else context.AddError(index, "Unknown index in "+ entity.Name + "."); } } else context.AddError(this, "Not a table reference."); } } private static Core.ParseEnum<Hint> _parseEnum = new Core.ParseEnum<Hint>( "Table hint", new Core.ParseEnum<Hint>.Seq(Hint.FORCESCAN, "FORCESCAN"), new Core.ParseEnum<Hint>.Seq(Hint.HOLDLOCK, "HOLDLOCK"), new Core.ParseEnum<Hint>.Seq(Hint.IGNORE_CONSTRAINTS, "IGNORE_CONSTRAINTS"), new Core.ParseEnum<Hint>.Seq(Hint.IGNORE_TRIGGERS, "IGNORE_TRIGGERS"), new Core.ParseEnum<Hint>.Seq(Hint.KEEPDEFAULTS, "KEEPDEFAULTS"), new Core.ParseEnum<Hint>.Seq(Hint.KEEPIDENTITY, "KEEPIDENTITY"), new Core.ParseEnum<Hint>.Seq(Hint.NOEXPAND, "NOEXPAND"), new Core.ParseEnum<Hint>.Seq(Hint.NOLOCK, "NOLOCK"), new Core.ParseEnum<Hint>.Seq(Hint.NOWAIT, "NOWAIT"), new Core.ParseEnum<Hint>.Seq(Hint.PAGLOCK, "PAGLOCK"), new Core.ParseEnum<Hint>.Seq(Hint.READCOMMITTED, "READCOMMITTED"), new Core.ParseEnum<Hint>.Seq(Hint.READCOMMITTEDLOCK, "READCOMMITTEDLOCK"), new Core.ParseEnum<Hint>.Seq(Hint.READPAST, "READPAST"), new Core.ParseEnum<Hint>.Seq(Hint.READUNCOMMITTED, "READUNCOMMITTED"), new Core.ParseEnum<Hint>.Seq(Hint.REPEATABLEREAD, "REPEATABLEREAD"), new Core.ParseEnum<Hint>.Seq(Hint.ROWLOCK, "ROWLOCK"), new Core.ParseEnum<Hint>.Seq(Hint.SERIALIZABLE, "SERIALIZABLE"), new Core.ParseEnum<Hint>.Seq(Hint.SNAPSHOT, "SNAPSHOT"), new Core.ParseEnum<Hint>.Seq(Hint.TABLOCK, "TABLOCK"), new Core.ParseEnum<Hint>.Seq(Hint.TABLOCKX, "TABLOCKX"), new Core.ParseEnum<Hint>.Seq(Hint.UPDLOCK, "UPDLOCK"), new Core.ParseEnum<Hint>.Seq(Hint.XLOCK, "XLOCK"), new Core.ParseEnum<Hint>.Seq(Hint._INDEX, "INDEX") ); } }
57.142857
142
0.398824
[ "Apache-2.0" ]
jannesen/TypedTSql
Jannesen.Language.TypedTSql/Node/Node/Node_TableHints.cs
6,802
C#
using System; using System.Drawing; using System.Globalization; using System.Text; using System.Windows.Forms; using PluginCore.Managers; namespace PluginCore.Utilities { public class DataConverter { /// <summary> /// Converts text to another encoding /// </summary> public static string ChangeEncoding(string text, int from, int to) { try { Encoding toEnc = Encoding.GetEncoding(from); Encoding fromEnc = Encoding.GetEncoding(to); byte[] fromBytes = fromEnc.GetBytes(text); byte[] toBytes = Encoding.Convert(fromEnc, toEnc, fromBytes); return toEnc.GetString(toBytes); } catch (Exception ex) { ErrorManager.ShowError(ex); return null; } } /// <summary> /// Converts Keys to correct string presentation /// </summary> public static string KeysToString(Keys keys) { KeysConverter kc = new KeysConverter(); return kc.ConvertToString(keys); } /// <summary> /// Converts a string to a Base64 string /// </summary> public static string StringToBase64(string text, Encoding encoding) { try { char[] chars = text.ToCharArray(); byte[] bytes = encoding.GetBytes(chars); return Convert.ToBase64String(bytes); } catch (Exception ex) { ErrorManager.ShowError(ex); return null; } } /// <summary> /// Converts a Base64 string to a string /// </summary> public static string Base64ToString(string base64, Encoding encoding) { try { byte[] bytes = Convert.FromBase64String(base64); return encoding.GetString(bytes); } catch (Exception ex) { ErrorManager.ShowError(ex); return null; } } /// <summary> /// Converts a String to a color (BGR order) /// </summary> public static int StringToColor(string aColor) { if (aColor != null) { Color c = Color.FromName(aColor); if (c.ToArgb() == 0 && aColor.Length >= 6) { int col; if (aColor.StartsWithOrdinal("0x")) int.TryParse(aColor.Substring(2), NumberStyles.HexNumber, null, out col); else int.TryParse(aColor, out col); return TO_COLORREF(col); } return TO_COLORREF(c.ToArgb() & 0x00ffffff); } return 0; } private static int TO_COLORREF(int c) => (((c & 0xff0000) >> 16) + ((c & 0x0000ff) << 16) + (c & 0x00ff00)); /// <summary> /// Converts a color to a string /// </summary> public static string ColorToHex(Color color) { return string.Concat("0x", color.R.ToString("X2", null), color.G.ToString("X2", null), color.B.ToString("X2", null)); } /// <summary> /// Converts a integer (BGR order) to a color /// </summary> public static Color BGRToColor(int bgr) { return Color.FromArgb((bgr >> 0) & 0xff, (bgr >> 8) & 0xff, (bgr >> 16) & 0xff); } /// <summary> /// Converts a color to an integer (BGR order) /// </summary> public static int ColorToBGR(Color color) => TO_COLORREF(color.ToArgb() & 0x00ffffff); /// <summary> /// Alias for ColorToBGR to not break the API. /// </summary> public static int ColorToInt32(Color color) => ColorToBGR(color); } }
32.52
130
0.487577
[ "MIT" ]
gvhung/flashdevelop
PluginCore/PluginCore/Utilities/DataConverter.cs
3,941
C#
using GitIssue.Fields; using GitIssue.Issues.Json; using GitIssue.Values; namespace GitIssue.Tests.IntegrationTests.Bug { /// <summary> /// A defect configuration /// </summary> public class BugConfiguration : IssueConfiguration { /// <summary> /// Initializes a new instance of the <see cref="BugConfiguration" /> class /// </summary> public BugConfiguration() { Fields.Add(FieldKey.Create("AffectsVersion"), new FieldInfo<Version, JsonArrayField>(false)); Fields.Add(FieldKey.Create("FixVersion"), new FieldInfo<Version, JsonArrayField>(false)); Fields.Add(FieldKey.Create("Severity"), new FieldInfo<Enumerated, JsonValueField>(false) { ValueMetadata = "[S1, S1, S3, S4, S5]" }); } } }
33.8
105
0.608284
[ "MIT" ]
lennoncork/GitIssue
src/GitIssue.Tests/IntegrationTests/Bug/BugConfiguration.cs
847
C#
using System; using AdaptiveCards; using Microsoft.Bot.Builder.Solutions.Responses; namespace RestaurantBooking.Shared.Resources.Cards { public class ReservationConfirmationData : ICardData { public string Title { get; set; } public string ImageUrl { get; set; } public AdaptiveImageSize ImageSize { get; set; } public AdaptiveHorizontalAlignment ImageAlign { get; set; } public string BookingPlace { get; set; } public string Location { get; set; } public string ReservationDate { get; set; } public string ReservationDateSpeak { get; set; } public string ReservationTime { get; set; } public string AttendeeCount { get; set; } public string Speak { get; set; } } }
24.34375
67
0.65982
[ "MIT" ]
adamstephensen/AI
solutions/Virtual-Assistant/src/csharp/experimental/skills/restaurantbooking/Dialogs/BookingDialog/Resources/Cards/ReservationConfirmationData.cs
781
C#
/* * 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 voice-id-2021-09-27.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.VoiceID.Model { /// <summary> /// Container for the parameters to the EvaluateSession operation. /// Evaluates a specified session based on audio data accumulated during a streaming Amazon /// Connect Voice ID call. /// </summary> public partial class EvaluateSessionRequest : AmazonVoiceIDRequest { private string _domainId; private string _sessionNameOrId; /// <summary> /// Gets and sets the property DomainId. /// <para> /// The identifier of the domain where the session started. /// </para> /// </summary> [AWSProperty(Required=true, Min=22, Max=22)] public string DomainId { get { return this._domainId; } set { this._domainId = value; } } // Check to see if DomainId property is set internal bool IsSetDomainId() { return this._domainId != null; } /// <summary> /// Gets and sets the property SessionNameOrId. /// <para> /// The session identifier, or name of the session, that you want to evaluate. In Voice /// ID integration, this is the Contact-Id. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=36)] public string SessionNameOrId { get { return this._sessionNameOrId; } set { this._sessionNameOrId = value; } } // Check to see if SessionNameOrId property is set internal bool IsSetSessionNameOrId() { return this._sessionNameOrId != null; } } }
31.283951
106
0.632991
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/VoiceID/Generated/Model/EvaluateSessionRequest.cs
2,534
C#
namespace Oculus.Platform.Samples.VrHoops { using Oculus.Platform.Models; public class RemotePlayer : Player { private User m_user; private P2PNetworkGoal m_goal; public User User { set { m_user = value; } } public ulong ID { get { return m_user.ID; } } public P2PNetworkGoal Goal { get { return m_goal; } set { m_goal = value; } } public override uint Score { set { // For now we ignore the score determined from locally scoring backets. // To get an indication of how close the physics simulations were between devices, // or whether the remote player was cheating, an estimate of the score could be // kept and compared against what the remote player was sending us. } } public void ReceiveRemoteScore(uint score) { base.Score = score; } } }
19.27907
86
0.676719
[ "MIT" ]
182719/Bachelor-Oppgave
BachelorScene/Assets/Oculus/Platform/Samples/VrHoops/Scripts/RemotePlayer.cs
829
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Support { /// <summary>Managed pipeline mode.</summary> public partial struct ManagedPipelineMode : System.IEquatable<ManagedPipelineMode> { public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ManagedPipelineMode Classic = @"Classic"; public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ManagedPipelineMode Integrated = @"Integrated"; /// <summary>the value for an instance of the <see cref="ManagedPipelineMode" /> Enum.</summary> private string _value { get; set; } /// <summary>Conversion from arbitrary object to ManagedPipelineMode</summary> /// <param name="value">the value to convert to an instance of <see cref="ManagedPipelineMode" />.</param> internal static object CreateFrom(object value) { return new ManagedPipelineMode(global::System.Convert.ToString(value)); } /// <summary>Compares values of enum type ManagedPipelineMode</summary> /// <param name="e">the value to compare against this instance.</param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ManagedPipelineMode e) { return _value.Equals(e._value); } /// <summary>Compares values of enum type ManagedPipelineMode (override for Object)</summary> /// <param name="obj">the value to compare against this instance.</param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public override bool Equals(object obj) { return obj is ManagedPipelineMode && Equals((ManagedPipelineMode)obj); } /// <summary>Returns hashCode for enum ManagedPipelineMode</summary> /// <returns>The hashCode of the value</returns> public override int GetHashCode() { return this._value.GetHashCode(); } /// <summary>Creates an instance of the <see cref="ManagedPipelineMode"/> Enum class.</summary> /// <param name="underlyingValue">the value to create an instance for.</param> private ManagedPipelineMode(string underlyingValue) { this._value = underlyingValue; } /// <summary>Returns string representation for ManagedPipelineMode</summary> /// <returns>A string for this value.</returns> public override string ToString() { return this._value; } /// <summary>Implicit operator to convert string to ManagedPipelineMode</summary> /// <param name="value">the value to convert to an instance of <see cref="ManagedPipelineMode" />.</param> public static implicit operator ManagedPipelineMode(string value) { return new ManagedPipelineMode(value); } /// <summary>Implicit operator to convert ManagedPipelineMode to string</summary> /// <param name="e">the value to convert to an instance of <see cref="ManagedPipelineMode" />.</param> public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ManagedPipelineMode e) { return e._value; } /// <summary>Overriding != operator for enum ManagedPipelineMode</summary> /// <param name="e1">the value to compare against <paramref name="e2" /></param> /// <param name="e2">the value to compare against <paramref name="e1" /></param> /// <returns><c>true</c> if the two instances are not equal to the same value</returns> public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ManagedPipelineMode e1, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ManagedPipelineMode e2) { return !e2.Equals(e1); } /// <summary>Overriding == operator for enum ManagedPipelineMode</summary> /// <param name="e1">the value to compare against <paramref name="e2" /></param> /// <param name="e2">the value to compare against <paramref name="e1" /></param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ManagedPipelineMode e1, Microsoft.Azure.PowerShell.Cmdlets.Functions.Support.ManagedPipelineMode e2) { return e2.Equals(e1); } } }
50.55102
193
0.656439
[ "MIT" ]
AlanFlorance/azure-powershell
src/Functions/generated/api/Support/ManagedPipelineMode.cs
4,857
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LiteCart_PageObject { public class Order { public int AmountGoogs { get; internal set; } public string Size { get; internal set; } } }
19.4
53
0.697595
[ "Apache-2.0" ]
dimichgml/LiteCartPageObject
LiteCartPageObject/model/Order.cs
293
C#
using Unity.UIWidgets.foundation; using Unity.UIWidgets.painting; using Unity.UIWidgets.ui; using Unity.UIWidgets.widgets; namespace Unity.UIWidgets.material { public class CardTheme : Diagnosticable { public CardTheme( Clip? clipBehavior = null, Color color = null, float? elevation = null, EdgeInsets margin = null, ShapeBorder shape = null ) { D.assert(elevation == null || elevation >= 0.0f); this.clipBehavior = clipBehavior; this.color = color; this.elevation = elevation; this.margin = margin; this.shape = shape; } public readonly Clip? clipBehavior; public readonly Color color; public readonly float? elevation; public readonly EdgeInsets margin; public readonly ShapeBorder shape; CardTheme copyWith( Clip? clipBehavior = null, Color color = null, float? elevation = null, EdgeInsets margin = null, ShapeBorder shape = null ) { return new CardTheme( clipBehavior: clipBehavior ?? this.clipBehavior, color: color ?? this.color, elevation: elevation ?? this.elevation, margin: margin ?? this.margin, shape: shape ?? this.shape ); } public static CardTheme of(BuildContext context) { return Theme.of(context).cardTheme; } public static CardTheme lerp(CardTheme a, CardTheme b, float t) { return new CardTheme( clipBehavior: t < 0.5f ? a?.clipBehavior : b?.clipBehavior, color: Color.lerp(a?.color, b?.color, t), elevation: MathUtils.lerpFloat(a?.elevation ?? 0.0f, b?.elevation ?? 0.0f, t), margin: EdgeInsets.lerp(a?.margin, b?.margin, t), shape: ShapeBorder.lerp(a?.shape, b?.shape, t) ); } public override int GetHashCode() { var hashCode = this.clipBehavior?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ this.color?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ this.elevation?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ this.margin?.GetHashCode() ?? 0; hashCode = (hashCode * 397) ^ this.shape?.GetHashCode() ?? 0; return hashCode; } public bool Equals(CardTheme other) { return other.clipBehavior == this.clipBehavior && other.color == this.color && other.elevation == this.elevation && other.margin == this.margin && other.shape == this.shape; } public override void debugFillProperties(DiagnosticPropertiesBuilder properties) { base.debugFillProperties(properties); properties.add(new DiagnosticsProperty<Clip?>("clipBehavior", this.clipBehavior, defaultValue: null)); properties.add(new DiagnosticsProperty<Color>("color", this.color, defaultValue: null)); properties.add(new DiagnosticsProperty<float?>("elevation", this.elevation, defaultValue: null)); properties.add(new DiagnosticsProperty<EdgeInsets>("margin", this.margin, defaultValue: null)); properties.add(new DiagnosticsProperty<ShapeBorder>("shape", this.shape, defaultValue: null)); } } }
40.494382
115
0.561598
[ "Apache-2.0" ]
Luciano-0/2048-Demo
Library/PackageCache/com.unity.uiwidgets@1.5.4-preview.12/Runtime/material/card_theme.cs
3,604
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OpenInvoicePeru.Servicio")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OpenInvoicePeru.Servicio")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("25d6b9af-55a6-4e7f-a061-52a492ccdb6e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.388889
84
0.744573
[ "Apache-2.0" ]
MrJmpl3-Forks/openinvoiceperu
OpenInvoicePeru/OpenInvoicePeru.Servicio/Properties/AssemblyInfo.cs
1,385
C#
using Micser.App.Infrastructure.Localization; using Micser.App.Infrastructure.Resources; using Micser.App.Infrastructure.Themes; using Micser.Common; using Micser.Common.Extensions; using System; using System.Windows; namespace Micser.App.Infrastructure { /// <summary> /// UI module performing default initialization tasks. /// </summary> public class InfrastructureModule : IAppModule { /// <inheritdoc /> public InfrastructureModule() { LocalizationManager.UiCultureChanged += OnUiCultureChanged; } /// <inheritdoc /> public void OnInitialized(IContainerProvider containerProvider) { var resourceRegistry = containerProvider.Resolve<IResourceRegistry>(); resourceRegistry.Add(new ResourceDictionary { Source = new Uri("/Micser.App.Infrastructure;component/Themes/Generic.xaml", UriKind.Relative) }); } /// <inheritdoc /> public void RegisterTypes(IContainerProvider containerRegistry) { } private static void OnUiCultureChanged(object sender, EventArgs e) { Strings.Culture = LocalizationManager.UiCulture; } } }
31.076923
156
0.672442
[ "Apache-2.0" ]
loreggia/micser
src/Micser.App.Infrastructure/InfrastructureModule.cs
1,214
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Net; namespace Lefebvre.eLefebvreOnContainers.Services.Webhooks.API.Infrastructure { using Exceptions; using Infrastructure.ActionResult; public class HttpGlobalExceptionFilter : IExceptionFilter { private readonly IWebHostEnvironment env; private readonly ILogger<HttpGlobalExceptionFilter> logger; public HttpGlobalExceptionFilter(IWebHostEnvironment env, ILogger<HttpGlobalExceptionFilter> logger) { this.env = env; this.logger = logger; } public void OnException(ExceptionContext context) { logger.LogError(new EventId(context.Exception.HResult), context.Exception, context.Exception.Message); if (context.Exception.GetType() == typeof(WebhooksDomainException)) { var problemDetails = new ValidationProblemDetails() { Instance = context.HttpContext.Request.Path, Status = StatusCodes.Status400BadRequest, Detail = "Please refer to the errors property for additional details." }; problemDetails.Errors.Add("DomainValidations", new string[] { context.Exception.Message.ToString() }); context.Result = new BadRequestObjectResult(problemDetails); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; } else { var json = new JsonErrorResponse { Messages = new[] { "An error ocurred." } }; if (env.IsDevelopment()) { json.DeveloperMeesage = context.Exception; } context.Result = new InternalServerErrorObjectResult(json); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; } context.ExceptionHandled = true; } private class JsonErrorResponse { public string[] Messages { get; set; } public object DeveloperMeesage { get; set; } } } }
34.714286
118
0.606173
[ "MIT" ]
lefevbre-organization/eShopOnContainers
src/Services/Webhooks/Webhooks.API/Infrastructure/HttpGlobalExceptionFilter.cs
2,432
C#
//Copyright (c) Microsoft Corporation. All rights reserved. using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; namespace Microsoft.WindowsAPICodePack.Taskbar { /// <summary> /// Represents a collection of jump list items. /// </summary> /// <typeparam name="T">The type of elements in this collection.</typeparam> internal class JumpListItemCollection<T> : ICollection<T>, INotifyCollectionChanged { private List<T> items = new List<T>(); /// <summary> /// Occurs anytime a change is made to the underlying collection. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged = delegate { }; /// <summary> /// Gets or sets a value that determines if this collection is read-only. /// </summary> public bool IsReadOnly { get; set; } /// <summary> /// Gets a count of the items currently in this collection. /// </summary> public int Count { get { return items.Count; } } /// <summary> /// Adds the specified item to this collection. /// </summary> /// <param name="item">The item to add.</param> public void Add(T item) { items.Add(item); // Trigger CollectionChanged event CollectionChanged( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, item)); } /// <summary> /// Removes the first instance of the specified item from the collection. /// </summary> /// <param name="item">The item to remove.</param> /// <returns><b>true</b> if an item was removed, otherwise <b>false</b> if no items were removed.</returns> public bool Remove(T item) { bool removed = items.Remove(item); if (removed == true) { // Trigger CollectionChanged event CollectionChanged( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, 0)); } return removed; } /// <summary> /// Clears all items from this collection. /// </summary> public void Clear() { items.Clear(); // Trigger CollectionChanged event CollectionChanged( this, new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Reset)); } /// <summary> /// Determines if this collection contains the specified item. /// </summary> /// <param name="item">The search item.</param> /// <returns><b>true</b> if an item was found, otherwise <b>false</b>.</returns> public bool Contains(T item) { return items.Contains(item); } /// <summary> /// Copies this collection to a compatible one-dimensional array, /// starting at the specified index of the target array. /// </summary> /// <param name="array">The array name.</param> /// <param name="index">The index of the starting element.</param> public void CopyTo(T[] array, int index) { items.CopyTo(array, index); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An enumerator to iterate through this collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return items.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection of a specified type. /// </summary> /// <returns>An enumerator to iterate through this collection.</returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return items.GetEnumerator(); } } }
32.740157
115
0.553151
[ "BSD-3-Clause" ]
KimJeongnam/Log2Console-ko-version
src/External/WindowsAPICodePack/Shell/Taskbar/JumpListItemCollection.cs
4,160
C#
using BlazorAuthorization.Shared; using Blazored.LocalStorage; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Claims; using System.Text.Json; using System.Threading.Tasks; namespace ClientSideBlazor.Client { public class ApiAuthenticationStateProvider : AuthenticationStateProvider { private readonly HttpClient _httpClient; private readonly ILocalStorageService _localStorage; public ApiAuthenticationStateProvider(HttpClient httpClient, ILocalStorageService localStorage) { _httpClient = httpClient; _localStorage = localStorage; } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var savedToken = await _localStorage.GetItemAsync<string>("authToken"); if (string.IsNullOrWhiteSpace(savedToken)) { return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())); } _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", savedToken); return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(savedToken), "jwt"))); } public void MarkUserAsAuthenticated(string token) { var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt")); var authState = Task.FromResult(new AuthenticationState(authenticatedUser)); NotifyAuthenticationStateChanged(authState); } public void MarkUserAsLoggedOut() { var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity()); var authState = Task.FromResult(new AuthenticationState(anonymousUser)); NotifyAuthenticationStateChanged(authState); } private IEnumerable<Claim> ParseClaimsFromJwt(string jwt) { var claims = new List<Claim>(); var payload = jwt.Split('.')[1]; var jsonBytes = ParseBase64WithoutPadding(payload); var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes); keyValuePairs.TryGetValue(ClaimTypes.Role, out object roles); if (roles != null) { if (roles.ToString().Trim().StartsWith("[")) { var parsedRoles = JsonSerializer.Deserialize<string[]>(roles.ToString()); foreach (var parsedRole in parsedRoles) { claims.Add(new Claim(ClaimTypes.Role, parsedRole)); } } else { claims.Add(new Claim(ClaimTypes.Role, roles.ToString())); } keyValuePairs.Remove(ClaimTypes.Role); } claims.AddRange(keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString()))); return claims; } private byte[] ParseBase64WithoutPadding(string base64) { switch (base64.Length % 4) { case 2: base64 += "=="; break; case 3: base64 += "="; break; } return Convert.FromBase64String(base64); } } }
35.622449
123
0.620166
[ "MIT" ]
chrissainty/PolicyBasedAuthWithBlazor
src/ClientSideBlazor.Client/ApiAuthenticationStateProvider.cs
3,493
C#
// Copyright 2021 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2beta1.Snippets { using Google.Cloud.Dialogflow.V2beta1; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; public sealed partial class GeneratedEnvironmentsClientStandaloneSnippets { /// <summary>Snippet for UpdateEnvironmentAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task UpdateEnvironmentRequestObjectAsync() { // Create client EnvironmentsClient environmentsClient = await EnvironmentsClient.CreateAsync(); // Initialize request argument(s) UpdateEnvironmentRequest request = new UpdateEnvironmentRequest { Environment = new Environment(), UpdateMask = new FieldMask(), AllowLoadToDraftAndDiscardChanges = false, }; // Make the request Environment response = await environmentsClient.UpdateEnvironmentAsync(request); } } }
38.978261
92
0.684328
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/dialogflow/v2beta1/google-cloud-dialogflow-v2beta1-csharp/Google.Cloud.Dialogflow.V2beta1.StandaloneSnippets/EnvironmentsClient.UpdateEnvironmentRequestObjectAsyncSnippet.g.cs
1,793
C#
using AndroidInteropLib.android.content; using AndroidInteropLib.android.util; using AndroidInteropLib.android.view; using AndroidInteropLib.org.xmlpull.v1; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace AndroidInteropLib.android.widget { public class TextView : View { TextBlock content = new TextBlock(); public TextView(Context c, AttributeSet a) : base(c, a) { } public override void CreateWinUI(params object[] obj) { content.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 115, 115, 115)); content.Margin = new Thickness(16); WinUI.Content = content; setText("null"); if(obj[1] != null && obj[1] is AttributeSet) { AttributeSet a = (AttributeSet)obj[1]; setText(a.getAttributeValue(XmlPullParser.ANDROID_NAMESPACE, "text")); } } public void setText(int resid) { //not implemented yet. //setText(mContext.getResources().); } public void setText(string text) { if (text != null) { content.Text = text; } } } }
25.625
100
0.582578
[ "Apache-2.0" ]
Ticomware/AstoriaUWP
AndroidUILib/android/widget/TextView.cs
1,437
C#
using System.Linq; using BrightstarDB.Storage.BPlusTreeStore.RelatedResourceIndex; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BrightstarDB.Tests.BPlusTreeTests { [TestClass] public class RelatedResourceIndexTests { [TestMethod] public void TestInsertRelatedResource() { ulong relatedResourceIndexRoot; using(var pageStore = TestUtils.CreateEmptyPageStore("TestInsertRelatedResource.dat")) { var relatedResourceIndex = new RelatedResourceIndex(0, pageStore); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 3ul, 4); var relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul, 4, null).ToList(); Assert.AreEqual(1, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); relatedResourceIndex.Save(0, null); relatedResourceIndexRoot = relatedResourceIndex.RootId; pageStore.Commit(0ul, null); } using(var pageStore = TestUtils.OpenPageStore("TestInsertRelatedResource.dat", true)) { var relatedResourceIndex = new RelatedResourceIndex(pageStore, relatedResourceIndexRoot, null); var relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul, 4, null).ToList(); Assert.AreEqual(1, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); } } [TestMethod] public void TestEnumerateMultipleRelatedResources() { ulong relatedResourceIndexRoot; using (var pageStore = TestUtils.CreateEmptyPageStore("TestMultipleRelatedResources.dat")) { var relatedResourceIndex = new RelatedResourceIndex(0, pageStore); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 3ul, 4); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 5ul, 4); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 6ul, 4); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 7ul, 8); var relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul, 4).ToList(); Assert.AreEqual(3, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(5ul, relatedResourceIds[1].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[2].ResourceId); relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul).ToList(); Assert.AreEqual(4, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(5ul, relatedResourceIds[1].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[2].ResourceId); Assert.AreEqual(7ul, relatedResourceIds[3].ResourceId); Assert.AreEqual(8, relatedResourceIds[3].GraphId); relatedResourceIndex.Save(0, null); relatedResourceIndexRoot = relatedResourceIndex.RootId; pageStore.Commit(0ul, null); } using (var pageStore = TestUtils.OpenPageStore("TestMultipleRelatedResources.dat", true)) { var relatedResourceIndex = new RelatedResourceIndex(pageStore, relatedResourceIndexRoot, null); var relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1, 2, 4).ToList(); Assert.AreEqual(3, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(5ul, relatedResourceIds[1].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[2].ResourceId); relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1, 2).ToList(); Assert.AreEqual(4, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(5ul, relatedResourceIds[1].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[2].ResourceId); Assert.AreEqual(7ul, relatedResourceIds[3].ResourceId); Assert.AreEqual(8, relatedResourceIds[3].GraphId); } } [TestMethod] public void TestDeleteRelatedResource() { ulong relatedResourceIndexRoot; using (var pageStore = TestUtils.CreateEmptyPageStore("TestDeleteRelatedResource.dat")) { var relatedResourceIndex = new RelatedResourceIndex(0, pageStore); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 3ul, 4); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 5ul, 4); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 6ul, 4); relatedResourceIndex.AddRelatedResource(0, 1ul, 2ul, 7ul, 8); var relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul, 4).ToList(); Assert.AreEqual(3, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(5ul, relatedResourceIds[1].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[2].ResourceId); relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul).ToList(); Assert.AreEqual(4, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(5ul, relatedResourceIds[1].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[2].ResourceId); Assert.AreEqual(7ul, relatedResourceIds[3].ResourceId); Assert.AreEqual(8, relatedResourceIds[3].GraphId); relatedResourceIndex.Save(0, null); relatedResourceIndexRoot = relatedResourceIndex.RootId; pageStore.Commit(0ul, null); } using (var pageStore = TestUtils.OpenPageStore("TestDeleteRelatedResource.dat", false)) { var relatedResourceIndex = new RelatedResourceIndex(pageStore, relatedResourceIndexRoot, null); var relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul, 4).ToList(); Assert.AreEqual(3, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(5ul, relatedResourceIds[1].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[2].ResourceId); relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul).ToList(); Assert.AreEqual(4, relatedResourceIds.Count); Assert.AreEqual(3ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(5ul, relatedResourceIds[1].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[2].ResourceId); Assert.AreEqual(7ul, relatedResourceIds[3].ResourceId); Assert.AreEqual(8, relatedResourceIds[3].GraphId); relatedResourceIndex.DeleteRelatedResource(1, 1, 2, 3, 4, null); Assert.AreEqual(3, relatedResourceIndex.EnumerateRelatedResources(1,2).Count()); relatedResourceIndex.DeleteRelatedResource(1, 1, 2, 7, 8, null); Assert.AreEqual(2, relatedResourceIndex.EnumerateRelatedResources(1, 2).Count()); relatedResourceIndex.Save(1, null); relatedResourceIndexRoot = relatedResourceIndex.RootId; pageStore.Commit(1ul, null); } using (var pageStore = TestUtils.OpenPageStore("TestDeleteRelatedResource.dat", true)) { var relatedResourceIndex = new RelatedResourceIndex(pageStore, relatedResourceIndexRoot, null); var relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul, 4).ToList(); Assert.AreEqual(2, relatedResourceIds.Count); Assert.AreEqual(5ul, relatedResourceIds[0].ResourceId); Assert.AreEqual(6ul, relatedResourceIds[1].ResourceId); relatedResourceIds = relatedResourceIndex.EnumerateRelatedResources(1ul, 2ul, 8).ToList(); Assert.AreEqual(0, relatedResourceIds.Count); } } } }
56.398693
116
0.643296
[ "MIT" ]
smkgeekfreak/BrightstarDB
src/core/BrightstarDB.InternalTests/BPlusTreeTests/RelatedResourceIndexTests.cs
8,631
C#
using MediatR; using System; using System.Collections.Generic; using System.Text; namespace EventStoreSample.Application.Commands { public class DirectPaymentCommand : IRequest<bool> { public decimal? Amount { get; set; } public int? CurrencyCode { get; set; } public string Msisdn { get; set; } public string OrderId { get; set; } } }
20.315789
54
0.660622
[ "MIT" ]
eyazici90/Galaxy
samples/eventStoreSample/EventStoreSample.Application/Commands/DirectPaymentCommand.cs
388
C#
using System.IO; using System.Management.Automation; using Microsoft.SharePoint.Client; using OfficeDevPnP.Core.Entities; using OfficeDevPnP.Core.Utilities; using PnP.PowerShell.CmdletHelpAttributes; using File = System.IO.File; namespace PnP.PowerShell.Commands.WebParts { [Cmdlet(VerbsCommon.Add, "PnPWebPartToWebPartPage")] [CmdletHelp("Adds a web part to a web part page in a specified zone", Category = CmdletHelpCategory.WebParts)] [CmdletExample( Code = @"PS:> Add-PnPWebPartToWebPartPage -ServerRelativePageUrl ""/sites/demo/sitepages/home.aspx"" -Path ""c:\myfiles\listview.webpart"" -ZoneId ""Header"" -ZoneIndex 1 ", Remarks = @"This will add the web part as defined by the XML in the listview.webpart file to the specified page in the specified zone and with the order index of 1", SortOrder = 1)] [CmdletExample( Code = @"PS:> Add-PnPWebPartToWebPartPage -ServerRelativePageUrl ""/sites/demo/sitepages/home.aspx"" -XML $webpart -ZoneId ""Header"" -ZoneIndex 1 ", Remarks = @"This will add the web part as defined by the XML in the $webpart variable to the specified page in the specified zone and with the order index of 1", SortOrder = 1)] public class AddWebPartToWebPartPage : PnPWebCmdlet { [Parameter(Mandatory = true, HelpMessage = "Server Relative Url of the page to add the web part to.")] [Alias("PageUrl")] public string ServerRelativePageUrl = string.Empty; [Parameter(Mandatory = true, ParameterSetName = "XML", HelpMessage = "A string containing the XML for the web part.")] public string Xml = string.Empty; [Parameter(Mandatory = true, ParameterSetName = "FILE", HelpMessage = "A path to a web part file on a the file system.")] public string Path = string.Empty; [Parameter(Mandatory = true, HelpMessage = "The Zone Id where the web part must be placed")] public string ZoneId; [Parameter(Mandatory = true, HelpMessage = "The Zone Index where the web part must be placed")] public int ZoneIndex; protected override void ExecuteCmdlet() { var serverRelativeWebUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl); if (!ServerRelativePageUrl.ToLowerInvariant().StartsWith(serverRelativeWebUrl.ToLowerInvariant())) { ServerRelativePageUrl = UrlUtility.Combine(serverRelativeWebUrl, ServerRelativePageUrl); } WebPartEntity wp = null; switch (ParameterSetName) { case "FILE": if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (File.Exists(Path)) { var fileStream = new StreamReader(Path); var webPartString = fileStream.ReadToEnd(); fileStream.Close(); wp = new WebPartEntity {WebPartZone = ZoneId, WebPartIndex = ZoneIndex, WebPartXml = webPartString}; } break; case "XML": wp = new WebPartEntity {WebPartZone = ZoneId, WebPartIndex = ZoneIndex, WebPartXml = Xml}; break; } if (wp != null) { SelectedWeb.AddWebPartToWebPartPage(ServerRelativePageUrl, wp); } } } }
45.461538
184
0.627186
[ "MIT" ]
FPotrafky/PnP-PowerShell
Commands/WebParts/AddWebPartToWebPartPage.cs
3,548
C#
/************************************************************************* * Copyright (c) 2010 Hu Fei(xiaotie@geblab.com; geblab, www.geblab.com) ************************************************************************/ using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Drawing.Imaging; namespace Geb.Image { [StructLayout(LayoutKind.Explicit)] public partial struct Argb32 { public static Argb32 WHITE = new Argb32 { Red = 255, Green = 255, Blue = 255, Alpha = 255 }; public static Argb32 BLACK = new Argb32 { Alpha = 255 }; public static Argb32 RED = new Argb32 { Red = 255, Alpha = 255 }; public static Argb32 BLUE = new Argb32 { Blue = 255, Alpha = 255 }; public static Argb32 GREEN = new Argb32 { Green = 255, Alpha = 255 }; public static Argb32 EMPTY = new Argb32 { }; [FieldOffset(0)] public Byte Blue; [FieldOffset(1)] public Byte Green; [FieldOffset(2)] public Byte Red; [FieldOffset(3)] public Byte Alpha; public Argb32(int red, int green, int blue, int alpha = 255) { Red = (byte)red; Green = (byte)green; Blue = (byte)blue; Alpha = (byte)alpha; } public Argb32(byte red, byte green, byte blue, byte alpha = 255) { Red = red; Green = green; Blue = blue; Alpha = alpha; } public Byte ToGray() { return (Byte)(0.299 * Red + 0.587 * Green + 0.114 * Blue); } public override string ToString() { return "Argb32 [A="+ Alpha +", R=" + Red.ToString() + ", G=" + Green.ToString() + ", B=" + Blue.ToString() + "]"; } } public struct Argb32Ptr { public unsafe Argb32* Ptr; public unsafe Argb32Ptr(Argb32* val) { Ptr = val; } public unsafe void Increase() { Ptr++; } } public struct Argb32Converter : IColorConverter { public unsafe void Copy(Rgb24* from, void* to, int length) { UnmanagedImageConverter.ToArgb32(from, (Argb32*)to, length); } public unsafe void Copy(Argb32* from, void* to, int length) { UnmanagedImageConverter.Copy((byte*)from, (byte*)to, 4* length); } public unsafe void Copy(byte* from, void* to, int length) { UnmanagedImageConverter.ToArgb32(from, (Argb32*)to, length); } } public partial class ImageArgb32 : UnmanagedImage<Argb32>, IEnumerable<Argb32Ptr> { public unsafe ImageArgb32(Int32 width, Int32 height) : base(width, height) { } public ImageArgb32(Bitmap map) :base(map) { } public ImageArgb32(String path) : base(path) { } protected override IColorConverter CreateByteConverter() { return new Argb32Converter(); } public ImageU8 ToGrayscaleImage() { return ToGrayscaleImage(0.299, 0.587, 0.114); } public ImageU8 ToGrayscaleImage(byte transparentColor) { return ToGrayscaleImage(0.299, 0.587, 0.114, transparentColor); } public unsafe ImageU8 ToGrayscaleImage(double rCoeff, double gCoeff, double bCoeff, byte transparentColor) { ImageU8 img = new ImageU8(this.Width, this.Height); Argb32* p = Start; Byte* to = img.Start; Argb32* end = p + Length; while (p != end) { if (p->Alpha == 0) { *to = transparentColor; } else { *to = (Byte)(p->Red * rCoeff + p->Green * gCoeff + p->Blue * bCoeff); } p++; to++; } return img; } public unsafe ImageU8 ToGrayscaleImage(double rCoeff, double gCoeff, double bCoeff) { ImageU8 img = new ImageU8(this.Width, this.Height); Argb32* p = Start; Byte* to = img.Start; Argb32* end = p + Length; if (Length < 1024) { while (p != end) { *to = (Byte)(p->Red * rCoeff + p->Green * gCoeff + p->Blue * bCoeff); p++; to++; } } else { int* bCache = stackalloc int[256]; int* gCache = stackalloc int[256]; int* rCache = stackalloc int[256]; const int shift = 1 << 10; int rShift = (int)(rCoeff * shift); int gShift = (int)(gCoeff * shift); int bShift = shift - rShift - gShift; int r = 0, g = 0, b = 0; for (int i = 0; i < 256; i++) { bCache[i] = b; gCache[i] = g; rCache[i] = r; b += bShift; g += gShift; r += rShift; } while (p != end) { *to = (Byte)((bCache[p->Red] + gCache[p->Green] + rCache[p->Red]) >> 10); p++; to++; } } return img; } public override IImage Clone() { ImageArgb32 img = new ImageArgb32(this.Width, this.Height); img.CloneFrom(this); return img; } protected override System.Drawing.Imaging.PixelFormat GetOutputBitmapPixelFormat() { return System.Drawing.Imaging.PixelFormat.Format32bppArgb; } protected override unsafe void ToBitmapCore(byte* src, byte* dst, int width) { UnmanagedImageConverter.Copy(src, dst, width * 4); } public unsafe void SetAlpha(byte alpha) { Argb32* start = (Argb32*)this.Start; Argb32* end = start + this.Length; while (start != end) { start->Alpha = alpha; start++; } } public unsafe void CombineAlpha(ImageArgb32 src, System.Drawing.Point start, System.Drawing.Rectangle region, System.Drawing.Point destAnchor) { if (start.X >= src.Width || start.Y >= src.Height) return; int startSrcX = Math.Max(0, start.X); int startSrcY = Math.Max(0, start.Y); int endSrcX = Math.Min(start.X + region.Width, src.Width); int endSrcY = Math.Min(start.Y + region.Height, src.Height); int offsetX = start.X < 0 ? -start.X : 0; int offsetY = start.Y < 0 ? -start.Y : 0; offsetX = destAnchor.X + offsetX; offsetY = destAnchor.Y + offsetY; int startDstX = Math.Max(0, offsetX); int startDstY = Math.Max(0, offsetY); offsetX = offsetX < 0 ? -offsetX : 0; offsetY = offsetY < 0 ? -offsetY : 0; startSrcX += offsetX; startSrcY += offsetY; int endDstX = Math.Min(destAnchor.X + region.Width, this.Width); int endDstY = Math.Min(destAnchor.Y + region.Height, this.Height); int copyWidth = Math.Min(endSrcX - startSrcX, endDstX - startDstX); int copyHeight = Math.Min(endSrcY - startSrcY, endDstY - startDstY); if (copyWidth <= 0 || copyHeight <= 0) return; int srcWidth = src.Width; int dstWidth = this.Width; Argb32* srcLine = (Argb32*)(src.StartIntPtr) + srcWidth * startSrcY + startSrcX; Argb32* dstLine = this.Start + dstWidth * startDstY + startDstX; Argb32* endSrcLine = srcLine + srcWidth * copyHeight; while (srcLine < endSrcLine) { Argb32* pSrc = srcLine; Argb32* endPSrc = pSrc + copyWidth; Argb32* pDst = dstLine; while (pSrc < endPSrc) { Argb32 p0 = *pSrc; Argb32 p1 = *pDst; switch (p0.Alpha) { case 255: *pDst = p0; break; case 0: default: break; } pSrc++; pDst++; } srcLine += srcWidth; dstLine += dstWidth; } } public IEnumerator<Argb32Ptr> GetEnumerator() { return new Argb32Enumerataor(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public class Argb32Enumerataor : IEnumerator<Argb32Ptr> { public unsafe Argb32* _start; public unsafe Argb32* _end; public Argb32Ptr _current; public unsafe Argb32** _pCurrent; public unsafe Argb32Enumerataor(UnmanagedImage<Argb32> img) { _start = (Argb32*)img.StartIntPtr; _end = _start + img.Length; this._current = new Argb32Ptr(_start); } public Argb32Ptr Current { get { return _current; } } public void Dispose() { } object System.Collections.IEnumerator.Current { get { return _current; } } public unsafe bool MoveNext() { //_current.Increase(); return _current.Ptr++ < _end; } public unsafe void Reset() { _current.Ptr = _start; } } } }
30.801802
150
0.468461
[ "MIT" ]
ProximaMonkey/GebImage
src/Geb.Image/UnmanagedImage/ImageArgb32.cs
10,259
C#
#region BSD License /* * * Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) * © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved. * * New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE) * Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2021. All rights reserved. * */ #endregion namespace Krypton.Toolkit { /// <summary> /// Defines the editing control for the DataGridViewKryptonDateTimePickerCell custom cell type. /// </summary> [ToolboxItem(false)] public class KryptonDataGridViewDateTimePickerEditingControl : KryptonDateTimePicker, IDataGridViewEditingControl { #region Static Fields private static readonly DateTimeConverter _dtc = new(); #endregion #region Instance Fields private DataGridView _dataGridView; private bool _valueChanged; #endregion #region Identity /// <summary> /// Initalize a new instance of the KryptonDataGridViewDateTimePickerEditingControl class. /// </summary> public KryptonDataGridViewDateTimePickerEditingControl() { TabStop = false; StateCommon.Border.Width = 0; StateCommon.Border.Draw = InheritBool.False; ShowBorder = false; } #endregion #region Public /// <summary> /// Property which caches the grid that uses this editing control /// </summary> public virtual DataGridView EditingControlDataGridView { get => _dataGridView; set => _dataGridView = value; } /// <summary> /// Property which represents the current formatted value of the editing control /// </summary> public virtual object EditingControlFormattedValue { get => GetEditingControlFormattedValue(DataGridViewDataErrorContexts.Formatting); set { if ((value == null) || (value == DBNull.Value)) { ValueNullable = value; } else { string formattedValue = value as string; if (string.IsNullOrEmpty(formattedValue)) { ValueNullable = (formattedValue == string.Empty) ? null : value; } else { Value = (DateTime)_dtc.ConvertFromInvariantString(formattedValue); } } } } /// <summary> /// Property which represents the row in which the editing control resides /// </summary> public virtual int EditingControlRowIndex { get; set; } /// <summary> /// Property which indicates whether the value of the editing control has changed or not /// </summary> public virtual bool EditingControlValueChanged { get => _valueChanged; set => _valueChanged = value; } /// <summary> /// Property which determines which cursor must be used for the editing panel, i.e. the parent of the editing control. /// </summary> public virtual Cursor EditingPanelCursor => Cursors.Default; /// <summary> /// Property which indicates whether the editing control needs to be repositioned when its value changes. /// </summary> public virtual bool RepositionEditingControlOnValueChange => false; /// <summary> /// Called by the grid to give the editing control a chance to prepare itself for the editing session. /// </summary> public virtual void PrepareEditingControlForEdit(bool selectAll) { } /// <summary> /// Method called by the grid before the editing control is shown so it can adapt to the provided cell style. /// </summary> public virtual void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle) { StateCommon.Content.Font = dataGridViewCellStyle.Font; StateCommon.Content.Color1 = dataGridViewCellStyle.ForeColor; StateCommon.Back.Color1 = dataGridViewCellStyle.BackColor; } /// <summary> /// Method called by the grid on keystrokes to determine if the editing control is interested in the key or not. /// </summary> public virtual bool EditingControlWantsInputKey(Keys keyData, bool dataGridViewWantsInputKey) { return (keyData & Keys.KeyCode) switch { Keys.Right or Keys.Left or Keys.Down or Keys.Up or Keys.Home or Keys.Delete => true, _ => !dataGridViewWantsInputKey }; } /// <summary> /// Returns the current value of the editing control. /// </summary> public virtual object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context) => (ValueNullable == null) || (ValueNullable == DBNull.Value) ? string.Empty : _dtc.ConvertToInvariantString(Value); #endregion #region Protected /// <summary> /// Listen to the ValueNullableChanged notification to forward the change to the grid. /// </summary> protected override void OnValueNullableChanged(EventArgs e) { base.OnValueNullableChanged(e); if (Focused) { NotifyDataGridViewOfValueChange(); } } #endregion #region Private private void NotifyDataGridViewOfValueChange() { if (!_valueChanged) { _valueChanged = true; _dataGridView.NotifyCurrentCellDirty(true); } } #endregion } }
35.405882
217
0.592623
[ "BSD-3-Clause" ]
Krypton-Suite/Standard-Toolk
Source/Krypton Components/Krypton.Toolkit/Controls Toolkit/KryptonDataGridViewDateTimePickerEditingControl.cs
6,022
C#
using System; using Spike.AggregateRepository.Lib.Base; namespace Spike.AggregateRepository.Lib.Vacancies { public class VacancyRepository : BaseRepository<Vacancy>, IVacancyRepository { public VacancyRepository(IRepositoryStore<Vacancy> store) : base(store) { } protected override void InitialiseInstance(Vacancy instance) { instance.Status = VacancyStatus.New; } protected override void ApplyChange(Vacancy instance, Vacancy change) { instance.Title = change.Title ?? instance.Title; instance.Description = change.Description ?? instance.Description; instance.Status = change.Status; instance.ChangeInfo = change.ChangeInfo ?? instance.ChangeInfo; } } }
33.791667
84
0.657213
[ "MIT" ]
mgwilliam/Spike.AggregateRepository
Spike.AggregateRepository.Lib/Vacancies/VacancyRepository.cs
813
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StackIndex : MonoBehaviour { public int indexNumber; }
17
39
0.79085
[ "MIT" ]
ZedCrome/TheTaleoftheGreenhouse
TheTaleofTheGreenhouse/Assets/Scripts/Objects/StackIndex.cs
155
C#
using System; using System.Collections.Generic; using System.Text; using Xunit.Abstractions; namespace NeodymiumDotNet.Optimizations.Test { internal sealed class TestHelperWriter : System.IO.TextWriter { private readonly ITestOutputHelper _helper; private StringBuilder _buffer; public override Encoding Encoding => Encoding.UTF8; public TestHelperWriter(ITestOutputHelper helper) { _helper = helper; _buffer = new StringBuilder(); } public override void Write(char value) { if(value == '\n') { _helper.WriteLine(_buffer.ToString()); _buffer = new StringBuilder(); } else { _buffer.Append(value); } } public override void WriteLine(string message) => _helper.WriteLine(message); public override void WriteLine(string message, params object[] args) => _helper.WriteLine(message, args); } }
26.575
76
0.585136
[ "Apache-2.0" ]
aka-nd1220/NeodymiumDotNet
NeodymiumDotNet.Optimizations.Test/TestHelperWriter.cs
1,065
C#
using Microsoft.EntityFrameworkCore; namespace OpenBudgeteer.Core.Common.Database; public class SqliteDatabaseContext : DatabaseContext { public SqliteDatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { } }
19.769231
91
0.762646
[ "Apache-2.0", "MIT" ]
Hazy87/OpenBudgeteer
OpenBudgeteer.Core/Common/Database/SqliteDatabaseContext.cs
259
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using NadekoBot.Common.Attributes; using NadekoBot.Core.Services; using NadekoBot.Core.Services.Database.Models; using NadekoBot.Extensions; using NadekoBot.Modules.Administration.Services; using NadekoBot.Modules.Utility.Services; namespace NadekoBot.Modules.Utility { public partial class Utility { [Group] public class RemindCommands : NadekoSubmodule<RemindService> { private readonly DbService _db; private readonly GuildTimezoneService _tz; public RemindCommands(DbService db, GuildTimezoneService tz) { _db = db; _tz = tz; } public enum MeOrHere { Me, Here } [NadekoCommand, Usage, Description, Aliases] [Priority(1)] public async Task Remind(MeOrHere meorhere, [Leftover] string remindString) { if (!_service.TryParseRemindMessage(remindString, out var remindData)) { await ReplyErrorLocalizedAsync("remind_invalid"); return; } ulong target; target = meorhere == MeOrHere.Me ? ctx.User.Id : ctx.Channel.Id; if (!await RemindInternal(target, meorhere == MeOrHere.Me || ctx.Guild == null, remindData.Time, remindData.What) .ConfigureAwait(false)) { await ReplyErrorLocalizedAsync("remind_too_long").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [UserPerm(GuildPerm.ManageMessages)] [Priority(0)] public async Task Remind(ITextChannel channel, [Leftover] string remindString) { var perms = ((IGuildUser) ctx.User).GetPermissions(channel); if (!perms.SendMessages || !perms.ViewChannel) { await ReplyErrorLocalizedAsync("cant_read_or_send").ConfigureAwait(false); return; } if (!_service.TryParseRemindMessage(remindString, out var remindData)) { await ReplyErrorLocalizedAsync("remind_invalid"); return; } if (!await RemindInternal(channel.Id, false, remindData.Time, remindData.What) .ConfigureAwait(false)) { await ReplyErrorLocalizedAsync("remind_too_long").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] public async Task RemindList(int page = 1) { if (--page < 0) return; var embed = new EmbedBuilder() .WithOkColor() .WithTitle(GetText("reminder_list")); List<Reminder> rems; using (var uow = _db.GetDbContext()) { rems = uow.Reminders.RemindersFor(ctx.User.Id, page) .ToList(); } if (rems.Any()) { var i = 0; foreach (var rem in rems) { var when = rem.When; var diff = when - DateTime.UtcNow; embed.AddField( $"#{++i + (page * 10)} {rem.When:HH:mm yyyy-MM-dd} UTC (in {(int) diff.TotalHours}h {(int) diff.Minutes}m)", $@"`Target:` {(rem.IsPrivate ? "DM" : "Channel")} `TargetId:` {rem.ChannelId} `Message:` {rem.Message?.TrimTo(50)}", false); } } else { embed.WithDescription(GetText("reminders_none")); } embed.AddPaginatedFooter(page + 1, null); await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] public async Task RemindDelete(int index) { if (--index < 0) return; var embed = new EmbedBuilder(); Reminder rem = null; using (var uow = _db.GetDbContext()) { var rems = uow.Reminders.RemindersFor(ctx.User.Id, index / 10) .ToList(); var pageIndex = index % 10; if (rems.Count > pageIndex) { rem = rems[pageIndex]; uow.Reminders.Remove(rem); uow.SaveChanges(); } } if (rem == null) { await ReplyErrorLocalizedAsync("reminder_not_exist").ConfigureAwait(false); } else { await ReplyErrorLocalizedAsync("reminder_deleted", index + 1).ConfigureAwait(false); } } private async Task<bool> RemindInternal(ulong targetId, bool isPrivate, TimeSpan ts, string message) { var time = DateTime.UtcNow + ts; if (ts > TimeSpan.FromDays(330)) return false; if (ctx.Guild != null) { var perms = ((IGuildUser) ctx.User).GetPermissions((IGuildChannel) ctx.Channel); if (!perms.MentionEveryone) { message = message.SanitizeAllMentions(); } } var rem = new Reminder { ChannelId = targetId, IsPrivate = isPrivate, When = time, Message = message, UserId = ctx.User.Id, ServerId = ctx.Guild?.Id ?? 0 }; using (var uow = _db.GetDbContext()) { uow.Reminders.Add(rem); await uow.SaveChangesAsync(); } var gTime = ctx.Guild == null ? time : TimeZoneInfo.ConvertTime(time, _tz.GetTimeZoneOrUtc(ctx.Guild.Id)); try { await ctx.Channel.SendConfirmAsync( "⏰ " + GetText("remind", Format.Bold(!isPrivate ? $"<#{targetId}>" : ctx.User.Username), Format.Bold(message), $"{ts.Days}d {ts.Hours}h {ts.Minutes}min", gTime, gTime)).ConfigureAwait(false); } catch { } return true; } } } }
35.121359
136
0.459572
[ "MIT" ]
Gibstick/nadekobot_fork
NadekoBot.Core/Modules/Utility/RemindCommands.cs
7,239
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SirJosh3917 { /// <summary> /// Up to the test for V 232 /// </summary> public class BlockPacket { /// <summary> /// Deserialize ANY message, ranging from 'block' to 'b', 'br', 'bs', e.t.c /// </summary> /// <param name="e"></param> /// <returns></returns> public static BlockPacket Deserialize(PlayerIOClient.Message e) { return new BlockPacket(e); } /// <summary> /// Auto deserialize given message /// </summary> /// <param name="e"></param> public BlockPacket(PlayerIOClient.Message e) { this.Deserialized = false; #region Deserialize 'block' if (IsValidCustomBlockMessage(e)) { //We're recieving back one of our special packets! //remember: we don't need to check each type ( e.g. if( e[0] is uint ) ) because IsValidCustomBlockMessage(e) covered that for us uint playerid = e.GetUInt(0); uint layer = e.GetUInt(1); uint x = e.GetUInt(2); uint y = e.GetUInt(3); uint blockid = e.GetUInt(4); uint blocktype = e.GetUInt(5); uint numbervalue = 0, morphvalue = 0, soundvalue = 0, portalrotation = 0, portalid = 0, portaltarget = 0, signtype = 0; string labeltext = "", labelcolor = "", signtext = "", worldtarget = "", npcname = "", npcchat1 = "", npcchat2 = "", npcchat3 = ""; if (!Enum.IsDefined(typeof(BlockIdentifier), (uint)BlockType)) throw new Exception("Invalid unigned integer used for enum."); this.PlayerId = playerid; this.Layer = layer; this.X = x; this.Y = y; this.BlockId = blockid; this.BlockType = (BlockIdentifier)blocktype; switch (blocktype) { case 0: { //plain block break; } case 1: { numbervalue = e.GetUInt(6); break; } case 2: { morphvalue = e.GetUInt(6); break; } case 3: { soundvalue = e.GetUInt(6); break; } case 4: { labeltext = e.GetString(6); labelcolor = e.GetString(7); break; } case 5: { //portal portalrotation = e.GetUInt(6); portalid = e.GetUInt(7); portaltarget = e.GetUInt(8); break; } case 6: { //sign signtext = e.GetString(6); signtype = e.GetUInt(7); break; } case 7: { //world portal worldtarget = e.GetString(6); break; } case 8: { npcname = e.GetString(6); npcchat1 = e.GetString(7); npcchat2 = e.GetString(8); npcchat3 = e.GetString(9); } break; } this.NumberValue = numbervalue; this.MorphableValue = morphvalue; this.SoundValue = (int)soundvalue; //lazy this.LabelText = labeltext; this.LabelColor = labelcolor; this.PortalRotation = portalrotation; this.PortalId = portalid; this.PortalTarget = portaltarget; this.SignText = signtext; this.SignType = signtype; this.WorldTarget = worldtarget; this.NPCName = npcname; this.NPCChat1 = npcchat1; this.NPCChat2 = npcchat2; this.NPCChat3 = npcchat3; this.Deserialized = true; return; } #endregion #region Deserialize 'b' and the likes switch (e.Type) { case "b": { if (e.Count > 4) if (e[0] is int && e[1] is uint && e[2] is uint && e[3] is uint && e[4] is uint) { int layer = e.GetInt(0); uint x = e.GetUInt(1); uint y = e.GetUInt(2); uint blockId = e.GetUInt(3); uint playerId = e.GetUInt(4); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = (uint)layer; this.X = x; this.Y = y; this.BlockId = blockId; this.BlockType = BlockIdentifier.Plain; Deserialized = true; } } break; case "bn": { if (e.Count > 7) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is string && e[4] is string && e[5] is string && e[6] is string && e[7] is uint) { uint layer = 0; uint x = e.GetUInt(0); uint y = e.GetUInt(1); uint blockId = e.GetUInt(2); string npcName = e.GetString(3); string npcChat1 = e.GetString(4); string npcChat2 = e.GetString(5); string npcChat3 = e.GetString(6); uint playerId = e.GetUInt(7); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = layer; this.X = x; this.Y = y; this.BlockId = blockId; this.BlockType = BlockIdentifier.NPC; this.NPCName = npcName; this.NPCChat1 = npcChat1; this.NPCChat2 = npcChat2; this.NPCChat3 = npcChat3; Deserialized = true; } } break; case "bc": { if (e.Count > 4) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is uint && e[4] is uint) { uint layer = 0; //sadly we have to hardcode values :/ uint x = e.GetUInt(0); uint y = e.GetUInt(1); uint blockId = e.GetUInt(2); uint numbervalue = e.GetUInt(3); uint playerId = e.GetUInt(4); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = layer; this.X = x; this.Y = y; this.BlockId = blockId; this.BlockType = BlockIdentifier.NumberValue; this.NumberValue = numbervalue; Deserialized = true; } } break; case "br": { if (e.Count > 5) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is uint && e[4] is int && e[5] is uint) { uint x = e.GetUInt(0); uint y = e.GetUInt(1); uint blockId = e.GetUInt(2); uint morph = e.GetUInt(3); int layer = e.GetInt(4); uint playerId = e.GetUInt(5); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = (uint)layer; this.X = x; this.Y = y; this.BlockId = blockId; this.BlockType = BlockIdentifier.Morphable; this.MorphableValue = morph; Deserialized = true; } } break; case "bs": { if (e.Count > 4) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is int && e[4] is uint) { int layer = 0; //unfortunate hardcoding uint x = e.GetUInt(0); uint y = e.GetUInt(1); uint blockId = e.GetUInt(2); int sound = e.GetInt(3); uint playerId = e.GetUInt(4); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = (uint)layer; this.X = x; this.Y = y; this.BlockId = blockId; this.BlockType = BlockIdentifier.Sound; this.SoundValue = sound; Deserialized = true; } } break; case "lb": { if (e.Count > 5) if (e[0] is uint && e[1] is uint && e[2] is int && e[3] is string && e[4] is string && e[5] is uint) { int layer = 0; //unfortunate hardcoding uint x = e.GetUInt(0); uint y = e.GetUInt(1); int blockId = e.GetInt(2); string text = e.GetString(3); string textColor = e.GetString(4); uint playerId = e.GetUInt(5); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); if (blockId < 0) throw new Exception("BlockId Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = (uint)layer; this.X = x; this.Y = y; this.BlockId = (uint)blockId; this.BlockType = BlockIdentifier.Label; this.LabelText = text; this.LabelColor = textColor; Deserialized = true; } } break; case "pt": { if (e.Count > 6) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is uint && e[4] is uint && e[5] is uint && e[6] is uint) { /* THE PROTOCOL SAYS THAT THIS IS A INT. */ int layer = 0; //unfortunate hardcoding uint x = e.GetUInt(0); uint y = e.GetUInt(1); uint blockId = e.GetUInt(2); uint portalRotation = e.GetUInt(3); uint portalId = e.GetUInt(4); uint portalTarget = e.GetUInt(5); uint playerId = e.GetUInt(6); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = (uint)layer; this.X = x; this.Y = y; this.BlockId = blockId; this.BlockType = BlockIdentifier.Portal; this.PortalRotation = portalRotation; this.PortalId = portalId; this.PortalTarget = portalTarget; Deserialized = true; } } break; case "ts": { if (e.Count > 5) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is string && e[4] is uint && e[5] is uint) { int layer = 0; //unfortunate hardcoding uint x = e.GetUInt(0); uint y = e.GetUInt(1); uint blockId = e.GetUInt(2); string text = e.GetString(3); uint signType = e.GetUInt(4); uint playerId = e.GetUInt(5); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = (uint)layer; this.X = x; this.Y = y; this.BlockId = (uint)blockId; this.BlockType = BlockIdentifier.Sign; this.SignText = text; this.SignType = signType; Deserialized = true; } } break; case "wp": { if (e.Count > 4) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is string && e[4] is uint) { int layer = 0; //unfortunate hardcoding uint x = e.GetUInt(0); uint y = e.GetUInt(1); uint blockId = e.GetUInt(2); string target = e.GetString(3); uint playerId = e.GetUInt(4); if (layer < 0) throw new Exception("Layer Integer is less than 0, not suitable for integer to uint conversion."); this.PlayerId = playerId; this.Layer = (uint)layer; this.X = x; this.Y = y; this.BlockId = blockId; this.BlockType = BlockIdentifier.WorldPortal; this.WorldTarget = target; Deserialized = true; } } break; } #endregion } #region serialize private int IntForm(uint b) { uint manip = b; while (manip > (uint)int.MaxValue) manip -= (uint)int.MaxValue; return (int)manip; } /// <summary> /// Serialize this BlockPacket to a Sendable B, a tl;dr 'b' packet that you can send directly to place the exact same block. /// </summary> /// <returns></returns> public PlayerIOClient.Message SerializeToSendableB() { PlayerIOClient.Message build = PlayerIOClient.Message.Create("b"); build.Add(IntForm(Layer), IntForm(X), IntForm(Y), IntForm(BlockId)); switch (BlockType) { case BlockIdentifier.Plain: { } break; case BlockIdentifier.NumberValue: { build.Add(IntForm(NumberValue)); } break; case BlockIdentifier.Morphable: { build.Add(IntForm(MorphableValue)); } break; case BlockIdentifier.Sound: { build.Add(SoundValue); } break; case BlockIdentifier.Label: { build.Add(LabelText); build.Add(LabelColor); } break; case BlockIdentifier.Portal: { build.Add(IntForm(PortalRotation)); build.Add(IntForm(PortalId)); build.Add(IntForm(PortalTarget)); } break; case BlockIdentifier.Sign: { build.Add(SignText); build.Add(IntForm(SignType)); } break; case BlockIdentifier.WorldPortal: { build.Add(WorldTarget); } break; case BlockIdentifier.NPC: { build.Add(NPCName); build.Add(NPCChat1); build.Add(NPCChat2); build.Add(NPCChat3); } break; default: { throw new Exception("Invalid BlockIdentifier."); } } return build; } /// <summary> /// Serialize this BlockPacket to one of EE's 'b' messages, can be interpreted and used for various classes and the likes. Will return 'b', 'bc', 'bs', 'pt', 'ts', e.t.c e.t.c exactly as the packet should be ( int and all ). /// </summary> /// <returns></returns> public PlayerIOClient.Message SerializeToB() { switch (BlockType) { case BlockIdentifier.Plain: { return PlayerIOClient.Message.Create("b", IntForm(Layer), X, Y, BlockId, PlayerId); } case BlockIdentifier.NPC: { return PlayerIOClient.Message.Create("bn", X, Y, BlockId, NPCName, NPCChat1, NPCChat2, NPCChat3, PlayerId); } case BlockIdentifier.NumberValue: { return PlayerIOClient.Message.Create("bc", X, Y, BlockId, NumberValue, PlayerId); } case BlockIdentifier.Morphable: { return PlayerIOClient.Message.Create("br", X, Y, BlockId, MorphableValue, IntForm(Layer), PlayerId); } case BlockIdentifier.Sound: { return PlayerIOClient.Message.Create("bs", X, Y, BlockId, SoundValue, PlayerId); } case BlockIdentifier.Label: { return PlayerIOClient.Message.Create("lb", X, Y, IntForm(BlockId), LabelText, LabelColor, PlayerId); } case BlockIdentifier.Portal: { return PlayerIOClient.Message.Create("pt", X, Y, BlockId, PortalRotation, PortalId, PortalTarget, PlayerId); } case BlockIdentifier.Sign: { return PlayerIOClient.Message.Create("ts", X, Y, BlockId, SignText, SignType, PlayerId); } case BlockIdentifier.WorldPortal: { return PlayerIOClient.Message.Create("wp", X, Y, BlockId, WorldTarget, PlayerId); } } throw new Exception("Invalid BlockIdentifier."); } /// <summary> /// Serialize this BlockPacket to the custom 'block' packet that I, ninjasupeatsninja, propose EE to use.. /// </summary> /// <returns></returns> public PlayerIOClient.Message SerializeToBlockPacket() { PlayerIOClient.Message build = PlayerIOClient.Message.Create("block"); if (!Enum.IsDefined(typeof(BlockIdentifier), (uint)BlockType)) throw new Exception("Invalid unigned integer used for enum."); build.Add(PlayerId); build.Add(Layer); build.Add(X); build.Add(Y); build.Add(BlockId); build.Add((uint)BlockType); switch (BlockType) { case BlockIdentifier.Plain: { } break; case BlockIdentifier.NumberValue: { build.Add(this.NumberValue); } break; case BlockIdentifier.Morphable: { build.Add(this.MorphableValue); } break; case BlockIdentifier.Sound: { build.Add(this.SoundValue); } break; case BlockIdentifier.Label: { build.Add(this.LabelText); build.Add(this.LabelColor); } break; case BlockIdentifier.Portal: { build.Add(this.PortalRotation); build.Add(this.PortalId); build.Add(this.PortalTarget); } break; case BlockIdentifier.Sign: { build.Add(this.SignText); build.Add(this.SignType); } break; case BlockIdentifier.WorldPortal: { build.Add(this.WorldTarget); } break; case BlockIdentifier.NPC: { build.Add(this.NPCName); build.Add(this.NPCChat1); build.Add(this.NPCChat2); build.Add(this.NPCChat3); } break; default: { throw new Exception("Undefined BlockIdentifier encountered."); } } if (IsValidCustomBlockMessage(build)) return build; else throw new Exception("Invalid 'build' message created - this is a weird internal exception! Perhaps you're changing my class' code?"); } #endregion #region packet checkers /// <summary> /// Check if a packet type is a /// 'b' /// 'bc' /// 'br' /// 'bs' /// 'lb' /// 'pt' /// 'ts' /// 'wp' /// </summary> /// <param name="e"></param> /// <returns></returns> public static bool IsValidEEBlockMessage(PlayerIOClient.Message e) { var i = e.Type; if (i == "b" || //Plain i == "bc" || //Number value i == "bn" || //NPC i == "br" || //Morphable i == "bs" || //Sound i == "lb" || //Label i == "pt" || //Portal i == "ts" || //Sign i == "wp") //World Portal switch (e.Type) { case "b": { if (e.Count > 4) if (e[0] is int && e[1] is uint && e[2] is uint && e[3] is uint && e[4] is uint) { return true; } } break; case "bc": { if (e.Count > 4) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is uint && e[4] is uint) { return true; } } break; case "bn": { if (e.Count > 7) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is string && e[4] is string && e[5] is string && e[6] is string && e[7] is uint) { return true; } } break; case "br": { if (e.Count > 5) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is uint && e[4] is int && e[5] is uint) { return true; } } break; case "bs": { if (e.Count > 4) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is int && e[4] is uint) { return true; } } break; case "lb": { if (e.Count > 5) if (e[0] is uint && e[1] is uint && e[2] is int && e[3] is string && e[4] is string && e[5] is uint) { return true; } } break; case "pt": { if (e.Count > 6) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is uint && e[4] is uint && e[5] is uint && e[6] is uint) { return true; } } break; case "ts": { if (e.Count > 5) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is string && e[4] is uint && e[5] is uint) { return true; } } break; case "wp": { if (e.Count > 4) if (e[0] is uint && e[1] is uint && e[2] is uint && e[3] is string && e[4] is uint) { return true; } } break; } return false; } /// <summary> /// Check if a packet matches the requirement for a 'block' packet. /// </summary> /// <param name="e"></param> /// <returns></returns> public static bool IsValidCustomBlockMessage(PlayerIOClient.Message e) { if (e.Type == "block") if (e.Count > 5) if (e[0] is uint && //valid base parameters e[1] is uint && e[2] is uint && e[3] is uint && e[4] is uint && e[5] is uint) { switch (e.GetUInt(5)) { case 0: { //plain block return true; } break; case 1: case 2: case 3: { //number value / morph / sound if (e.Count > 6) return e[6] is uint; } break; case 4: { // label if (e.Count > 7) return e[6] is string && e[7] is string; } break; case 5: { //portal if (e.Count > 8) return e[6] is uint && e[7] is uint && e[8] is uint; } break; case 6: { //sign if (e.Count > 7) return e[6] is string && e[7] is uint; } break; case 7: { //world portal if (e.Count > 6) return e[6] is string; } break; case 8: { //npc if(e.Count > 9) return e[6] is string && e[7] is string && e[8] is string && e[9] is string; } break; } } return false; } #endregion #region variables /// <summary> If deserialization completed with no errors. Useful for debugging. </summary> public bool Deserialized { get; private set; } public uint PlayerId { get; private set; } public uint Layer { get; private set; } public uint X { get; private set; } public uint Y { get; private set; } public uint BlockId { get; private set; } public BlockIdentifier BlockType { get; private set; } #region extra block params //Plain //Number public uint NumberValue { get; private set; } //Morphable public uint MorphableValue { get; set; } //Sound public int SoundValue { get; set; } //Label public string LabelText { get; private set; } public string LabelColor { get; private set; } //Portal public uint PortalRotation { get; private set; } public uint PortalId { get; private set; } public uint PortalTarget { get; private set; } //SignBlock public string SignText { get; private set; } public uint SignType { get; private set; } //WorldPortal public string WorldTarget { get; private set; } //NPC public string NPCName { get; private set; } public string NPCChat1 { get; private set; } public string NPCChat2 { get; private set; } public string NPCChat3 { get; private set; } #endregion public enum BlockIdentifier : uint { Plain = 0, NumberValue = 1, Morphable = 2, Sound = 3, Label = 4, Portal = 5, Sign = 6, WorldPortal = 7, NPC = 8, } #endregion } }
24.936146
226
0.553706
[ "MIT" ]
SirJosh3917/BlockPacket
BlockPacket/BlockPacket.cs
21,869
C#
//#define ASTAR_NO_POOLING //Disable pooling for some reason. Could be debugging or just for measuring the difference. using System; using System.Collections.Generic; namespace Pathfinding { public static class PathPool<T> where T : Path, new() { private static Stack<T> pool; private static int totalCreated; static PathPool () { pool = new Stack<T>(); } /** Recycles a path and puts in the pool. * This function should not be used directly. Instead use the Path.Claim and Path.Release functions. */ public static void Recycle (T path) { lock (pool) { #if UNITY_EDITOR // I am trusting the developer that it at least 1 time tests the game in the editor // Increases performance in builds if (!System.Type.Equals (path.GetType (), typeof(T))) { throw new ArgumentException ("Cannot recycle path of type '"+path.GetType().Name+"' in a pool for path type '"+typeof(T).Name+"'.\n" + "Most likely the path type does not have support for recycling. Please do not call Recycle () on that path"); } #endif path.recycled = true; path.OnEnterPool (); pool.Push (path); } } /** Warms up path, node list and vector list pools. * Makes sure there is at least \a count paths, each with a minimum capacity for paths with length \a length in the pool. * The capacity means that paths shorter or equal to the capacity can be calculated without any large allocations taking place. */ public static void Warmup (int count, int length) { Pathfinding.Util.ListPool<GraphNode>.Warmup (count, length); Pathfinding.Util.ListPool<UnityEngine.Vector3>.Warmup (count, length); Path[] tmp = new Path[count]; for (int i=0;i<count;i++) { tmp[i] = GetPath (); tmp[i].Claim (tmp); } for (int i=0;i<count;i++) tmp[i].Release (tmp); } public static int GetTotalCreated () { return totalCreated; } public static int GetSize () { return pool.Count; } public static T GetPath () { lock (pool) { T result; if (pool.Count > 0) { result = pool.Pop (); } else { result = new T (); totalCreated++; } result.recycled = false; result.Reset(); return result; } } } }
29
139
0.654725
[ "MIT" ]
Brackeys/WaveIncoming
Assets/AstarPathfindingProject/Core/Misc/PathPool.cs
2,233
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("BasicSpa.Data")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BasicSpa.Data")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("abd5e998-fdb8-4511-8f83-ea9d00fb17f7")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
29.27027
57
0.743306
[ "MIT" ]
surviveplus/SPA-Sample
vs2015ja/BasicSpa-3-Database/BasicSpa.Data/Properties/AssemblyInfo.cs
1,652
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using Squidex.Domain.Apps.Core.Apps; using Squidex.Domain.Apps.Entities.Apps.Commands; using Squidex.Domain.Apps.Entities.Apps.Services; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Entities.Apps.Guards { public static class GuardApp { public static void CanCreate(CreateApp command) { Guard.NotNull(command, nameof(command)); Validate.It(() => "Cannot create app.", e => { if (!command.Name.IsSlug()) { e("Name must be a valid slug.", nameof(command.Name)); } }); } public static void CanChangePlan(ChangePlan command, AppPlan plan, IAppPlansProvider appPlans) { Guard.NotNull(command, nameof(command)); Validate.It(() => "Cannot change plan.", e => { if (string.IsNullOrWhiteSpace(command.PlanId)) { e("Plan id is required.", nameof(command.PlanId)); return; } if (appPlans.GetPlan(command.PlanId) == null) { e("A plan with this id does not exist.", nameof(command.PlanId)); } if (!string.IsNullOrWhiteSpace(command.PlanId) && plan != null && !plan.Owner.Equals(command.Actor)) { e("Plan can only changed from the user who configured the plan initially."); } if (string.Equals(command.PlanId, plan?.PlanId, StringComparison.OrdinalIgnoreCase)) { e("App has already this plan."); } }); } } }
34.639344
116
0.474207
[ "MIT" ]
BtrJay/squidex
src/Squidex.Domain.Apps.Entities/Apps/Guards/GuardApp.cs
2,116
C#
using UnityEngine; // Represents a visual piece, gives different accesses to a piece's GameObject namespace GameView { public class PieceScript : MonoBehaviour { private Sprite m_sprite1; // Black square private Sprite m_sprite2; // White square private Sprite m_spriteGlow1; // Black square glowing sprite private Sprite m_spriteGlow2; // White square glowing sprite private PieceType m_type; private Color m_color; private GameModel.Piece m_piece; public PieceScript(PieceType type, Color color, GameModel.Square square) { m_type = type; m_color = color; gameObject.transform.position = Board.ToUnityCoord(square); if (!InitSprites()) { Debug.LogError("Error initializating sprites for " + m_type); return; } gameObject.GetComponent<SpriteRenderer>().sprite = (square.X + square.Y) % 2 == 0 ? m_sprite1 : m_sprite2; gameObject.SetActive(true); } public PieceScript(PieceType type, Color color, GameModel.Intersection intersection) { m_type = type; m_color = color; gameObject.transform.position = Board.ToUnityCoord(intersection); if (!InitSprites()) { Debug.LogError("Error initializating sprites for " + m_type); return; } SpriteRenderer.sprite = (intersection.A + intersection.B) % 2 == 0 ? m_sprite1 : m_sprite2; gameObject.SetActive(true); } public PieceScript(PieceType type, Color color, GameModel.Piece piece, Vector3 position) { m_type = type; m_color = color; gameObject.transform.position = position; if (!InitSprites()) { Debug.LogError("Error initializating sprites for " + GameModel.GetString.GetStr(piece.Type)); return; } CheckSprite(); gameObject.SetActive(true); } // Init the piece's sprites depending on its type, color and position public bool InitSprites() { string spriteName = ""; spriteName += m_type.ToString(); spriteName += m_color == Color.Black ? " A" : " B"; spriteName += 1; spriteName += ".png"; // Loading black square sprite m_sprite1 = Resources.Load<Sprite>(spriteName); if (m_sprite1 == null) return false; // Changing sprite to white square spriteName = spriteName.Replace((char) 1, (char) 2); // Loading white square sprite m_sprite2 = Resources.Load<Sprite>(spriteName); if (m_sprite2 == null) return false; // Changing sprite to white square glowing spriteName = spriteName.Replace(".png", "glow.png"); // Loading white square glowing sprite m_spriteGlow2 = Resources.Load<Sprite>(spriteName); if (m_spriteGlow2 == null) return false; // Changing sprite to black square glowing spriteName = spriteName.Replace((char) 2, (char) 1); // Loading black square glowing sprite m_spriteGlow1 = Resources.Load<Sprite>(spriteName); if (m_spriteGlow1 == null) return false; return true; } // Checks and uses the adapted sprite, regarding to the row+column alignment (meaning: the actual square color) public void CheckSprite() { Sprite = (this.Square.X + this.Square.Y) % 2 == 0 ? m_sprite2 : m_sprite1; } /* UNITY METHODS */ // When the mouse is pressed then released over the piece private void OnMouseUpAsButton() { AppManagers.IOManager.OnPieceClicked(this.m_piece); } /* ACCESSORS */ public PieceType Type { get; set; } public Color Color { get; set; } public SpriteRenderer SpriteRenderer { get; set; } public BoxCollider2D Collider { get; set; } public GameModel.Piece Piece { get; set; } public Sprite Sprite { get { return gameObject.GetComponent<SpriteRenderer>().sprite; } set { gameObject.GetComponent<SpriteRenderer>().sprite = value; } } public GameModel.Square Square { get { return Board.ToModelSqr(gameObject.transform.position); } set { gameObject.transform.position = Board.ToUnityCoord(value); } } public GameModel.Intersection Intersection { get { return Board.ToModelIntr(gameObject.transform.position); } set { gameObject.transform.position = Board.ToUnityCoord(value); } } } }
33.105263
119
0.563593
[ "MIT" ]
ZyriabDsgn/Plankton-Synapse
src/view/PieceScript.cs
5,034
C#
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Org.Apache.REEF.Tang.Annotations; using Org.Apache.REEF.Tang.Util; namespace Org.Apache.REEF.Tang.Interface { public interface ICsConfigurationBuilder : IConfigurationBuilder { /// <summary> /// Binds the named parameter. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> ICsConfigurationBuilder BindNamedParameter(Type name, string value); //name must extend from Name<T> /// <summary> /// Binds the class impl as the implementation of the interface iface /// </summary> /// <param name="iface">The iface.</param> /// <param name="impl">The impl.</param> ICsConfigurationBuilder BindImplementation(Type iface, Type impl); /// <summary> /// Binds the List entry. /// </summary> /// <param name="iface">The iface. It is a Name of IList</param> /// <param name="impl">The impl.</param> ICsConfigurationBuilder BindList(Type iface, IList<Type> impl); /// <summary> /// Binds the named parameter. /// </summary> /// <typeparam name="U"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="name">The name.</param> /// <param name="value">The value.</param> ICsConfigurationBuilder BindNamedParameter<U, T>(GenericType<U> name, string value) where U : Name<T>; /// <summary> /// Binds the named parameter. /// </summary> /// <typeparam name="U"></typeparam> /// <typeparam name="V"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="iface">The iface.</param> /// <param name="impl">The impl.</param> ICsConfigurationBuilder BindNamedParameter<U, V, T>(GenericType<U> iface, GenericType<V> impl) where U : Name<T> where V : T; /// <summary> /// Binds the implementation. /// </summary> /// <typeparam name="U"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="iface">The iface.</param> /// <param name="impl">The impl.</param> ICsConfigurationBuilder BindImplementation<U, T>(GenericType<U> iface, GenericType<T> impl) where T : U; //public <T> void bindConstructor(Class<T> c, Class<? extends ExternalConstructor<? extends T>> v) throws BindException; ICsConfigurationBuilder BindConstructor<T, U>(GenericType<T> c, GenericType<U> v) where U : IExternalConstructor<T>; //public <T> void bindSetEntry(Class<? extends Name<Set<T>>> iface, String value) throws BindException; ICsConfigurationBuilder BindSetEntry<U, T>(GenericType<U> iface, string value) where U : Name<ISet<T>>; //public <T> void bindSetEntry(Class<? extends Name<Set<T>>> iface, Class<? extends T> impl) throws BindException; ICsConfigurationBuilder BindSetEntry<U, V, T>(GenericType<U> iface, GenericType<V> impl) where U : Name<ISet<T>> where V : T; ICsConfigurationBuilder BindList<U, V, T>(GenericType<U> iface, IList<GenericType<V>> impl) where U : Name<IList<T>> where V : T; ICsConfigurationBuilder BindList<U, T>(GenericType<U> iface, IList<string> impl) where U : Name<IList<T>>; ICsConfigurationBuilder BindNamedParameter<U, V, T>() where U : Name<T> where V : T; ICsConfigurationBuilder BindNamedParam<TName, TType>(string str) where TName : Name<TType>; ICsConfigurationBuilder BindStringNamedParam<T>(string str) where T : Name<string>; ICsConfigurationBuilder BindIntNamedParam<T>(string str) where T : Name<int>; ICsConfigurationBuilder BindImplementation<T1, T2>() where T2 : T1; ICsConfigurationBuilder BindSetEntry<T1, T2, T3>() where T1 : Name<ISet<T3>> where T2 : T3; ICsConfigurationBuilder BindSetEntry<U, T>(string value) where U : Name<ISet<T>>; ICsConfigurationBuilder BindList<U, T>(IList<string> impl) where U : Name<IList<T>>; ICsConfigurationBuilder BindConstructor<T, U>() where U : IExternalConstructor<T>; } }
42.081967
128
0.636151
[ "Apache-2.0" ]
tmajest/incubator-reef
lang/cs/Org.Apache.REEF.Tang/Interface/ICsConfigurationBuilder.cs
5,136
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace HelloEmpty { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
31.439024
122
0.639255
[ "MIT" ]
syneffort/Server_Web
0.Sources/HelloAspNet/HelloEmpty/Startup.cs
1,289
C#
#region License // // Copyright 2002-2017 Drew Noakes // Ported from Java to C# by Yakov Danilov for Imazen LLC in 2014 // // 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. // // More information about this project is available at: // // https://github.com/drewnoakes/metadata-extractor-dotnet // https://drewnoakes.com/code/exif/ // #endregion using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace MetadataExtractor.Formats.Exif.Makernotes { /// <summary>Describes tags specific to Ricoh cameras.</summary> /// <author>Drew Noakes https://drewnoakes.com</author> [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public class RicohMakernoteDirectory : Directory { public const int TagMakernoteDataType = 0x0001; public const int TagVersion = 0x0002; public const int TagPrintImageMatchingInfo = 0x0E00; public const int TagRicohCameraInfoMakernoteSubIfdPointer = 0x2001; private static readonly Dictionary<int, string> _tagNameMap = new Dictionary<int, string> { { TagMakernoteDataType, "Makernote Data Type" }, { TagVersion, "Version" }, { TagPrintImageMatchingInfo, "Print Image Matching (PIM) Info" }, { TagRicohCameraInfoMakernoteSubIfdPointer, "Ricoh Camera Info Makernote Sub-IFD" } }; public RicohMakernoteDirectory() { SetDescriptor(new RicohMakernoteDescriptor(this)); } public override string Name => "Ricoh Makernote"; protected override bool TryGetTagName(int tagType, out string tagName) { return _tagNameMap.TryGetValue(tagType, out tagName); } } }
36.967213
97
0.691353
[ "Apache-2.0" ]
AkosLukacs/metadata-extractor-dotnet
MetadataExtractor/Formats/Exif/makernotes/RicohMakernoteDirectory.cs
2,255
C#
namespace Adnc.Infra.Core.DependencyInjection; public sealed class ServiceLocator { private ServiceLocator() { } static ServiceLocator() { } /// <summary> /// 只能获取Singleton/Transient,获取Scoped周期的对象会存与构造函数获取的不是相同对象 /// </summary> public static IServiceProvider? Provider { get; set; } }
19.294118
61
0.670732
[ "MIT" ]
Jiayg/Adnc
src/ServerApi/Infrastructures/Adnc.Infra.Core/Adnc/DependencyInjection/ServiceLocator.cs
386
C#
//----------------------------------------------------------------------- // <copyright file="Bootstrapper.cs" company="James Chaldecott"> // Copyright (c) 2012-2013 James Chaldecott. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Reflection; using System.Windows.Controls; using Caliburn.Micro; using Microsoft.Phone.Controls; using TivoAhoy.Common.Services; using TivoAhoy.Common.ViewModels; namespace TivoAhoy.Phone { public class Bootstrapper : PhoneBootstrapper { private PhoneContainer container; protected override void Configure() { container = new PhoneContainer(); container.RegisterPhoneServices(RootFrame); container.Instance<IProgressService>(new ProgressService(RootFrame)); container.Singleton<IAnalyticsService, AnalyticsService>(); container.Singleton<ITivoConnectionService, TivoConnectionService>(); container.Singleton<IScheduledRecordingsService, ScheduledRecordingsService>(); container.PerRequest<SettingsPageViewModel>(); container.PerRequest<MainPageViewModel>(); container.PerRequest<ShowContainerShowsPageViewModel>(); container.PerRequest<CollectionDetailsPageViewModel>(); container.PerRequest<ShowDetailsPageViewModel>(); container.PerRequest<PersonDetailsPageViewModel>(); container.PerRequest<MyShowsViewModel>(); container.PerRequest<ChannelListViewModel>(); container.PerRequest<ToDoListViewModel>(); container.PerRequest<SearchViewModel>(); container.PerRequest<IndividualShowViewModel>(); container.PerRequest<OfferViewModel>(); container.PerRequest<RecordingViewModel>(); container.PerRequest<ShowContainerViewModel>(); container.PerRequest<LazyRecordingFolderItemViewModel>(); container.PerRequest<PersonItemViewModel>(); container.PerRequest<CollectionItemViewModel>(); container.PerRequest<CreditsViewModel>(); container.PerRequest<PersonContentViewModel>(); container.PerRequest<UpcomingOffersViewModel>(); AddCustomConventions(); } protected override IEnumerable<Assembly> SelectAssemblies() { var assemblies = new List<Assembly> { typeof(Bootstrapper).Assembly, typeof(MainPageViewModel).Assembly }; AssemblySource.Instance.AddRange(assemblies); return base.SelectAssemblies(); } protected override object GetInstance(Type service, string key) { return container.GetInstance(service, key); } protected override IEnumerable<object> GetAllInstances(Type service) { return container.GetAllInstances(service); } protected override void BuildUp(object instance) { container.BuildUp(instance); } protected override void OnLaunch(object sender, Microsoft.Phone.Shell.LaunchingEventArgs e) { EnableAnalytics(true); EnableConnections(true); base.OnLaunch(sender, e); } private void EnableConnections(bool enable) { var connectionService = (ITivoConnectionService)this.container.GetInstance(typeof(ITivoConnectionService), null); connectionService.IsConnectionEnabled = enable; } private void EnableAnalytics(bool enable) { var analytics = (IAnalyticsService)this.container.GetInstance(typeof(IAnalyticsService), null); if (enable) { analytics.OpenSession(); } else { analytics.CloseSession(); } } protected override void OnClose(object sender, Microsoft.Phone.Shell.ClosingEventArgs e) { base.OnClose(sender, e); EnableConnections(false); EnableAnalytics(false); } protected override void OnActivate(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e) { EnableAnalytics(true); EnableConnections(true); base.OnActivate(sender, e); } protected override void OnDeactivate(object sender, Microsoft.Phone.Shell.DeactivatedEventArgs e) { base.OnDeactivate(sender, e); EnableConnections(false); EnableAnalytics(false); } protected override void OnUnhandledException(object sender, System.Windows.ApplicationUnhandledExceptionEventArgs e) { try { var analytics = (IAnalyticsService)this.container.GetInstance(typeof(IAnalyticsService), null); analytics.AppCrash(e.ExceptionObject); } catch (Exception) { // Ignore errors when logging } base.OnUnhandledException(sender, e); } static void AddCustomConventions() { ViewModelLocator.AddNamespaceMapping("TivoAhoy.Phone.Views", "TivoAhoy.Common.ViewModels", "View"); ViewModelLocator.AddNamespaceMapping("TivoAhoy.Phone.Views", "TivoAhoy.Common.ViewModels", "Page"); ViewLocator.AddNamespaceMapping("TivoAhoy.Common.ViewModels", "TivoAhoy.Phone.Views", "View"); ViewLocator.AddNamespaceMapping("TivoAhoy.Common.ViewModels", "TivoAhoy.Phone.Views", "Page"); ConventionManager.AddElementConvention<PerformanceProgressBar>(PerformanceProgressBar.IsIndeterminateProperty, "IsIndeterminate", "Loaded"); ConventionManager.AddElementConvention<Pivot>(Pivot.ItemsSourceProperty, "SelectedItem", "SelectionChanged").ApplyBinding = (viewModelType, path, property, element, convention) => { if (ConventionManager .GetElementConvention(typeof(ItemsControl)) .ApplyBinding(viewModelType, path, property, element, convention)) { ConventionManager .ConfigureSelectedItem(element, Pivot.SelectedItemProperty, viewModelType, path); ConventionManager .ApplyHeaderTemplate(element, Pivot.HeaderTemplateProperty, null, viewModelType); return true; } return false; }; ConventionManager.AddElementConvention<Panorama>(Panorama.ItemsSourceProperty, "SelectedItem", "SelectionChanged").ApplyBinding = (viewModelType, path, property, element, convention) => { if (ConventionManager .GetElementConvention(typeof(ItemsControl)) .ApplyBinding(viewModelType, path, property, element, convention)) { ConventionManager .ConfigureSelectedItem(element, Panorama.SelectedItemProperty, viewModelType, path); ConventionManager .ApplyHeaderTemplate(element, Panorama.HeaderTemplateProperty, null, viewModelType); return true; } return false; }; ConventionManager.AddElementConvention<ListPicker>(ListPicker.ItemsSourceProperty, "SelectedItem", "SelectionChanged") .ApplyBinding = (viewModelType, path, property, element, convention) => { if (ConventionManager.GetElementConvention(typeof(ItemsControl)) .ApplyBinding(viewModelType, path, property, element, convention)) { ConventionManager .ConfigureSelectedItem(element, ListPicker.SelectedItemProperty, viewModelType, path); //ConventionManager // .ApplyHeaderTemplate(element, ListPicker.HeaderTemplateProperty, null, viewModelType); return true; } return false; }; } } }
40.75576
153
0.573948
[ "MIT" ]
swythan/showlist-tivo
Src/TivoAhoy.Phone/Bootstrapper.cs
8,846
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Text; using System.Threading.Tasks; using AspNetCore.Identity.LiteDB.Models; using EmbyStat.Common; using EmbyStat.Common.Helpers; using EmbyStat.Common.Models.Account; using EmbyStat.Common.Models.Entities; using EmbyStat.Common.Models.Settings; using EmbyStat.Logging; using EmbyStat.Services.Interfaces; using Microsoft.AspNetCore.Identity; using Microsoft.IdentityModel.Tokens; namespace EmbyStat.Services { public class AccountService : IAccountService { private readonly SignInManager<EmbyStatUser> _signInManager; private readonly UserManager<EmbyStatUser> _userManager; private readonly AppSettings _appSettings; private readonly Logger _logger; private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler; public AccountService(SignInManager<EmbyStatUser> signInManager, UserManager<EmbyStatUser> userManager, ISettingsService settingsService, JwtSecurityTokenHandler jwtSecurityTokenHandler) { _signInManager = signInManager; _jwtSecurityTokenHandler = jwtSecurityTokenHandler; _userManager = userManager; _userManager.Options.User.RequireUniqueEmail = false; _appSettings = settingsService.GetAppSettings(); _logger = LogFactory.CreateLoggerForType(typeof(AccountService), "ACCOUNT"); } public async Task<AuthenticateResponse> Authenticate(AuthenticateRequest login, string remoteIp) { var result = await _signInManager.PasswordSignInAsync(login.Username, login.Password, login.RememberMe, false); if (!result.Succeeded) { return null; } var user = await _userManager.FindByNameAsync(login.Username); var token = AuthenticationHelper.GenerateAccessToken(user, _appSettings.Jwt, _jwtSecurityTokenHandler); var refreshToken = AuthenticationHelper.GenerateRefreshToken(); user.AddRefreshToken(refreshToken, user.Id, remoteIp); await _userManager.UpdateAsync(user); return new AuthenticateResponse { AccessToken = token, RefreshToken = refreshToken, }; } public async Task<AuthenticateResponse> RefreshToken(string accessToken, string refreshToken, string remoteIp) { var tokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Jwt.Key)), ValidateLifetime = false }; var principal = _jwtSecurityTokenHandler.ValidateToken(accessToken, tokenValidationParameters, out var securityToken); if (!(securityToken is JwtSecurityToken jwtSecurityToken) || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token"); } if (principal == null) { return null; } var username = principal.Claims.First(c => c.Type == "sub"); var user = await _userManager.FindByNameAsync(username.Value); if (user != null && user.HasValidRefreshToken(refreshToken)) { var token = AuthenticationHelper.GenerateAccessToken(user, _appSettings.Jwt, _jwtSecurityTokenHandler); var newRefreshToken = AuthenticationHelper.GenerateRefreshToken(); user.RemoveRefreshToken(refreshToken); user.AddRefreshToken(newRefreshToken, user.Id, remoteIp); await _userManager.UpdateAsync(user); return new AuthenticateResponse { AccessToken = token, RefreshToken = newRefreshToken, }; } return null; } public async Task Register(AuthenticateRequest login) { var user = new EmbyStatUser { UserName = login.Username, Roles = new List<string> { Constants.JwtClaims.Admin, Constants.JwtClaims.User }, Email = new EmailInfo(), EmailConfirmed = false }; await _userManager.CreateAsync(user, login.Password); } public async Task LogOut() { await _signInManager.SignOutAsync(); } public bool AnyAdmins() { var boe = _userManager.Users.ToList(); return _userManager.Users.Any(x => x.Roles.Contains(Constants.JwtClaims.Admin)); } public async Task<bool> ChangePassword(ChangePasswordRequest request) { var user = await _userManager.FindByNameAsync(request.UserName); if (user == null) { return false; } var result = await _userManager.ChangePasswordAsync(user, request.OldPassword, request.NewPassword); if (!result.Succeeded) { _logger.Warn($"Password update for ${user.UserName} failed with following message \n ${result.Errors.Select(x => x.Code + " - " + x.Description + "\n")}"); } return result.Succeeded; } public async Task<bool> ChangeUserName(ChangeUserNameRequest request) { var user = await _userManager.FindByNameAsync(request.UserName); if (user == null) { return false; } var result = await _userManager.SetUserNameAsync(user, request.NewUserName); if (!result.Succeeded) { _logger.Warn($"Username update for ${user.UserName} failed with following message \n ${result.Errors.Select(x => x.Code + " - " + x.Description + "\n")}"); } return result.Succeeded; } public async Task<bool> ResetPassword(string username) { var user = await _userManager.FindByNameAsync(username); if (user != null) { var token = await _userManager.GeneratePasswordResetTokenAsync(user); var newPassword = RandomString(15); await _userManager.ResetPasswordAsync(user, token, newPassword); _logger.Info("------------------------------"); _logger.Info($"Password reset requested for user {user.UserName}"); _logger.Info($"New Password: {newPassword}"); _logger.Info("------------------------------"); return true; } return false; } private static string RandomString(int length) { var random = new Random(); const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } } }
38.401042
185
0.609114
[ "MIT" ]
mregni/EmbyStat
EmbyStat.Services/AccountService.cs
7,375
C#
using Newtonsoft.Json; namespace SFA.DAS.CourseDelivery.Domain.ImportTypes { public class Address { [JsonProperty("address1")] public string Address1 { get; set; } [JsonProperty("address2")] public string Address2 { get; set; } [JsonProperty("town")] public string Town { get; set; } [JsonProperty("county")] public string County { get; set; } [JsonProperty("lat")] public double Lat { get; set; } [JsonProperty("long")] public double Long { get; set; } [JsonProperty("postcode")] public string Postcode { get; set; } } }
25.96
51
0.577812
[ "MIT" ]
SkillsFundingAgency/das-coursedelivery-api
src/SFA.DAS.CourseDelivery.Domain/ImportTypes/Address.cs
649
C#
using System; using UnityEditor; using UnityEngine; namespace ETEditor { [TypeDrawer] public class Vector2TypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (Vector2); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { return EditorGUILayout.Vector2Field(memberName, (Vector2) value); } } }
24.2
106
0.617769
[ "MIT" ]
naivetang/2019MiniGame22
Unity/Assets/Editor/ComponentViewEditor/TypeDrawer/Vector2TypeDrawer.cs
484
C#
using System.Collections.Generic; using System.Text.Json.Serialization; using Essensoft.Paylink.Alipay.Domain; namespace Essensoft.Paylink.Alipay.Response { /// <summary> /// AlipayCommerceSportsVenueModifyResponse. /// </summary> public class AlipayCommerceSportsVenueModifyResponse : AlipayResponse { /// <summary> /// 具体地址 /// </summary> [JsonPropertyName("address")] public string Address { get; set; } /// <summary> /// 区域code /// </summary> [JsonPropertyName("area_code")] public string AreaCode { get; set; } /// <summary> /// 是否可预定 Y/N (不传默认可预定) /// </summary> [JsonPropertyName("bookable")] public string Bookable { get; set; } /// <summary> /// 城市code /// </summary> [JsonPropertyName("city_code")] public string CityCode { get; set; } /// <summary> /// 场馆介绍 /// </summary> [JsonPropertyName("desc")] public string Desc { get; set; } /// <summary> /// 纬度 /// </summary> [JsonPropertyName("latitude")] public string Latitude { get; set; } /// <summary> /// 经度 /// </summary> [JsonPropertyName("longitude")] public string Longitude { get; set; } /// <summary> /// 场馆名称 /// </summary> [JsonPropertyName("name")] public string Name { get; set; } /// <summary> /// 营业时间 开始时间 - 结束时间; /// </summary> [JsonPropertyName("opening_hours")] public string OpeningHours { get; set; } /// <summary> /// 服务商场馆ID /// </summary> [JsonPropertyName("out_venue_id")] public string OutVenueId { get; set; } /// <summary> /// 联系电话 /// </summary> [JsonPropertyName("phone")] public List<string> Phone { get; set; } /// <summary> /// 场馆图片链接列表 最多5张 /// </summary> [JsonPropertyName("picture_list")] public List<string> PictureList { get; set; } /// <summary> /// poi /// </summary> [JsonPropertyName("poi")] public string Poi { get; set; } /// <summary> /// 场馆主图海报链接 /// </summary> [JsonPropertyName("poster")] public string Poster { get; set; } /// <summary> /// 场馆售卖产品类型集合,逗号隔开 calendar:价格日历 ticket:票券 course: 课程 /// </summary> [JsonPropertyName("product_type_list")] public List<string> ProductTypeList { get; set; } /// <summary> /// 省份code /// </summary> [JsonPropertyName("province_code")] public string ProvinceCode { get; set; } /// <summary> /// 子场馆列表 /// </summary> [JsonPropertyName("sub_venue_list")] public List<SubVenueQueryInfo> SubVenueList { get; set; } /// <summary> /// 标签列表 /// </summary> [JsonPropertyName("tag_list")] public List<string> TagList { get; set; } /// <summary> /// 交通信息 /// </summary> [JsonPropertyName("traffic")] public string Traffic { get; set; } /// <summary> /// 支付宝场馆ID /// </summary> [JsonPropertyName("venue_id")] public string VenueId { get; set; } /// <summary> /// 场馆商户pid /// </summary> [JsonPropertyName("venue_pid")] public string VenuePid { get; set; } /// <summary> /// 场馆状态 /// </summary> [JsonPropertyName("venue_status")] public string VenueStatus { get; set; } /// <summary> /// 场馆类型, 01足球;02篮球;03乒乓球;04羽毛球;05台球;06射箭;07哒哒球;08游泳;09网球;10攀岩;11空手道;12跆拳道;14瑜伽;15搏击;16舞蹈;17艺术体操;18太极;19击剑;20水上运动;21滑雪;22健身;23轮滑;24排球;25门球;00其他运动 /// </summary> [JsonPropertyName("venue_type")] public List<string> VenueType { get; set; } } }
26.662252
153
0.51391
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Response/AlipayCommerceSportsVenueModifyResponse.cs
4,464
C#
using Fishie.Behaviour; using SFML.Graphics; using SFML.System; using System; using System.Collections.Generic; using System.Text; namespace Fishie.Entities { public class MyCursor : Entity { public MyCursor(RenderWindow window, FloatRect gameArea) : base() { Character = new Character(this); Character.ControlStrategy = new ControlStrategyMouse(window); Character.UpdateStrategy = new UpdateStrategyVelocity(); Character.Radius = 6.0f; Character.PointCount = 3; Character.FillColor = Color.Magenta; this.gameArea = gameArea; } public override void Draw(RenderTarget target, RenderStates states) { target.Draw(Character, states); } public override void HandleInput() { Character.HandleInput(); } public override void RegisterEventHandlers(RenderWindow target) { } public override void Update(float deltaTime) { Character.Update(deltaTime); Vector2f pos = Character.Position; float radius = Character.Radius; if (pos.X - radius < gameArea.Left) { Character.Position = new Vector2f(gameArea.Left + radius, Character.Position.Y); } else if (pos.X + radius > (gameArea.Left + gameArea.Width)) { Character.Position = new Vector2f(gameArea.Left + gameArea.Width - radius, Character.Position.Y); } if (pos.Y - radius < gameArea.Top) { Character.Position = new Vector2f(Character.Position.X, gameArea.Top + radius); } else if (pos.Y + radius > (gameArea.Top + gameArea.Height)) { Character.Position = new Vector2f(Character.Position.X, gameArea.Top + gameArea.Height - radius); } } protected override void DoTouch(Entity entity) { } protected override void DoDetach(Entity entity) { } private FloatRect gameArea; } }
30.671233
114
0.554712
[ "MIT" ]
LazyPride/Fishie
Fishie/Entities/MyCursor.cs
2,241
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. namespace MultiModalSpeechDetection { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Psi; using Microsoft.Psi.Audio; using Microsoft.Psi.Imaging; using Microsoft.Psi.Kinect; using Microsoft.Psi.Speech; /// <summary> /// Kinect sample program. /// </summary> public class Program { // Variables related to Psi private const int Width = 1920; private const int Height = 1080; private const string ApplicationName = "KinectSample"; private static TimeSpan hundredMs = TimeSpan.FromSeconds(0.1); /// <summary> /// Main entry point. /// </summary> public static void Main() { Program prog = new Program(); prog.PerformMultiModalSpeechDetection(); } /// <summary> /// Event handler for the <see cref="Pipeline.PipelineCompleted"/> event. /// </summary> /// <param name="sender">The sender which raised the event.</param> /// <param name="e">The pipeline completion event arguments.</param> private static void Pipeline_PipelineCompleted(object sender, PipelineCompletedEventArgs e) { Console.WriteLine("Pipeline execution completed with {0} errors", e.Errors.Count); } /// <summary> /// Event handler for the <see cref="Pipeline.PipelineExceptionNotHandled"/> event. /// </summary> /// <param name="sender">The sender which raised the event.</param> /// <param name="e">The pipeline exception event arguments.</param> private static void Pipeline_PipelineException(object sender, PipelineExceptionNotHandledEventArgs e) { Console.WriteLine(e.Exception); } /// <summary> /// This is the main code for our Multimodal Speech Detection demo. /// </summary> private void PerformMultiModalSpeechDetection() { Console.WriteLine("Initializing Psi."); bool detected = false; // First create our \Psi pipeline using (var pipeline = Pipeline.Create("MultiModalSpeechDetection")) { // Register an event handler to catch pipeline errors pipeline.PipelineExceptionNotHandled += Pipeline_PipelineException; // Register an event handler to be notified when the pipeline completes pipeline.PipelineCompleted += Pipeline_PipelineCompleted; // Next create our Kinect sensor. We will be using the color images, face tracking, and audio from the Kinect sensor var kinectSensorConfig = new KinectSensorConfiguration(); kinectSensorConfig.OutputColor = true; kinectSensorConfig.OutputAudio = true; kinectSensorConfig.OutputBodies = true; // In order to detect faces using Kinect you must also enable detection of bodies var kinectSensor = new KinectSensor(pipeline, kinectSensorConfig); var kinectFaceDetector = new Microsoft.Psi.Kinect.Face.KinectFaceDetector(pipeline, kinectSensor, Microsoft.Psi.Kinect.Face.KinectFaceDetectorConfiguration.Default); // Create our Voice Activation Detector var speechDetector = new SystemVoiceActivityDetector(pipeline); var convertedAudio = kinectSensor.Audio.Resample(WaveFormat.Create16kHz1Channel16BitPcm()); convertedAudio.PipeTo(speechDetector); // Use the Kinect's face track to determine if the mouth is opened var mouthOpenAsFloat = kinectFaceDetector.Faces.Where(faces => faces.Count > 0).Select((List<Microsoft.Psi.Kinect.Face.KinectFace> list) => { if (!detected) { detected = true; Console.WriteLine("Found your face"); } bool open = (list[0] != null) ? list[0].FaceProperties[Microsoft.Kinect.Face.FaceProperty.MouthOpen] == Microsoft.Kinect.DetectionResult.Yes : false; return open ? 1.0 : 0.0; }); // Next take the "mouthOpen" value and create a hold on that value (so that we don't see 1,0,1,0,1 but instead would see 1,1,1,1,0.8,0.6,0.4) var mouthOpen = mouthOpenAsFloat.Hold(0.1); // Next join the results of the speechDetector with the mouthOpen generator and only select samples where // we have detected speech and that the mouth was open. var mouthAndSpeechDetector = speechDetector.Join(mouthOpen, hundredMs).Select((t, e) => t.Item1 && t.Item2); // Convert our speech into text var speechRecognition = convertedAudio.SpeechToText(mouthAndSpeechDetector); speechRecognition.Do((s, t) => { if (s.Item1.Length > 0) { Console.WriteLine("You said: " + s.Item1); } }); // Create a stream of landmarks (points) from the face detector var facePoints = new List<Tuple<System.Windows.Point, string>>(); var landmarks = kinectFaceDetector.Faces.Where(faces => faces.Count > 0).Select((List<Microsoft.Psi.Kinect.Face.KinectFace> list) => { facePoints.Clear(); System.Windows.Point pt1 = new System.Windows.Point( list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.EyeLeft].X, list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.EyeLeft].Y); facePoints.Add(Tuple.Create(pt1, string.Empty)); System.Windows.Point pt2 = new System.Windows.Point( list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.EyeRight].X, list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.EyeRight].Y); facePoints.Add(Tuple.Create(pt2, string.Empty)); System.Windows.Point pt3 = new System.Windows.Point( list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.MouthCornerLeft].X, list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.MouthCornerLeft].Y); facePoints.Add(Tuple.Create(pt3, string.Empty)); System.Windows.Point pt4 = new System.Windows.Point( list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.MouthCornerRight].X, list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.MouthCornerRight].Y); facePoints.Add(Tuple.Create(pt4, string.Empty)); System.Windows.Point pt5 = new System.Windows.Point( list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.Nose].X, list[0].FacePointsInColorSpace[Microsoft.Kinect.Face.FacePointType.Nose].Y); facePoints.Add(Tuple.Create(pt5, string.Empty)); return facePoints; }); // ******************************************************************** // Finally create a Live Visualizer using PsiStudio. // We must persist our streams to a store in order for Live Viz to work properly // ******************************************************************** // Create store for the data. Live Visualizer can only read data from a store. var pathToStore = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos); Microsoft.Psi.Data.Exporter store = Store.Create(pipeline, ApplicationName, pathToStore); mouthOpen.Select(v => v ? 1d : 0d).Write("MouthOpen", store); speechDetector.Select(v => v ? 1d : 0d).Write("VAD", store); mouthAndSpeechDetector.Write("Join(MouthOpen,VAD)", store); kinectSensor.Audio.Write("Audio", store); var images = kinectSensor.ColorImage.EncodeJpeg(90, DeliveryPolicy.LatestMessage).Out; Store.Write(images, "Images", store, true, DeliveryPolicy.LatestMessage); landmarks.Write("FaceLandmarks", store); // Run the pipeline pipeline.RunAsync(); Console.WriteLine("Press any key to finish recording"); Console.ReadKey(); } } } }
49.77095
181
0.588506
[ "MIT" ]
DeCatNiels/psi
Samples/KinectSample/Program.cs
8,911
C#
using System.Reflection; using MediatR; using Microsoft.EntityFrameworkCore; using Npgsql; using SiteWatcher.Application.Interfaces; using SiteWatcher.Domain.Exceptions; using SiteWatcher.Domain.Models; using SiteWatcher.Infra.Extensions; namespace SiteWatcher.Infra; public class SiteWatcherContext : DbContext, IUnitOfWork { private readonly IAppSettings _appSettings; private readonly IMediator _mediator; public const string Schema = "siteWatcher_webApi"; public SiteWatcherContext(IAppSettings appSettings, IMediator mediator) { _appSettings = appSettings; _mediator = mediator; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseNpgsql(_appSettings.ConnectionString); if (_appSettings.IsDevelopment) { optionsBuilder .EnableSensitiveDataLogging() .LogTo(Console.WriteLine); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.HasDefaultSchema(Schema); modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); } public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) { try { await _mediator.DispatchDomainEvents(this); return await base.SaveChangesAsync(cancellationToken); } catch (DbUpdateException ex) { var inner = ex.InnerException; if ((inner as PostgresException)?.SqlState != PostgresErrorCodes.UniqueViolation) throw; throw GenerateUniqueViolationException(ex); } } protected UniqueViolationException GenerateUniqueViolationException(DbUpdateException exception) { var modelNames = string.Join("; ", exception.Entries.Select(e => e.Metadata.Name.Split('.').Last())); return new UniqueViolationException(modelNames); } public DbSet<User> Users { get; set; } }
31.485294
109
0.696871
[ "MIT" ]
xilapa/SiteWatcher
src/Infra/Persistence/SiteWatcherContext.cs
2,143
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Abp.Authorization; using Abp.Configuration; using Abp.Domain.Uow; using YMApp.Authorization.Roles; using YMApp.Authorization.Users; using YMApp.MultiTenancy; namespace YMApp.Identity { public class SignInManager : AbpSignInManager<Tenant, Role, User> { public SignInManager( UserManager userManager, IHttpContextAccessor contextAccessor, UserClaimsPrincipalFactory claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<User>> logger, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IAuthenticationSchemeProvider schemes) : base( userManager, contextAccessor, claimsFactory, optionsAccessor, logger, unitOfWorkManager, settingManager, schemes) { } } }
30.025641
69
0.64731
[ "MIT" ]
yannis123/YMApp
src/ymapp-aspnet-core/src/YMApp.Core/Identity/SignInManager.cs
1,171
C#
/* * 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 neptune-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.Neptune.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.Neptune.Model.Internal.MarshallTransformations { /// <summary> /// DeleteDBInstance Request Marshaller /// </summary> public class DeleteDBInstanceRequestMarshaller : IMarshaller<IRequest, DeleteDBInstanceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DeleteDBInstanceRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DeleteDBInstanceRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.Neptune"); request.Parameters.Add("Action", "DeleteDBInstance"); request.Parameters.Add("Version", "2014-10-31"); if(publicRequest != null) { if(publicRequest.IsSetDBInstanceIdentifier()) { request.Parameters.Add("DBInstanceIdentifier", StringUtils.FromString(publicRequest.DBInstanceIdentifier)); } if(publicRequest.IsSetFinalDBSnapshotIdentifier()) { request.Parameters.Add("FinalDBSnapshotIdentifier", StringUtils.FromString(publicRequest.FinalDBSnapshotIdentifier)); } if(publicRequest.IsSetSkipFinalSnapshot()) { request.Parameters.Add("SkipFinalSnapshot", StringUtils.FromBool(publicRequest.SkipFinalSnapshot)); } } return request; } private static DeleteDBInstanceRequestMarshaller _instance = new DeleteDBInstanceRequestMarshaller(); internal static DeleteDBInstanceRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteDBInstanceRequestMarshaller Instance { get { return _instance; } } } }
35.957895
147
0.633782
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Neptune/Generated/Model/Internal/MarshallTransformations/DeleteDBInstanceRequestMarshaller.cs
3,416
C#
using NExpect.Exceptions; using NExpect.Interfaces; using NExpect.MatcherLogic; using NUnit.Framework; namespace NExpect.Tests.DanglingPrepositions { [TestFixture] public class A { [Test] public void ShouldProvideExtensionPoint() { // Arrange // Pre-Assert // Act Assert.That( () => { Expectations.Expect(new Frog() as object).To.Be.A.Frog(); }, Throws.Nothing); Assert.That( () => { Expectations.Expect(new Frog() as object).Not.To.Be.A.Frog(); }, Throws.Exception.InstanceOf<UnmetExpectationException>() .With.Message.Contains("Expected not to get a frog")); // Assert } } public class Frog { } public static class ExtensionsForTestingA { public static void Frog(this IA<object> continuation) { continuation.AddMatcher( o => { var passed = o is Frog; return new MatcherResult( passed, () => passed ? "Expected not to get a frog" : "Expected to get a frog"); }); } } }
25.192982
81
0.442897
[ "BSD-3-Clause" ]
tammylotter/NExpect
src/NExpect.Tests/DanglingPrepositions/A.cs
1,438
C#
using System; using System.Collections.Generic; namespace WebApi.Models { public partial class Scientist { public int Id { get; set; } public string Name { get; set; } public DateTime DateAdded { get; set; } } }
19.230769
47
0.624
[ "MIT" ]
DaveSkender/angular-seed-dotnet-sql
src/server/WebApi/Models/Scientist.cs
252
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Resources { public static class GetDeploymentAtTenantScope { /// <summary> /// Deployment information. /// API Version: 2020-10-01. /// </summary> public static Task<GetDeploymentAtTenantScopeResult> InvokeAsync(GetDeploymentAtTenantScopeArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetDeploymentAtTenantScopeResult>("azure-native:resources:getDeploymentAtTenantScope", args ?? new GetDeploymentAtTenantScopeArgs(), options.WithVersion()); } public sealed class GetDeploymentAtTenantScopeArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the deployment. /// </summary> [Input("deploymentName", required: true)] public string DeploymentName { get; set; } = null!; public GetDeploymentAtTenantScopeArgs() { } } [OutputType] public sealed class GetDeploymentAtTenantScopeResult { /// <summary> /// The ID of the deployment. /// </summary> public readonly string Id; /// <summary> /// the location of the deployment. /// </summary> public readonly string? Location; /// <summary> /// The name of the deployment. /// </summary> public readonly string Name; /// <summary> /// Deployment properties. /// </summary> public readonly Outputs.DeploymentPropertiesExtendedResponse Properties; /// <summary> /// Deployment tags /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// The type of the deployment. /// </summary> public readonly string Type; [OutputConstructor] private GetDeploymentAtTenantScopeResult( string id, string? location, string name, Outputs.DeploymentPropertiesExtendedResponse properties, ImmutableDictionary<string, string>? tags, string type) { Id = id; Location = location; Name = name; Properties = properties; Tags = tags; Type = type; } } }
29.625
210
0.603759
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Resources/GetDeploymentAtTenantScope.cs
2,607
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MyList")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MyList")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3af3ef9e-22dc-4086-af35-2683f0260c83")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.297297
84
0.745652
[ "MIT" ]
kamentr/University_Exams
MyList/MyList/Properties/AssemblyInfo.cs
1,383
C#
using Dust.ORM.Core.Models; using Dust.ORM.UnitTest; using System; using System.Collections.Generic; using System.Text; using Xunit; using Xunit.Abstractions; namespace Dust.ORM.CoreTest.Models { public class ModelDescriptorTest { private readonly TestLogger Log; public ModelDescriptorTest(ITestOutputHelper output) { Log = new TestLogger(output); } [Theory] [MemberData(nameof(ModelDescriptorElements.ModelDescriptorTestCase), MemberType = typeof(ModelDescriptorElements))] public void ModelCreationTest(DataModel model) { ModelDescriptor descriptor = null; try { descriptor = new ModelDescriptor(model.GetType()); Log.Info(descriptor.ToString()); } catch (Exception e) { Log.Info(e.ToString()); Assert.False(true); } Assert.NotEmpty(descriptor.Props); Assert.Equal(model.GetType(), descriptor.ModelType); } } internal static class DataModelElementsTestCases { public static readonly List<DataModel> ModelTypeTestCase = new List<DataModel> { new TestClass<bool>(), new TestClass<int>(), new TestClass<string>(), new TestClass<DateTime>(), }; } internal class ModelDescriptorElements { public static IEnumerable<object[]> ModelDescriptorTestCase { get { List<object[]> tmp = new List<object[]>(); for (int i = 0; i < DataModelElementsTestCases.ModelTypeTestCase.Count; i++) tmp.Add(new[] { DataModelElementsTestCases.ModelTypeTestCase[i] }); return tmp; } } } }
28.538462
123
0.574663
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Natlink/Dust.ORM
Dust.Orm.CoreTest/Models/ModelDescriptorTest.cs
1,857
C#
 namespace GCBM.tools { partial class frmManageApp { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmManageApp)); this.btnListApp = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.btnPackageApp = new System.Windows.Forms.Button(); this.btnInstallApp = new System.Windows.Forms.Button(); this.btnRemoveApp = new System.Windows.Forms.Button(); this.dgvAppList = new System.Windows.Forms.DataGridView(); this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components); this.fbd = new System.Windows.Forms.FolderBrowserDialog(); ((System.ComponentModel.ISupportInitialize)(this.dgvAppList)).BeginInit(); this.SuspendLayout(); // // btnListApp // this.btnListApp.Image = global::GCBM.Properties.Resources.open_folder_32; this.btnListApp.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnListApp.Location = new System.Drawing.Point(12, 241); this.btnListApp.Name = "btnListApp"; this.btnListApp.Size = new System.Drawing.Size(120, 45); this.btnListApp.TabIndex = 19; this.btnListApp.Text = "Listar APP\'s"; this.btnListApp.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnListApp.UseVisualStyleBackColor = true; this.btnListApp.Click += new System.EventHandler(this.btnListApp_Click); // // btnClose // this.btnClose.Image = global::GCBM.Properties.Resources.cancel_32; this.btnClose.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnClose.Location = new System.Drawing.Point(516, 241); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(120, 45); this.btnClose.TabIndex = 18; this.btnClose.Text = "Fechar"; this.btnClose.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // btnPackageApp // this.btnPackageApp.Image = global::GCBM.Properties.Resources.compact_file_32; this.btnPackageApp.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnPackageApp.Location = new System.Drawing.Point(390, 241); this.btnPackageApp.Name = "btnPackageApp"; this.btnPackageApp.Size = new System.Drawing.Size(120, 45); this.btnPackageApp.TabIndex = 17; this.btnPackageApp.Text = "Empacotar APP"; this.btnPackageApp.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnPackageApp.UseVisualStyleBackColor = true; this.btnPackageApp.Click += new System.EventHandler(this.btnPackageApp_Click); // // btnInstallApp // this.btnInstallApp.Enabled = false; this.btnInstallApp.Image = global::GCBM.Properties.Resources.install_software_32; this.btnInstallApp.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnInstallApp.Location = new System.Drawing.Point(138, 241); this.btnInstallApp.Name = "btnInstallApp"; this.btnInstallApp.Size = new System.Drawing.Size(120, 45); this.btnInstallApp.TabIndex = 16; this.btnInstallApp.Text = "Instalar APP"; this.btnInstallApp.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnInstallApp.UseVisualStyleBackColor = true; this.btnInstallApp.Click += new System.EventHandler(this.btnInstallApp_Click); // // btnRemoveApp // this.btnRemoveApp.Image = global::GCBM.Properties.Resources.eraser_32; this.btnRemoveApp.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.btnRemoveApp.Location = new System.Drawing.Point(264, 241); this.btnRemoveApp.Name = "btnRemoveApp"; this.btnRemoveApp.Size = new System.Drawing.Size(120, 45); this.btnRemoveApp.TabIndex = 15; this.btnRemoveApp.Text = "Apagar APP"; this.btnRemoveApp.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; this.btnRemoveApp.UseVisualStyleBackColor = true; this.btnRemoveApp.Click += new System.EventHandler(this.btnRemoveApp_Click); // // dgvAppList // this.dgvAppList.AllowUserToAddRows = false; this.dgvAppList.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.dgvAppList.BackgroundColor = System.Drawing.Color.White; this.dgvAppList.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgvAppList.Location = new System.Drawing.Point(12, 12); this.dgvAppList.MultiSelect = false; this.dgvAppList.Name = "dgvAppList"; this.dgvAppList.ReadOnly = true; this.dgvAppList.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.dgvAppList.Size = new System.Drawing.Size(624, 223); this.dgvAppList.TabIndex = 14; // // notifyIcon // this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon.Icon"))); this.notifyIcon.Visible = true; // // fbd // this.fbd.Description = "Selecione a pasta com os app\'s:"; this.fbd.RootFolder = System.Environment.SpecialFolder.MyComputer; this.fbd.ShowNewFolderButton = false; // // frmManageApp // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(647, 292); this.Controls.Add(this.btnListApp); this.Controls.Add(this.btnClose); this.Controls.Add(this.btnPackageApp); this.Controls.Add(this.btnInstallApp); this.Controls.Add(this.btnRemoveApp); this.Controls.Add(this.dgvAppList); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmManageApp"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Gerenciar APP\'s"; ((System.ComponentModel.ISupportInitialize)(this.dgvAppList)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnListApp; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Button btnPackageApp; private System.Windows.Forms.Button btnInstallApp; private System.Windows.Forms.Button btnRemoveApp; private System.Windows.Forms.DataGridView dgvAppList; private System.Windows.Forms.NotifyIcon notifyIcon; private System.Windows.Forms.FolderBrowserDialog fbd; } }
51.05814
144
0.633341
[ "MIT" ]
AxionDrak/GameCube-Backup-Manager
GCBM/tools/frmManageApp.Designer.cs
8,784
C#
using System; using System.Configuration; using System.Linq; using System.Net; using System.Net.Sockets; using Topshelf; namespace EventStoreWinServiceWrapper { class Program { public static void Main() { var configuration = (EventStoreServiceConfiguration)ConfigurationManager.GetSection("eventStore"); HostFactory.Run(x => { x.RunAsLocalSystem(); x.StartAutomatically(); x.EnableShutdown(); x.EnableServiceRecovery(c => c.RestartService(1)); x.Service<ServiceWrapper>(s => { s.ConstructUsing(name => new ServiceWrapper(configuration)); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.SetDescription("EventStoreServiceWrapper"); x.SetDisplayName("EventStoreServiceWrapper"); x.SetServiceName("EventStoreServiceWrapper"); }); } } }
28.026316
110
0.551174
[ "MIT" ]
mastoj/EventStoreWinServiceWrapper
src/EventStoreWinServiceWrapper/Program.cs
1,067
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Gildemeister.Cliente360.Transport; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using NLog; namespace Gildemeister.Cliente360.WebAPI.Controllers { [Produces("application/json")] [Route("api/Logger")] //[Authorize] public class LoggerController : Controller { private static NLogManager _logger = new NLogManager(LogManager.GetCurrentClassLogger()); // GET: api/Logger [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET: api/Logger/5 [HttpGet("{id}", Name = "Get")] public string Get(int id) { return "value"; } // POST: api/Logger [HttpPost] public void Post([FromBody] LogDTO log) { if (log.Level == "Error") { Exception ex = new ApplicationException(log.Message + ". " + log.StackTrace); _logger.LogError(ex); } if (log.Level == "Trace") { _logger.LogTrace(log.Message); } } // PUT: api/Logger/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE: api/ApiWithActions/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
24.380952
97
0.53125
[ "MIT" ]
pSharpX/customer360-api
src/Gildemeister.Cliente360.WebAPI/Controllers/LoggerController.cs
1,538
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IUpdatePermission.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.Security.Permissions { using Kephas.Security.Authorization; using Kephas.Security.Permissions.AttributedModel; /// <summary> /// Declares the 'update' permission. /// The content of the data can be updated. May be intersected with other permissions to further restrict specific sections. /// </summary> [PermissionInfo(DataPermissionTokenName.Update, Scoping.Type | Scoping.Instance)] public interface IUpdatePermission : IReadPermission { } }
47.714286
128
0.560878
[ "MIT" ]
kephas-software/kephas
src/Kephas.Data/Security/Permissions/IUpdatePermission.cs
1,004
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 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 System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Xml; using XenAdmin.Core; using XenAdmin.Network; using XenAPI; using System.Globalization; namespace XenAdmin.Actions { /// <summary> /// Ask the server for a list of IQNs on a particular iSCSI target. /// </summary> public class ISCSIPopulateIQNsAction : AsyncAction { private readonly string targetHost; private readonly UInt16 targetPort; private readonly string chapUsername; private readonly string chapPassword; private IScsiIqnInfo[] _iqns; /// <summary> /// Will be null if the scan has not yet successfully returned. /// </summary> public IScsiIqnInfo[] IQNs { get { return _iqns; } } public ISCSIPopulateIQNsAction(IXenConnection connection, string targetHost, UInt16 targetPort, string chapUsername, string chapPassword) : base(connection, string.Format(Messages.ACTION_ISCSI_IQN_SCANNING, targetHost), null, true) { this.targetHost = targetHost; this.targetPort = targetPort; this.chapUsername = chapUsername; this.chapPassword = chapPassword; } public class NoIQNsFoundException : Exception { private readonly string host; public NoIQNsFoundException(string host) { this.host = host; } public override string Message { get { return String.Format(Messages.NEWSR_NO_IQNS_FOUND, host); } } } private const string UriPrefix = "http://"; private string ParseIPAddress(string address) { Uri url; if (Uri.TryCreate(string.Format("{0}{1}", UriPrefix, address), UriKind.Absolute, out url)) { IPAddress ip; if (IPAddress.TryParse(url.Host, out ip)) { if (ip.AddressFamily == AddressFamily.InterNetworkV6) return "[" + ip + "]"; return ip.ToString(); } } return address; } protected override void Run() { Pool pool = Helpers.GetPoolOfOne(Connection); if (pool == null) throw new Failure(Failure.INTERNAL_ERROR, Messages.POOL_GONE); Dictionary<string, string> settings = new Dictionary<string, string>(); settings["target"] = targetHost; settings["port"] = targetPort.ToString(CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(this.chapUsername)) { settings["chapuser"] = this.chapUsername; settings["chappassword"] = this.chapPassword; } try { // Perform a create with some missing params: should fail with the error // containing the list of SRs on the filer. RelatedTask = XenAPI.SR.async_create(Session, pool.master, settings, 0, Helpers.GuiTempObjectPrefix, Messages.ISCSI_SHOULD_NO_BE_CREATED, XenAPI.SR.SRTypes.lvmoiscsi.ToString(), "user", true, new Dictionary<string, string>()); this.PollToCompletion(); // Create should always fail and never get here throw new InvalidOperationException(Messages.ISCSI_FAIL); } catch (XenAPI.Failure exn) { if (exn.ErrorDescription.Count < 1) throw new BadServerResponse(targetHost); // We expect an SR_BACKEND_FAILURE_96 error, with a message from // xapi, stdout, and then stderr. // stderr will be an XML-encoded description of the iSCSI IQNs. if (exn.ErrorDescription[0] != "SR_BACKEND_FAILURE_96") throw; // We want a custom error if the server returns no aggregates. if (exn.ErrorDescription.Count < 4 || exn.ErrorDescription[3].Length == 0) throw new NoIQNsFoundException(targetHost); XmlDocument doc = new XmlDocument(); List<IScsiIqnInfo> results = new List<IScsiIqnInfo>(); try { doc.LoadXml(exn.ErrorDescription[3].ToString()); foreach (XmlNode targetListNode in doc.GetElementsByTagName("iscsi-target-iqns")) { foreach (XmlNode targetNode in targetListNode.ChildNodes) { int index = -1; string address = null; UInt16 port = Util.DEFAULT_ISCSI_PORT; string targetIQN = null; foreach (XmlNode infoNode in targetNode.ChildNodes) { if (infoNode.Name.ToLowerInvariant() == "index") { index = int.Parse(infoNode.InnerText, System.Globalization.CultureInfo.InvariantCulture); } else if (infoNode.Name.ToLowerInvariant() == "ipaddress") { string addr = infoNode.InnerText.Trim(); address = ParseIPAddress(addr); } else if (infoNode.Name.ToLowerInvariant() == "port") { port = UInt16.Parse(infoNode.InnerText, System.Globalization.CultureInfo.InvariantCulture); } else if (infoNode.Name.ToLowerInvariant() == "targetiqn") { targetIQN = infoNode.InnerText.Trim(); } } results.Add(new IScsiIqnInfo(index, targetIQN, address, port)); } } results.Sort(); _iqns = results.ToArray(); } catch { throw new BadServerResponse(targetHost); } if (_iqns.Length < 1) throw new NoIQNsFoundException(targetHost); } } } public struct IScsiIqnInfo : IComparable<IScsiIqnInfo>, IEquatable<IScsiIqnInfo> { public readonly int Index; /// <summary> /// May be null. /// </summary> public readonly string TargetIQN; /// <summary> /// May be null. /// </summary> public readonly string IpAddress; public readonly UInt16 Port; public IScsiIqnInfo(int index, string targetIQN, string ipAddress, UInt16 port) { Index = index; TargetIQN = targetIQN; IpAddress = ipAddress; Port = port; } public int CompareTo(IScsiIqnInfo other) { // Special case: * goes at the end if (TargetIQN == "*" && other.TargetIQN != "*") return 1; if (other.TargetIQN == "*" && TargetIQN != "*") return -1; // Sort by the TargetIQN (not the Index: see CA-40066) return StringUtility.NaturalCompare(TargetIQN, other.TargetIQN); } public bool Equals(IScsiIqnInfo other) { return this.Index == other.Index && this.TargetIQN == other.TargetIQN && this.IpAddress == other.IpAddress && this.Port == other.Port; } } }
39.569106
128
0.524348
[ "BSD-2-Clause" ]
GaborApatiNagy/xenadmin
XenModel/Actions/SR/ISCSIPopulateIQNsAction.cs
9,736
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; using System.Runtime.CompilerServices; using UnityEngine.Events; public class flightcontol : NetworkBehaviour { public float rotateSpeed = 3f; // Use this for initialization void Start() { if (isLocalPlayer) { GameObject.Find("Camera").GetComponent<netCameraFollow>().target = this.gameObject; } } // Update is called once per frame void Update() { this.LocalMove(); } void LocalMove() { if (isLocalPlayer) { Vector3 v = Vector3.zero; if (Input.GetKey(KeyCode.W)) { v = new Vector3(0, v.y + this.rotateSpeed * Time.deltaTime * 5, 0); } if (Input.GetKey(KeyCode.S)) { v = new Vector3(0, v.y - this.rotateSpeed * Time.deltaTime * 5, 0); } if (Input.GetKey(KeyCode.A)) { v = new Vector3(0, v.y, -this.rotateSpeed * Time.deltaTime * 20); } if (Input.GetKey(KeyCode.D)) { v = new Vector3(0, v.y, +this.rotateSpeed * Time.deltaTime * 20); } if (Input.GetKey(KeyCode.Q)) { v = new Vector3(+this.rotateSpeed * Time.deltaTime * 20, v.y, v.z); } if (Input.GetKey(KeyCode.E)) { v = new Vector3(-this.rotateSpeed * Time.deltaTime * 20, v.y, v.z); } this.CmdRemoteMove(v); } } [Command] void CmdRemoteMove(Vector3 v) { this.transform.Translate(new Vector3(0, 0, v.y)); this.transform.Rotate(new Vector3(0, v.z, v.x)); } }
25.577465
95
0.514868
[ "BSD-2-Clause" ]
PretDB/CrazyBooble
Assets/script/control/flightcontol.cs
1,818
C#
namespace Alex.Blocks.Minecraft { public class LilyPad : Block { public LilyPad() : base() { Solid = true; Transparent = true; IsReplacible = false; IsFullBlock = false; IsFullCube = false; BlockMaterial = Material.Plants.Clone().SetTranslucent(); } } }
16.588235
60
0.659574
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
lvyitian1/Alex
src/Alex/Blocks/Minecraft/LilyPad.cs
282
C#
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2014 Tasharen Entertainment //---------------------------------------------- using UnityEngine; using UnityEngine.UI; /// <summary> /// Simple script that lets you localize a UIWidget. /// </summary> namespace Hugula { [ExecuteInEditMode] [RequireComponent (typeof (MaskableGraphic))] public class UGUILocalize : MonoBehaviour { /// <summary> /// Localization key. /// </summary> public string key; [Tooltip("从Luafunction中获取值")] public bool luaFunction = true; public static System.Func<string,string> LocaltionFun; /// <summary> /// Manually change the value of whatever the localization component is attached to. /// </summary> public string value { set { if (!string.IsNullOrEmpty (value)) { MaskableGraphic w = GetComponent<MaskableGraphic> (); //Image Text lbl = w as Text; Image sp = w as Image; if (lbl != null) { // If this is a label used by input, we should localize its default value instead //UIInput input = NGUITools.FindInParents<UIInput>(lbl.gameObject); //if (input != null && input.label == lbl) input.defaultText = value; //else lbl.text = value; } else if (sp != null) { sp.sprite.name = value; } } } } bool mStarted = false; /// <summary> /// Localize the widget on enable, but only if it has been started already. /// </summary> void OnEnable () { #if UNITY_EDITOR if (!Application.isPlaying) return; #endif if (mStarted) OnLocalize (); } /// <summary> /// Localize the widget on start. /// </summary> void Start () { #if UNITY_EDITOR if (!Application.isPlaying) return; #endif mStarted = true; OnLocalize (); } /// <summary> /// This function is called by the Localization manager via a broadcast SendMessage. /// </summary> void OnLocalize () { // If no localization key has been specified, use the label's text as the key if (string.IsNullOrEmpty (key)) { Text lbl = GetComponent<Text> (); if (lbl != null) key = lbl.text; } // If we still don't have a key, leave the value as blank if (!string.IsNullOrEmpty (key)) { if(luaFunction && LocaltionFun!=null) { value = LocaltionFun.Invoke(key); } else { value = Localization.Get (key); } } } } }
30.09434
106
0.45674
[ "MIT" ]
tenvick/hugula
Client/Assets/Hugula/Language/UGUILocalize.cs
3,201
C#
using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; namespace MrMeeseeks.ResXTranslationCombinator.Translation { internal interface ITranslator { bool TranslationsShouldBeCached { get; } Task<HashSet<CultureInfo>> GetSupportedCultureInfos(); Task<string[]> Translate( string[] sourceTexts, CultureInfo targetCulture); } }
28.133333
62
0.7109
[ "MIT" ]
Yeah69/MrMeeseeks.ResXTranslationCombinator
Main/Translation/ITranslator.cs
422
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OrmTest { public partial class NewUnitTest { public static void Ado() { var task1 = Db.Ado.GetScalarAsync("select 1"); task1.Wait(); UValidate.Check(1, task1.Result, "ado"); var task2 = Db.Ado.GetIntAsync("select 2"); task2.Wait(); UValidate.Check(2, task2.Result, "ado"); var task3 = Db.Ado.GetLongAsync("select 3"); task3.Wait(); UValidate.Check(3, task3.Result, "ado"); var task4 = Db.Ado.GetDataTableAsync("select 4 as id"); task4.Wait(); UValidate.Check(4, task4.Result.Rows[0]["id"], "ado"); var task5 = Db.Ado.GetInt("select @id as id",new { id=5}); UValidate.Check(5, task5, "ado"); var task6 = Db.Ado.SqlQuery<dynamic>("select @id as id", new { id = 5 }); UValidate.Check(5, task6[0].id, "ado"); var task7 = Db.Ado.SqlQueryAsync<dynamic>("select @id as id", new { id = 7 }); task7.Wait(); UValidate.Check(7, task7.Result[0].id, "ado"); var task8 = Db.Ado.SqlQueryAsync<dynamic>("select 8 as id"); task8.Wait(); UValidate.Check(8, task8.Result[0].id, "ado"); var task9=Db.Ado.SqlQuery<Order, OrderItem>(@"select * from ""order"";select * from OrderDetail"); var task10 = Db.Ado.SqlQueryAsync<Order, OrderItem>(@"select * from ""order"";select * from OrderDetail"); task10.Wait(); } } }
28.87931
118
0.551045
[ "Apache-2.0" ]
1093439315/SqlSugar
Src/Asp.Net/PgSqlTest/UnitTest/UAdo.cs
1,677
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Acme.BookStore.Migrations { public partial class Created_Book_Entity : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropPrimaryKey( name: "PK_Books", table: "Books"); migrationBuilder.RenameTable( name: "Books", newName: "AppBooks"); migrationBuilder.AlterColumn<string>( name: "Name", table: "AppBooks", type: "nvarchar(128)", maxLength: 128, nullable: false, defaultValue: "", oldClrType: typeof(string), oldType: "nvarchar(max)", oldNullable: true); migrationBuilder.AddPrimaryKey( name: "PK_AppBooks", table: "AppBooks", column: "Id"); migrationBuilder.CreateIndex( name: "IX_AppBooks_AuthorId", table: "AppBooks", column: "AuthorId"); migrationBuilder.AddForeignKey( name: "FK_AppBooks_Authors_AuthorId", table: "AppBooks", column: "AuthorId", principalTable: "Authors", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_AppBooks_Authors_AuthorId", table: "AppBooks"); migrationBuilder.DropPrimaryKey( name: "PK_AppBooks", table: "AppBooks"); migrationBuilder.DropIndex( name: "IX_AppBooks_AuthorId", table: "AppBooks"); migrationBuilder.RenameTable( name: "AppBooks", newName: "Books"); migrationBuilder.AlterColumn<string>( name: "Name", table: "Books", type: "nvarchar(max)", nullable: true, oldClrType: typeof(string), oldType: "nvarchar(128)", oldMaxLength: 128); migrationBuilder.AddPrimaryKey( name: "PK_Books", table: "Books", column: "Id"); } } }
30.790123
71
0.495589
[ "MIT" ]
271943794/abp-samples
BookStore-Blazor-EfCore/src/Acme.BookStore.EntityFrameworkCore/Migrations/20210712064054_Created_Book_Entity.cs
2,496
C#
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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 UnityEngine; using UnityEngine.UI; using Spine; namespace Spine.Unity { [ExecuteInEditMode, RequireComponent(typeof(CanvasRenderer), typeof(RectTransform)), DisallowMultipleComponent] [AddComponentMenu("Spine/SkeletonGraphic (Unity UI Canvas)")] public class SkeletonGraphic : MaskableGraphic, ISkeletonComponent, IAnimationStateComponent, ISkeletonAnimation, IHasSkeletonDataAsset { #region Inspector public SkeletonDataAsset skeletonDataAsset; public SkeletonDataAsset SkeletonDataAsset { get { return skeletonDataAsset; } } [SpineSkin(dataField:"skeletonDataAsset")] public string initialSkinName = "default"; public bool initialFlipX, initialFlipY; [SpineAnimation(dataField:"skeletonDataAsset")] public string startingAnimation; public bool startingLoop; public float timeScale = 1f; public bool freeze; public bool unscaledTime; #if UNITY_EDITOR protected override void OnValidate () { // This handles Scene View preview. base.OnValidate (); if (this.IsValid) { if (skeletonDataAsset == null) { Clear(); startingAnimation = ""; } else if (skeletonDataAsset.GetSkeletonData(true) != skeleton.data) { Clear(); Initialize(true); startingAnimation = ""; if (skeletonDataAsset.atlasAssets.Length > 1 || skeletonDataAsset.atlasAssets[0].MaterialCount > 1) Debug.LogError("Unity UI does not support multiple textures per Renderer. Your skeleton will not be rendered correctly. Recommend using SkeletonAnimation instead. This requires the use of a Screen space camera canvas."); } else { if (freeze) return; if (!string.IsNullOrEmpty(initialSkinName)) { var skin = skeleton.data.FindSkin(initialSkinName); if (skin != null) { if (skin == skeleton.data.defaultSkin) skeleton.SetSkin((Skin)null); else skeleton.SetSkin(skin); } } // Only provide visual feedback to inspector changes in Unity Editor Edit mode. if (!Application.isPlaying) { skeleton.scaleX = this.initialFlipX ? -1 : 1; skeleton.scaleY = this.initialFlipY ? -1 : 1; skeleton.SetToSetupPose(); if (!string.IsNullOrEmpty(startingAnimation)) skeleton.PoseWithAnimation(startingAnimation, 0f, false); } } } else { if (skeletonDataAsset != null) Initialize(true); } } protected override void Reset () { base.Reset(); if (material == null || material.shader != Shader.Find("Spine/SkeletonGraphic (Premultiply Alpha)")) Debug.LogWarning("SkeletonGraphic works best with the SkeletonGraphic material."); } #endif #endregion #region Runtime Instantiation /// <summary>Create a new GameObject with a SkeletonGraphic component.</summary> /// <param name="material">Material for the canvas renderer to use. Usually, the default SkeletonGraphic material will work.</param> public static SkeletonGraphic NewSkeletonGraphicGameObject (SkeletonDataAsset skeletonDataAsset, Transform parent, Material material) { var sg = SkeletonGraphic.AddSkeletonGraphicComponent(new GameObject("New Spine GameObject"), skeletonDataAsset, material); if (parent != null) sg.transform.SetParent(parent, false); return sg; } /// <summary>Add a SkeletonGraphic component to a GameObject.</summary> /// <param name="material">Material for the canvas renderer to use. Usually, the default SkeletonGraphic material will work.</param> public static SkeletonGraphic AddSkeletonGraphicComponent (GameObject gameObject, SkeletonDataAsset skeletonDataAsset, Material material) { var c = gameObject.AddComponent<SkeletonGraphic>(); if (skeletonDataAsset != null) { c.material = material; c.skeletonDataAsset = skeletonDataAsset; c.Initialize(false); } return c; } #endregion #region Internals // This is used by the UI system to determine what to put in the MaterialPropertyBlock. Texture overrideTexture; public Texture OverrideTexture { get { return overrideTexture; } set { overrideTexture = value; canvasRenderer.SetTexture(this.mainTexture); // Refresh canvasRenderer's texture. Make sure it handles null. } } public override Texture mainTexture { get { // Fail loudly when incorrectly set up. if (overrideTexture != null) return overrideTexture; return skeletonDataAsset == null ? null : skeletonDataAsset.atlasAssets[0].PrimaryMaterial.mainTexture; } } protected override void Awake () { base.Awake (); if (!this.IsValid) { Initialize(false); Rebuild(CanvasUpdate.PreRender); } } public override void Rebuild (CanvasUpdate update) { base.Rebuild(update); if (canvasRenderer.cull) return; if (update == CanvasUpdate.PreRender) UpdateMesh(); } public virtual void Update () { if (freeze) return; Update(unscaledTime ? Time.unscaledDeltaTime : Time.deltaTime); } public virtual void Update (float deltaTime) { if (!this.IsValid) return; deltaTime *= timeScale; skeleton.Update(deltaTime); state.Update(deltaTime); state.Apply(skeleton); if (UpdateLocal != null) UpdateLocal(this); skeleton.UpdateWorldTransform(); if (UpdateWorld != null) { UpdateWorld(this); skeleton.UpdateWorldTransform(); } if (UpdateComplete != null) UpdateComplete(this); } public void LateUpdate () { if (freeze) return; //this.SetVerticesDirty(); // Which is better? UpdateMesh(); } #endregion #region API protected Skeleton skeleton; public Skeleton Skeleton { get { return skeleton; } internal set { skeleton = value; } } public SkeletonData SkeletonData { get { return skeleton == null ? null : skeleton.data; } } public bool IsValid { get { return skeleton != null; } } protected Spine.AnimationState state; public Spine.AnimationState AnimationState { get { return state; } } [SerializeField] protected Spine.Unity.MeshGenerator meshGenerator = new MeshGenerator(); public Spine.Unity.MeshGenerator MeshGenerator { get { return this.meshGenerator; } } DoubleBuffered<Spine.Unity.MeshRendererBuffers.SmartMesh> meshBuffers; SkeletonRendererInstruction currentInstructions = new SkeletonRendererInstruction(); public Mesh GetLastMesh () { return meshBuffers.GetCurrent().mesh; } public event UpdateBonesDelegate UpdateLocal; public event UpdateBonesDelegate UpdateWorld; public event UpdateBonesDelegate UpdateComplete; /// <summary> Occurs after the vertex data populated every frame, before the vertices are pushed into the mesh.</summary> public event Spine.Unity.MeshGeneratorDelegate OnPostProcessVertices; public void Clear () { skeleton = null; canvasRenderer.Clear(); } public void Initialize (bool overwrite) { if (this.IsValid && !overwrite) return; // Make sure none of the stuff is null if (this.skeletonDataAsset == null) return; var skeletonData = this.skeletonDataAsset.GetSkeletonData(false); if (skeletonData == null) return; if (skeletonDataAsset.atlasAssets.Length <= 0 || skeletonDataAsset.atlasAssets[0].MaterialCount <= 0) return; this.state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData()); if (state == null) { Clear(); return; } this.skeleton = new Skeleton(skeletonData) { scaleX = this.initialFlipX ? -1 : 1, scaleY = this.initialFlipY ? -1 : 1 }; meshBuffers = new DoubleBuffered<MeshRendererBuffers.SmartMesh>(); canvasRenderer.SetTexture(this.mainTexture); // Needed for overwriting initializations. // Set the initial Skin and Animation if (!string.IsNullOrEmpty(initialSkinName)) skeleton.SetSkin(initialSkinName); if (!string.IsNullOrEmpty(startingAnimation)) { var animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(startingAnimation); if (animationObject != null) { animationObject.PoseSkeleton(skeleton, 0f); skeleton.UpdateWorldTransform(); #if UNITY_EDITOR if (Application.isPlaying) { #endif // Make this block not run in Unity Editor edit mode. state.SetAnimation(0, animationObject, startingLoop); #if UNITY_EDITOR } #endif } } } public void UpdateMesh () { if (!this.IsValid) return; skeleton.SetColor(this.color); var smartMesh = meshBuffers.GetNext(); var currentInstructions = this.currentInstructions; MeshGenerator.GenerateSingleSubmeshInstruction(currentInstructions, skeleton, this.material); bool updateTriangles = SkeletonRendererInstruction.GeometryNotEqual(currentInstructions, smartMesh.instructionUsed); meshGenerator.Begin(); if (currentInstructions.hasActiveClipping) { meshGenerator.AddSubmesh(currentInstructions.submeshInstructions.Items[0], updateTriangles); } else { meshGenerator.BuildMeshWithArrays(currentInstructions, updateTriangles); } if (canvas != null) meshGenerator.ScaleVertexData(canvas.referencePixelsPerUnit); if (OnPostProcessVertices != null) OnPostProcessVertices.Invoke(this.meshGenerator.Buffers); var mesh = smartMesh.mesh; meshGenerator.FillVertexData(mesh); if (updateTriangles) meshGenerator.FillTrianglesSingle(mesh); meshGenerator.FillLateVertexData(mesh); canvasRenderer.SetMesh(mesh); smartMesh.instructionUsed.Set(currentInstructions); //this.UpdateMaterial(); // TODO: This allocates memory. } #endregion } }
36.888525
226
0.724202
[ "MIT" ]
lantis-of-china/UnityFramework
ClientFramework/QiPai/Assets/OtherCompoments/Spine/Runtime/spine-unity/Modules/SkeletonGraphic/SkeletonGraphic.cs
11,251
C#
using Microsoft.AppCenter.Ingestion; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Microsoft.AppCenter.Test.Windows.Ingestion { [TestClass] public class IngestionExceptionTest { /// <summary> /// Validate that exception message is saving /// </summary> [TestMethod] public void CheckMessageError() { string exceptionMessage = "Test exception message"; IngestionException ingException = new IngestionException(exceptionMessage); Assert.AreEqual(exceptionMessage, ingException.Message); } /// <summary> /// Validate that exception is saving as an internal exception /// </summary> [TestMethod] public void CheckInternalError() { string exceptionMessage = "Test exception message"; Exception internalException = new Exception(exceptionMessage); IngestionException ingException = new IngestionException(internalException); Assert.AreSame(internalException, ingException.InnerException); Assert.AreEqual(exceptionMessage, ingException.InnerException.Message); } } }
32.972973
88
0.662295
[ "MIT" ]
ManjuBP/.net
Tests/Microsoft.AppCenter.Test.Windows/Ingestion/IngestionExceptionTest.cs
1,222
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace QuantConnect.Brokerages.InteractiveBrokers.Client { /// <summary> /// Order Time in Force Values /// </summary> public static class TimeInForce { /// <summary> /// Day /// </summary> public const string Day = "DAY"; /// <summary> /// Good Till Cancel /// </summary> public const string GoodTillCancel = "GTC"; /// <summary> /// You can set the time in force for MARKET or LIMIT orders as IOC. This dictates that any portion of the order not executed immediately after it becomes available on the market will be cancelled. /// </summary> public const string ImmediateOrCancel = "IOC"; /// <summary> /// Setting FOK as the time in force dictates that the entire order must execute immediately or be canceled. /// </summary> public const string FillOrKill = "FOK"; /// <summary> /// Good Till Date /// </summary> public const string GoodTillDate = "GTD"; /// <summary> /// Market On Open /// </summary> public const string MarketOnOpen = "OPG"; /// <summary> /// Undefined /// </summary> public const string Undefined = ""; } }
33.881356
205
0.631816
[ "Apache-2.0" ]
AENotFound/Lean
Brokerages/InteractiveBrokers/Client/TimeInForce.cs
2,001
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using SMLimitless.Extensions; using SMLimitless.Interfaces; using SMLimitless.Physics; namespace SMLimitless.Collections { /// <summary> /// Represents a single cell in a <see cref="SparseCellGrid{T}" /> instance. /// </summary> /// <typeparam name="T"> /// A type implementing the <see cref="IPositionable2" /> interface. /// </typeparam> public sealed class SparseCell<T> where T : IPositionable2 { /// <summary> /// A collection of all the items intersecting this cell. /// </summary> private HashSet<T> cellItems = new HashSet<T>(); /// <summary> /// The two-dimensional, zero-based index of this cell. /// </summary> private Point cellNumber; /// <summary> /// The size of this cell. /// </summary> private Vector2 cellSize; /// <summary> /// Gets the bounding rectangle enclosing this cell. /// </summary> public BoundingRectangle Bounds { get; } /// <summary> /// Gets a value indicating whether this cell has no items. /// </summary> public bool IsEmpty => cellItems.Count == 0; /// <summary> /// Gets a collection of all the items intersecting this cell. /// </summary> public HashSet<T> Items => cellItems; /// <summary> /// Initializes a new instance of the <see cref="SparseCell{T}" /> class. /// </summary> /// <param name="cCellSize">The size of this cell.</param> /// <param name="cCellNumber"> /// The two-dimensional, zero-based index of this cell. /// </param> public SparseCell(Vector2 cCellSize, Point cCellNumber) { if (cCellSize.IsNaN() || cCellSize.X <= 0f || cCellSize.Y <= 0f) { throw new ArgumentException("The sparse cell constructor received a cell size that is not a number or has zero or negative area.", nameof(cCellSize)); } // cCellNumber doesn't need to be validated - all int pairs are valid cellSize = cCellSize; cellNumber = cCellNumber; Bounds = CreateBounds(); } /// <summary> /// Initializes a new instance of the <see cref="SparseCell{T}" /> class. /// </summary> /// <param name="items"> /// A collection of items to place within this cell. /// </param> /// <param name="cCellSize">The size of this cell.</param> /// <param name="cCellNumber"> /// The two-dimensional, zero-based index of this cell. /// </param> public SparseCell(IEnumerable<T> items, Vector2 cCellSize, Point cCellNumber) { if (items == null || !items.Any()) { throw new ArgumentException("The sparse cell constructor received a collection of items that was null or empty.", nameof(items)); } if (cCellSize.X <= 0f || cCellSize.Y <= 0f || cCellSize.IsNaN()) { throw new ArgumentException("The sparse cell constructor received a cell size that is not a number or has zero or negative area.", nameof(cCellSize)); } cellItems = new HashSet<T>(items); cellSize = cCellSize; cellNumber = cCellNumber; Bounds = CreateBounds(); } /// <summary> /// Adds an item to this cell. /// </summary> /// <param name="item">The item to add.</param> public void Add(T item) { if (!ItemIntersectsCell(item)) { throw new ArgumentOutOfRangeException(nameof(item.Position), $"When trying to add an item to a sparse cell, the item was found to be outside of the cell. Please validate the positioning of the item or which cell it should go in. Expected range: from {new Vector2(Bounds.Top, Bounds.Left)} to {new Vector2(Bounds.Bottom, Bounds.Right)} (cell {cellNumber.X},{cellNumber.Y}). Item's actual properties: position {item.Position}, size {item.Size}"); } cellItems.Add(item); } /// <summary> /// Returns a value indicating whether a given item intersects this cell. /// </summary> /// <param name="item">The item to check for intersection.</param> /// <returns> /// True if the item intersects this cell (including a tangent, /// edges-only intersection), False if it does not. /// </returns> public bool ItemIntersectsCell(T item) { if (item == null) { throw new ArgumentNullException(nameof(item), "When attempting to determine if an item falls within a given sparse grid cell, the item provided was a null reference. Please ensure a null reference isn't passed to this method."); } if (item.Size == Vector2.Zero || item.Size.IsNaN()) { return false; } return new BoundingRectangle(item.Position, item.Position + item.Size).IntersectsIncludingEdges(Bounds); } /// <summary> /// Removes an item from this cell. /// </summary> /// <param name="item">The item to remove.</param> public bool Remove(T item) { return cellItems.Remove(item); } /// <summary> /// Creates the bounding rectangle of this cell. /// </summary> /// <returns>The bounding rectangle of this cell.</returns> private BoundingRectangle CreateBounds() { // seems rather wasteful to keep constructing the rectangle all the time Vector2 cellPosition = new Vector2(cellNumber.X * cellSize.X, cellNumber.Y * cellSize.Y); return new BoundingRectangle(cellPosition.X, cellPosition.Y, cellSize.X, cellSize.Y); } } }
36.359155
482
0.678094
[ "MIT" ]
smldev/smlimitless
MonoGame/SMLimitless/SMLimitless/Collections/SparseCell.cs
5,165
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace Microsoft.Teams.App.KronosWfc.Models.ResponseEntities.JobAssignment { [XmlRoot] public class Response { [XmlElement("JobAssignment")] public JobAssignment JobAssign { get; set; } [XmlAttribute] public string Status { get; set; } [XmlAttribute] public string Action { get; set; } public Error Error { get; set; } } public class JobAssignment { [XmlElement("PrimaryLaborAccounts")] public PrimaryLaborAccounts PrimaryLaborAccList { get; set; } [XmlElement("BaseWageRates")] public BaseWageRates BaseWageRats { get; set; } [XmlElement("Period")] public Period Perd { get; set; } [XmlElement("JobAssignmentDetailsData")] public JobAssignmentDetailsData jobAssignDetData { get; set; } } public class JobAssignmentDetailsData { [XmlElement("JobAssignmentDetails")] public JobAssignmentDetails JobAssignDet { get; set; } } public class JobAssignmentDetails { [XmlAttribute] public string PayRuleName { get; set; } [XmlAttribute] public string SupervisorPersonNumber { get; set; } [XmlAttribute] public string SupervisorName { get; set; } [XmlAttribute] public string TimeZoneName { get; set; } [XmlAttribute] public string BaseWageHourly { get; set; } } public class Period { [XmlElement("TimeFramePeriod")] public TimeFramePeriod TimeFramePerd { get; set; } } public class TimeFramePeriod { [XmlAttribute] public string PeriodDateSpan { get; set; } [XmlAttribute] public string TimeFrameName { get; set; } } public class PrimaryLaborAccounts { [XmlElement("PrimaryLaborAccount")] public PrimaryLaborAccount PrimaryLaborAcc { get; set; } } public class PrimaryLaborAccount { [XmlAttribute] public string EffectiveDate { get; set; } [XmlAttribute] public string ExpirationDate { get; set; } [XmlAttribute] public string OrganizationPath { get; set; } [XmlAttribute] public string LaborAccountName { get; set; } } public class BaseWageRates { [XmlElement("BaseWageRate")] public BaseWageRate[] BaseWageRt { get; set; } } public class BaseWageRate { [XmlAttribute] public string HourlyRate { get; set; } [XmlAttribute] public string EffectiveDate { get; set; } [XmlAttribute] public string ExpirationDate { get; set; } } }
21.70229
77
0.619416
[ "MIT" ]
OfficeDev/Kronos-Workforce-Central-Bot
Microsoft.Teams.App.KronosWfc/Microsoft.Teams.App.KronosWfc.Models/ResponseEntities/JobAssignment/Response.cs
2,845
C#
using AutoMapper; using StudentsFirst.Common.Dtos.Groups; using StudentsFirst.Common.Dtos.Users; using StudentsFirst.Common.Models; namespace StudentsFirst.Api.Monolithic.Infrastructure.Mapping { public class MappingProfile : Profile { public MappingProfile() { CreateMap<User, UserResponse>(); CreateMap<Group, GroupResponse>(); } } }
24.294118
62
0.658596
[ "MIT" ]
saraetx/studentsfirst
StudentsFirst.Api.Monolithic/Infrastructure/Mapping/MappingProfile.cs
413
C#
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// ConciergeQueryRequest /// </summary> [DataContract] public partial class ConciergeQueryRequest : IEquatable<ConciergeQueryRequest>, IValidatableObject { public ConciergeQueryRequest() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="ConciergeQueryRequest" /> class. /// </summary> /// <param name="AccountManagementRepCountry">.</param> /// <param name="ContractCountry">.</param> /// <param name="PlanId">.</param> /// <param name="Region">.</param> /// <param name="ShippingCountry">.</param> public ConciergeQueryRequest(string AccountManagementRepCountry = default(string), string ContractCountry = default(string), string PlanId = default(string), string Region = default(string), string ShippingCountry = default(string)) { this.AccountManagementRepCountry = AccountManagementRepCountry; this.ContractCountry = ContractCountry; this.PlanId = PlanId; this.Region = Region; this.ShippingCountry = ShippingCountry; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="accountManagementRepCountry", EmitDefaultValue=false)] public string AccountManagementRepCountry { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="contractCountry", EmitDefaultValue=false)] public string ContractCountry { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="planId", EmitDefaultValue=false)] public string PlanId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="region", EmitDefaultValue=false)] public string Region { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="shippingCountry", EmitDefaultValue=false)] public string ShippingCountry { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ConciergeQueryRequest {\n"); sb.Append(" AccountManagementRepCountry: ").Append(AccountManagementRepCountry).Append("\n"); sb.Append(" ContractCountry: ").Append(ContractCountry).Append("\n"); sb.Append(" PlanId: ").Append(PlanId).Append("\n"); sb.Append(" Region: ").Append(Region).Append("\n"); sb.Append(" ShippingCountry: ").Append(ShippingCountry).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ConciergeQueryRequest); } /// <summary> /// Returns true if ConciergeQueryRequest instances are equal /// </summary> /// <param name="other">Instance of ConciergeQueryRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(ConciergeQueryRequest other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AccountManagementRepCountry == other.AccountManagementRepCountry || this.AccountManagementRepCountry != null && this.AccountManagementRepCountry.Equals(other.AccountManagementRepCountry) ) && ( this.ContractCountry == other.ContractCountry || this.ContractCountry != null && this.ContractCountry.Equals(other.ContractCountry) ) && ( this.PlanId == other.PlanId || this.PlanId != null && this.PlanId.Equals(other.PlanId) ) && ( this.Region == other.Region || this.Region != null && this.Region.Equals(other.Region) ) && ( this.ShippingCountry == other.ShippingCountry || this.ShippingCountry != null && this.ShippingCountry.Equals(other.ShippingCountry) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AccountManagementRepCountry != null) hash = hash * 59 + this.AccountManagementRepCountry.GetHashCode(); if (this.ContractCountry != null) hash = hash * 59 + this.ContractCountry.GetHashCode(); if (this.PlanId != null) hash = hash * 59 + this.PlanId.GetHashCode(); if (this.Region != null) hash = hash * 59 + this.Region.GetHashCode(); if (this.ShippingCountry != null) hash = hash * 59 + this.ShippingCountry.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
37.401042
240
0.556468
[ "MIT" ]
MaxMood96/docusign-esign-csharp-client
sdk/src/DocuSign.eSign/Model/ConciergeQueryRequest.cs
7,181
C#
/* * 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 codestar-2017-04-19.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CodeStar.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeStar.Model.Internal.MarshallTransformations { /// <summary> /// ListUserProfiles Request Marshaller /// </summary> public class ListUserProfilesRequestMarshaller : IMarshaller<IRequest, ListUserProfilesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ListUserProfilesRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListUserProfilesRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeStar"); string target = "CodeStar_20170419.ListUserProfiles"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-04-19"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetMaxResults()) { context.Writer.WritePropertyName("maxResults"); context.Writer.Write(publicRequest.MaxResults); } if(publicRequest.IsSetNextToken()) { context.Writer.WritePropertyName("nextToken"); context.Writer.Write(publicRequest.NextToken); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static ListUserProfilesRequestMarshaller _instance = new ListUserProfilesRequestMarshaller(); internal static ListUserProfilesRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListUserProfilesRequestMarshaller Instance { get { return _instance; } } } }
35.227273
147
0.622968
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/CodeStar/Generated/Model/Internal/MarshallTransformations/ListUserProfilesRequestMarshaller.cs
3,875
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.12 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace QuantLib { public class DKKCurrency : Currency { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal DKKCurrency(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NQuantLibcPINVOKE.DKKCurrency_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(DKKCurrency obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~DKKCurrency() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_DKKCurrency(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public DKKCurrency() : this(NQuantLibcPINVOKE.new_DKKCurrency(), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } } }
33.632653
136
0.640777
[ "BSD-3-Clause" ]
x-xing/Quantlib-SWIG
CSharp/csharp/DKKCurrency.cs
1,648
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("my-recipe-book")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("my-recipe-book")] [assembly: System.Reflection.AssemblyTitleAttribute("my-recipe-book")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.333333
80
0.645161
[ "MIT" ]
TheTommyTwitch/my-recipe-book
obj/Debug/netcoreapp2.0/my-recipe-book.AssemblyInfo.cs
992
C#
#region Copyright /*************************************************************************************** ******Copyright (C) 2016 Pritam Zope***** <copyright file="SampleProject_Form.cs" company=""> {- Program Name = Silver-J An Integrated Development Environment(IDE) for Java Programming Language written In C# -} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Please credit me if you reuse, don't sell it under your own name, don't pretend you're me </copyright> * ****************************************************************************************/ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; namespace Silver_J { public partial class SampleProject_Form : Form { public SampleProject_Form() { InitializeComponent(); } public static String project_file = ""; public static String project_folder = ""; public static String project_name = ""; public static Boolean is_project_created = false; public String getProjectFile() { return project_file; } public Boolean isProjectCreated() { return is_project_created; } private void SampleProject_Form_Load(object sender, EventArgs e) { listBox1.SelectedIndex = 0; } String defaultprojfilepath = Application.StartupPath + "\\files\\defaultprojloc.slvjfile"; String[] basic_controls_demo_files = { Application.StartupPath+"\\Samples\\BasicControlsDemo\\BasicControlsDemo.slvjfile", Application.StartupPath+"\\Samples\\BasicControlsDemo\\ButtonsDemo.slvjfile", Application.StartupPath+"\\Samples\\BasicControlsDemo\\CheckBoxDemo.slvjfile", Application.StartupPath+"\\Samples\\BasicControlsDemo\\ComboBoxDemo.slvjfile", Application.StartupPath+"\\Samples\\BasicControlsDemo\\TabbedPaneDemo.slvjfile", Application.StartupPath+"\\Samples\\BasicControlsDemo\\TableDemo.slvjfile", Application.StartupPath+"\\Samples\\BasicControlsDemo\\TextAreaDemo.slvjfile", Application.StartupPath+"\\Samples\\BasicControlsDemo\\TextFieldDemo.slvjfile", Application.StartupPath+"\\Samples\\BasicControlsDemo\\TreeDemo.slvjfile" }; String[] basic_controls_demo_2 ={ "BasicControlsDemo.java", "ButtonsDemo.java", "CheckBoxDemo.java", "ComboBoxDemo.java", "TabbedPaneDemo.java", "TableDemo.java", "TextAreaDemo.java", "TextFieldDemo.java", "TreeDemo.java" }; String[] bounceball_files = { Application.StartupPath+"\\Samples\\BounceBall\\BounceBall.slvjfile" }; String[] bounceball_2 ={ "BounceBall.java", }; String[] game_engine = { Application.StartupPath+"\\Samples\\BasicGameEngineInJava\\Game.slvjfile", Application.StartupPath+"\\Samples\\BasicGameEngineInJava\\Texture.slvjfile", Application.StartupPath+"\\Samples\\BasicGameEngineInJava\\Camera.slvjfile", Application.StartupPath+"\\Samples\\BasicGameEngineInJava\\Screen.slvjfile" }; String[] game_engine_2 ={ "Game.java", "Texture.java", "Camera.java", "Screen.java", }; String[] buttons_demo_files = { Application.StartupPath+"\\Samples\\ButtonsDemo\\ButtonsDemo.slvjfile" }; String[] buttons_demo_2 ={ "ButtonsDemo.java", }; String[] calculator_files = { Application.StartupPath+"\\Samples\\Calculator\\Calculator.slvjfile" }; String[] calculator_2 ={ "Calculator.java", }; String[] fontstest_files = { Application.StartupPath+"\\Samples\\FontsTest\\FontsTest.slvjfile" }; String[] fontstest_2 ={ "FontsTest.java" }; String[] graphicstest_files = { Application.StartupPath+"\\Samples\\GraphicsTest\\GraphicsTest.slvjfile", Application.StartupPath+"\\Samples\\GraphicsTest\\abc.jpg" }; String[] graphicstest_2 ={ "GraphicsTest.java" }; String[] javahtmleditor_files = { Application.StartupPath+"\\Samples\\JavaHTMLEditor\\JavaHTMLEditor.slvjfile" }; String[] javahtmleditor_2 ={ "JavaHTMLEditor.java" }; String[] lookandfeeldemo_demo_files = { Application.StartupPath+"\\Samples\\LookAndFeelDemo\\JavaBlueTheme.slvjfile", Application.StartupPath+"\\Samples\\LookAndFeelDemo\\JavaGreenTheme.slvjfile", Application.StartupPath+"\\Samples\\LookAndFeelDemo\\JavaRedTheme.slvjfile", Application.StartupPath+"\\Samples\\LookAndFeelDemo\\LookAndFeelDemo.slvjfile", Application.StartupPath+"\\Samples\\LookAndFeelDemo\\TestFrame.slvjfile", }; String[] lookandfeeldemo_demo_2 ={ "JavaBlueTheme.java", "JavaGreenTheme.java", "JavaRedTheme.java", "LookAndFeelDemo.java", "TestFrame.java", }; String[] notepad_files = { Application.StartupPath+"\\Samples\\Notepad\\Notepad.slvjfile" }; String[] notepad_2 ={ "Notepad.java" }; String[] paintapp_files = { Application.StartupPath+"\\Samples\\PaintApp\\PaintApp.slvjfile" }; String[] paintapp_2 ={ "PaintApp.java" }; public String ProjectLocaionFoder() { String projectfolder = ""; using (XmlReader reader = XmlReader.Create(defaultprojfilepath)) { while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name.ToString()) { case "DefaultProjectLocation": projectfolder = reader.ReadString(); break; } } } } return projectfolder; } public void LoadProject() { if (ProjectLocaionFoder() == "" || ProjectLocaionFoder() == "null" || ProjectLocaionFoder() == "\n ") { DialogResult dg = MessageBox.Show("Project Folder is not specified\nClick 'Yes' to select your project folder", "Error to Load", MessageBoxButtons.YesNo); if (dg == DialogResult.Yes) { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { String path = folderBrowserDialog1.SelectedPath; XmlDocument doc = new XmlDocument(); doc.Load(defaultprojfilepath); doc.SelectSingleNode("SilverJ/DefaultProjectLocation").InnerText = path; doc.Save(defaultprojfilepath); } } } else if (ProjectLocaionFoder() != "" || ProjectLocaionFoder() != "null" || ProjectLocaionFoder() != " \n ") { String selected_item = listBox1.SelectedItem.ToString(); String projectfolder = ProjectLocaionFoder(); if (selected_item == "Basic Controls Demo") { project_name = "BasicControlsDemo"; String directory = projectfolder + "\\BasicControlsDemo"; String projectfile = "BasicControlsDemo.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; //File.Create(directory + "\\" + projectfile); project_file = directory + "\\" + projectfile; } foreach (String item in basic_controls_demo_files) { if (File.Exists(item)) { String filename = item; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(item); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "BasicControlsDemo"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[1]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[1]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[2]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[2]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[3]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[3]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[4]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[4]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[5]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[5]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[6]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[6]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[7]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[7]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[8]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + basic_controls_demo_2[8]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } } is_project_created = true; } } else if (selected_item == "BounceBall") { project_name = "BounceBall"; String directory = projectfolder + "\\BounceBall"; String projectfile = "BounceBall.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(bounceball_files[0])) { String filename = bounceball_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(bounceball_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "BounceBall"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + bounceball_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + bounceball_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + bounceball_2[0]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } else if (selected_item == "ButtonsDemo") { project_name = "ButtonsDemo"; String directory = projectfolder + "\\ButtonsDemo"; String projectfile = "ButtonsDemo.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(buttons_demo_files[0])) { String filename = buttons_demo_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(buttons_demo_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "ButtonsDemo"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + buttons_demo_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + buttons_demo_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + buttons_demo_2[0]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } else if (selected_item == "Calculator") { project_name = "Calculator"; String directory = projectfolder + "\\Calculator"; String projectfile = "Calculator.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(calculator_files[0])) { String filename = calculator_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(calculator_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "Calculator"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + calculator_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + calculator_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + calculator_2[0]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } else if (selected_item == "FontsTest") { project_name = "FontsTest"; String directory = projectfolder + "\\FontsTest"; String projectfile = "FontsTest.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(fontstest_files[0])) { String filename = fontstest_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(fontstest_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "FontsTest"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + fontstest_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + fontstest_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + fontstest_2[0]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } else if (selected_item == "GraphicsTest") { project_name = "GraphicsTest"; String directory = projectfolder + "\\GraphicsTest"; String projectfile = "GraphicsTest.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(graphicstest_files[0])) { String filename = graphicstest_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(graphicstest_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); if (File.Exists(graphicstest_files[1])) { File.Copy(graphicstest_files[1], srcclasses + "\\abc.jpg"); } } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "GraphicsTest"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + graphicstest_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + graphicstest_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + graphicstest_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("OtherFile", directory + "\\srcclasses" + "\\abc.jpg"); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } else if (selected_item == "HTML Editor in Java") { project_name = "JavaHTMLEditor"; String directory = projectfolder + "\\JavaHTMLEditor"; String projectfile = "JavaHTMLEditor.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(javahtmleditor_files[0])) { String filename = javahtmleditor_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(javahtmleditor_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "JavaHTMLEditor"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + javahtmleditor_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + javahtmleditor_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + javahtmleditor_2[0]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } else if (selected_item == "Look and Feel Demo") { project_name = "LookAndFeelDemo"; String directory = projectfolder + "\\LookAndFeelDemo"; String projectfile = "LookAndFeelDemo.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; //File.Create(directory + "\\" + projectfile); project_file = directory + "\\" + projectfile; } foreach (String item in lookandfeeldemo_demo_files) { if (File.Exists(item)) { String filename = item; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(item); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "LookAndFeelDemo"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[3]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[1]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[1]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[2]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[2]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[3]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[3]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[4]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + lookandfeeldemo_demo_2[4]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } } is_project_created = true; } } else if (selected_item == "Notepad") { project_name = "Notepad"; String directory = projectfolder + "\\Notepad"; String projectfile = "Notepad.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(notepad_files[0])) { String filename = notepad_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(notepad_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (latest) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "Notepad"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + notepad_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + notepad_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + notepad_2[0]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } else if (selected_item == "PaintApp") { project_name = "PaintApp"; String directory = projectfolder + "\\PaintApp"; String projectfile = "PaintApp.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(paintapp_files[0])) { String filename = paintapp_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(paintapp_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (b148) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "PaintApp"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + paintapp_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + paintapp_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + paintapp_2[0]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } else if (selected_item == "Game Engine in Java") { project_name = "Game Engine in Java"; String directory = projectfolder + "\\BasicGameEngineInJava"; String projectfile = "BasicGameEngineInJava.tjsln"; if (Directory.Exists(directory)) { MessageBox.Show("The selected project is already exists in current location", "Error............"); } else { Directory.CreateDirectory(directory); if (Directory.Exists(directory)) { project_folder = directory; project_file = directory + "\\" + projectfile; } if (File.Exists(paintapp_files[0])) { String filename = paintapp_files[0]; String fname = filename.Substring(filename.LastIndexOf("\\") + 1); fname = fname.Remove(fname.Length - 9); fname = fname + ".java"; if (Directory.Exists(directory)) { String src = directory + "\\src"; String srcclasses = directory + "\\srcclasses"; String classes = directory + "\\classes"; Directory.CreateDirectory(src); Directory.CreateDirectory(srcclasses); Directory.CreateDirectory(classes); String content = ""; content = File.ReadAllText(paintapp_files[0]); if (Directory.Exists(srcclasses)) { StreamWriter strw = new StreamWriter(File.Create(srcclasses + "\\" + fname)); strw.Write(content); strw.Close(); strw.Dispose(); } //creating & writing slvjproj file using (XmlWriter xmlwriter = XmlWriter.Create(directory + "\\" + projectfile)) { xmlwriter.WriteStartDocument(); xmlwriter.WriteStartElement("SilverJProject"); xmlwriter.WriteString("\n"); xmlwriter.WriteComment("ThinkJava (b148) Java Application Project"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectName", "BasicGameEngineInJava"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFolder", directory); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectLocationFile", directory + "\\" + projectfile); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("ProjectType", "ApplicationType"); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("MainClassFile", directory + "\\srcclasses" + "\\" + paintapp_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("JavaClassFile", directory + "\\srcclasses" + "\\" + paintapp_2[0]); xmlwriter.WriteString("\n"); xmlwriter.WriteElementString("VisualFile", directory + "\\srcclasses" + "\\" + paintapp_2[0]); xmlwriter.WriteEndElement(); xmlwriter.WriteEndDocument(); xmlwriter.Close(); } } } is_project_created = true; } } } else { DialogResult dg = MessageBox.Show("Project Folder is not specified\nClick 'Yes' to select your project folder", "Error to Load", MessageBoxButtons.YesNo); if (dg == DialogResult.Yes) { if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { String path = folderBrowserDialog1.SelectedPath; XmlDocument doc = new XmlDocument(); doc.Load(defaultprojfilepath); doc.SelectSingleNode("SilverJ/DefaultProjectLocation").InnerText = path; doc.Save(defaultprojfilepath); } } } } private void OKbutton_Click(object sender, EventArgs e) { LoadProject(); this.Close(); } private void Cancelbutton_Click(object sender, EventArgs e) { this.Close(); } } }
51.009091
170
0.407473
[ "MIT" ]
kaitoujokercodes/ThinkJava
ThinkJava/SampleProject_Form.cs
67,334
C#
using AIProgrammer.Fitness.Base; using AIProgrammer.GeneticAlgorithm; using AIProgrammer.Managers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AIProgrammer.Fitness.Concrete { /// <summary> /// Calculates the Fibonacci sequence, starting at input1, input2. /// Usage: /// In App.config: /// <add key="BrainfuckVersion" value="2"/> /// In Program.cs set: /// private static string _appendCode = FibonacciFitness.FibonacciFunctions; /// ... /// private static IFitness GetFitnessMethod() /// { /// return new FibonacciFitness(_ga, _maxIterationCount, 4, 3, _appendCode); /// } /// </summary> public class FibonacciFitness : FitnessBase { private int _trainingCount; private int _maxDigits; // number of fibonacci numbers to calculate. private static int _functionCount; // number of functions in the appeneded code. /// <summary> /// Previously generated BrainPlus function for addition. Generated using AddFitness. /// To use, set _appendCode = FibonacciFitness.FibonacciFunctions in main program. /// </summary> public static string FibonacciFunctions = ",>,-[-<+>]<+.$@"; public FibonacciFitness(GA ga, int maxIterationCount, int maxDigits = 4, int maxTrainingCount = 3, string appendFunctions = null) : base(ga, maxIterationCount, appendFunctions) { _maxDigits = maxDigits; _trainingCount = maxTrainingCount; if (_targetFitness == 0) { _targetFitness = _trainingCount * 256 * _maxDigits; _functionCount = CommonManager.GetFunctionCount(appendFunctions); } } #region FitnessBase Members protected override double GetFitnessMethod(string program) { byte input1 = 0, input2 = 0; int state = 0; double countBonus = 0; double penalty = 0; List<byte> digits = new List<byte>(); for (int i = 0; i < _trainingCount; i++) { switch (i) { case 0: input1 = 1; input2 = 2; break; case 1: input1 = 3; input2 = 5; break; case 2: input1 = 8; input2 = 13; break; }; try { state = 0; _console.Clear(); digits.Clear(); // Run the program. _bf = new Interpreter(program, () => { if (state == 0) { state++; return input1; } else if (state == 1) { state++; return input2; } else { // Not ready for input. penalty++; return 0; } }, (b) => { if (state < 2) { // Not ready for output. penalty++; } else { _console.Append(b); _console.Append(","); digits.Add(b); } }); _bf.Run(_maxIterationCount); } catch { } _output.Append(_console.ToString()); _output.Append("|"); // 0,1,1,2,3,5,8,13,21,34,55,89,144,233. Starting at 3 and verifying 10 digits. int index = 0; int targetValue = input1 + input2; // 1 + 2 = 3 int lastValue = input2; // 2 foreach (byte digit in digits) { Fitness += 256 - Math.Abs(digit - targetValue); int temp = lastValue; // 2 lastValue = targetValue; // 3 targetValue += temp; // 3 + 2 = 5 if (++index >= _maxDigits) break; } // Make the AI wait until a solution is found without the penalty (too many input characters). Fitness -= penalty; // Check for solution. IsFitnessAchieved(); // Bonus for less operations to optimize the code. countBonus += ((_maxIterationCount - _bf.m_Ticks) / 1000.0); // Bonus for using functions. if (_functionCount > 0) { for (char functionName = 'a'; functionName < 'a' + _functionCount; functionName++) { if (MainProgram.Contains(functionName)) { countBonus += 25; } } } Ticks += _bf.m_Ticks; } if (_fitness != Double.MaxValue) { _fitness = Fitness + countBonus; } return _fitness; } protected override void RunProgramMethod(string program) { for (int i = 0; i < 99; i++) { try { int state = 0; // Run the program. Interpreter bf = new Interpreter(program, () => { if (state == 0) { state++; Console.WriteLine(); Console.Write(">: "); byte b = Byte.Parse(Console.ReadLine()); return b; } else if (state == 1) { state++; Console.WriteLine(); Console.Write(">: "); byte b = Byte.Parse(Console.ReadLine()); return b; } else { return 0; } }, (b) => { Console.Write(b + ","); }); bf.Run(_maxIterationCount); } catch { } } } public override string GetConstructorParameters() { return _maxIterationCount + ", " + _maxDigits + ", " + _trainingCount; } #endregion } }
32.588235
137
0.395307
[ "MIT" ]
Abhinav23/Automatic-Self-Modifying-Program
AIProgrammer.Fitness/Concrete/FibonacciFitness.cs
7,204
C#
using CQELight.Bootstrapping.Notifications; using CQELight.TestFramework; using FluentAssertions; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace CQELight.Tests { public class BootstrapperNotificationTests : BaseUnitTestClass { #region Ctor & members #endregion #region Ctor [Fact] public void When_Creating_A_New_BootstrapperNotification_With_Message_It_Should_Set_ContentType_To_CustomService() { var n = new BootstrapperNotification(BootstrapperNotificationType.Error, "Error message"); n.ContentType.Should().Be(BootstapperNotificationContentType.CustomServiceNotification); } [Fact] public void When_Creating_A_New_BootstrapperNotification_Type_Should_Be_Provided() { Assert.Throws<ArgumentNullException>(() => new BootstrapperNotification(BootstrapperNotificationType.Error, "error message", null)); } #endregion } }
26.538462
122
0.710145
[ "MIT" ]
Thanouz/CQELight
tests/CQELight.Tests/Bootstrapper/BootstrapperNotification.Tests.cs
1,037
C#
using Discount.API.Entities; using Discount.API.Repositories; using Microsoft.AspNetCore.Mvc; using System; using System.Net; using System.Threading.Tasks; namespace Discount.API.Controllers { [ApiController] [Route("api/v1/[controller]")] public class DiscountController : ControllerBase { private readonly IRepository _repository; public DiscountController(IRepository repository) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); } [HttpGet("{productName}", Name = "GetDiscount")] [ProducesResponseType(typeof(Coupon), (int)HttpStatusCode.OK)] public async Task<ActionResult<Coupon>> GetDiscount(string productName) { var coupon = await _repository.GetDiscount(productName); return Ok(coupon); } [HttpPost] [ProducesResponseType(typeof(Coupon), (int)HttpStatusCode.OK)] public async Task<ActionResult<Coupon>> CreateDiscount([FromBody] Coupon coupon) { await _repository.CreateDiscount(coupon); return CreatedAtRoute("GetDiscount", new { productName = coupon.ProductName }, coupon); } [HttpPut] [ProducesResponseType(typeof(Coupon), (int)HttpStatusCode.OK)] public async Task<ActionResult<Coupon>> UpdateDiscount([FromBody] Coupon coupon) { return Ok(await _repository.UpdateDiscount(coupon)); } [HttpDelete("{productName}", Name = "DeleteDiscount")] [ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)] public async Task<ActionResult<bool>> DeleteDiscount(string productName) { return Ok(await _repository.DeleteDiscount(productName)); } } }
34.423077
99
0.663687
[ "MIT" ]
sebash1992/MicroservicesNet6
src/Discount/Discount.API/Controllers/DiscountController.cs
1,792
C#
using System; using System.Collections.Generic; using System.Text; namespace OpenNetLinkApp.Data.SGQuery { class MailApproveParam : BaseParam { public string SearchFromDay { get; set; }//on public string SearchToDay { get; set; }//on public string ApprKind { get; set; } //on public string TransKind { get; set; } public string ApprStatus { get; set; } public string ApproveFlag { get; set; } //on public string TransStatus { get; set; } //on public string ReqUserName { get; set; } public string Sender { get; set; } //on public string Receiver { get; set; } //on public string Title { get; set; } //on public string UserID { get; set; }//on public string APPROVE_TYPE_SFM { get; set; } //1:대결자기준, 2:결재자기준 //on public string SystemId { get; set; } //사용자가 접근한 시스템 //on } }
36.72
80
0.59695
[ "Apache-2.0" ]
angellos12/OpenNetLink
src/OpenNetLinkApp/Data/SGQuery/MailApproveParam.cs
958
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codepipeline-2015-07-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CodePipeline.Model { /// <summary> /// Container for the parameters to the PutJobSuccessResult operation. /// Represents the success of a job as returned to the pipeline by a job worker. Only /// used for custom actions. /// </summary> public partial class PutJobSuccessResultRequest : AmazonCodePipelineRequest { private string _continuationToken; private CurrentRevision _currentRevision; private ExecutionDetails _executionDetails; private string _jobId; /// <summary> /// Gets and sets the property ContinuationToken. /// <para> /// A token generated by a job worker, such as an AWS CodeDeploy deployment ID, that a /// successful job provides to identify a custom action in progress. Future jobs will /// use this token in order to identify the running instance of the action. It can be /// reused to return additional information about the progress of the custom action. When /// the action is complete, no continuation token should be supplied. /// </para> /// </summary> [AWSProperty(Min=1, Max=2048)] public string ContinuationToken { get { return this._continuationToken; } set { this._continuationToken = value; } } // Check to see if ContinuationToken property is set internal bool IsSetContinuationToken() { return this._continuationToken != null; } /// <summary> /// Gets and sets the property CurrentRevision. /// <para> /// The ID of the current revision of the artifact successfully worked upon by the job. /// </para> /// </summary> public CurrentRevision CurrentRevision { get { return this._currentRevision; } set { this._currentRevision = value; } } // Check to see if CurrentRevision property is set internal bool IsSetCurrentRevision() { return this._currentRevision != null; } /// <summary> /// Gets and sets the property ExecutionDetails. /// <para> /// The execution details of the successful job, such as the actions taken by the job /// worker. /// </para> /// </summary> public ExecutionDetails ExecutionDetails { get { return this._executionDetails; } set { this._executionDetails = value; } } // Check to see if ExecutionDetails property is set internal bool IsSetExecutionDetails() { return this._executionDetails != null; } /// <summary> /// Gets and sets the property JobId. /// <para> /// The unique system-generated ID of the job that succeeded. This is the same ID returned /// from PollForJobs. /// </para> /// </summary> [AWSProperty(Required=true)] public string JobId { get { return this._jobId; } set { this._jobId = value; } } // Check to see if JobId property is set internal bool IsSetJobId() { return this._jobId != null; } } }
33.894309
110
0.620053
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/CodePipeline/Generated/Model/PutJobSuccessResultRequest.cs
4,169
C#
/* * 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 ram-2018-01-04.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.RAM.Model { /// <summary> /// The specified tag is a reserved word and cannot be used. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class TagPolicyViolationException : AmazonRAMException { /// <summary> /// Constructs a new TagPolicyViolationException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public TagPolicyViolationException(string message) : base(message) {} /// <summary> /// Construct instance of TagPolicyViolationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TagPolicyViolationException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of TagPolicyViolationException /// </summary> /// <param name="innerException"></param> public TagPolicyViolationException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of TagPolicyViolationException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TagPolicyViolationException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of TagPolicyViolationException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TagPolicyViolationException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the TagPolicyViolationException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected TagPolicyViolationException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
47.233871
178
0.680895
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/RAM/Generated/Model/TagPolicyViolationException.cs
5,857
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using Azure.Core; namespace Azure.ResourceManager.Sql.Models { /// <summary> A list of subscription usage metrics in a location. </summary> internal partial class SubscriptionUsageListResult { /// <summary> Initializes a new instance of SubscriptionUsageListResult. </summary> internal SubscriptionUsageListResult() { Value = new ChangeTrackingList<SubscriptionUsage>(); } /// <summary> Initializes a new instance of SubscriptionUsageListResult. </summary> /// <param name="value"> Array of results. </param> /// <param name="nextLink"> Link to retrieve next page of results. </param> internal SubscriptionUsageListResult(IReadOnlyList<SubscriptionUsage> value, string nextLink) { Value = value; NextLink = nextLink; } /// <summary> Array of results. </summary> public IReadOnlyList<SubscriptionUsage> Value { get; } /// <summary> Link to retrieve next page of results. </summary> public string NextLink { get; } } }
33.945946
101
0.661624
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/SubscriptionUsageListResult.cs
1,256
C#
using System; using EventStore.Core.Bus; using EventStore.Core.Messaging; using EventStore.Transport.Http; using EventStore.Transport.Http.EntityManagement; namespace EventStore.Core.Services.Transport.Http { public class SendToHttpWithConversionEnvelope<TExpectedResponseMessage, TExpectedHttpFormattedResponseMessage> : IEnvelope where TExpectedResponseMessage : Message { private readonly Func<ICodec, TExpectedHttpFormattedResponseMessage, string> _formatter; private readonly Func<ICodec, TExpectedHttpFormattedResponseMessage, ResponseConfiguration> _configurator; private readonly Func<TExpectedResponseMessage, TExpectedHttpFormattedResponseMessage> _convertor; private readonly IEnvelope _httpEnvelope; public SendToHttpWithConversionEnvelope(IPublisher networkSendQueue, HttpEntityManager entity, Func<ICodec, TExpectedHttpFormattedResponseMessage, string> formatter, Func<ICodec, TExpectedHttpFormattedResponseMessage, ResponseConfiguration> configurator, Func<TExpectedResponseMessage, TExpectedHttpFormattedResponseMessage> convertor, IEnvelope nonMatchingEnvelope = null) { _formatter = formatter; _configurator = configurator; _convertor = convertor; _httpEnvelope = new SendToHttpEnvelope<TExpectedResponseMessage>(networkSendQueue, entity, Formatter, Configurator, nonMatchingEnvelope); } private ResponseConfiguration Configurator(ICodec codec, TExpectedResponseMessage message) { var convertedMessage = _convertor(message); return _configurator(codec, convertedMessage); } private string Formatter(ICodec codec, TExpectedResponseMessage message) { var convertedMessage = _convertor(message); return _formatter(codec, convertedMessage); } public void ReplyWith<T>(T message) where T : Message { _httpEnvelope.ReplyWith(message); } } }
40.777778
113
0.822888
[ "Apache-2.0", "CC0-1.0" ]
01100010011001010110010101110000/EventStore
src/EventStore.Core/Services/Transport/Http/SendToHttpWithConversionEnvelope.cs
1,835
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace Inbox2.Framework.UI { /// <summary> /// From: http://serialseb.blogspot.com/2007/09/wpf-tips-6-preventing-scrollviewer-from.html /// </summary> public class ScrollViewerCorrector { public static readonly DependencyProperty FixScrollingProperty = DependencyProperty.RegisterAttached("FixScrolling", typeof(bool), typeof(ScrollViewerCorrector), new FrameworkPropertyMetadata(false, OnFixScrollingPropertyChanged)); public static bool GetFixScrolling(DependencyObject obj) { return (bool)obj.GetValue(FixScrollingProperty); } public static void SetFixScrolling(DependencyObject obj, bool value) { obj.SetValue(FixScrollingProperty, value); } public static void OnFixScrollingPropertyChanged(object sender, DependencyPropertyChangedEventArgs e) { ScrollViewer viewer = sender as ScrollViewer; if (viewer == null) throw new ArgumentException("The dependency property can only be attached to a ScrollViewer", "sender"); if ((bool)e.NewValue == true) viewer.PreviewMouseWheel += HandlePreviewMouseWheel; else if ((bool)e.NewValue == false) viewer.PreviewMouseWheel -= HandlePreviewMouseWheel; } private static List<MouseWheelEventArgs> _reentrantList = new List<MouseWheelEventArgs>(); private static void HandlePreviewMouseWheel(object sender, MouseWheelEventArgs e) { var scrollControl = sender as ScrollViewer; if (!e.Handled && sender != null && !_reentrantList.Contains(e)) { var previewEventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta) { RoutedEvent = UIElement.PreviewMouseWheelEvent, Source = sender }; var originalSource = e.OriginalSource as UIElement; if (originalSource != null) { _reentrantList.Add(previewEventArg); originalSource.RaiseEvent(previewEventArg); _reentrantList.Remove(previewEventArg); // at this point if no one else handled the event in our children, we do our job if (!previewEventArg.Handled && ((e.Delta > 0 && scrollControl.VerticalOffset == 0) || (e.Delta <= 0 && scrollControl.VerticalOffset >= scrollControl.ExtentHeight - scrollControl.ViewportHeight))) { e.Handled = true; var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta); eventArg.RoutedEvent = UIElement.MouseWheelEvent; eventArg.Source = sender; var parent = (UIElement)((FrameworkElement)sender).Parent; parent.RaiseEvent(eventArg); } } } } } }
32.034884
170
0.711434
[ "BSD-3-Clause" ]
Klaudit/inbox2_desktop
Code/Client/Inbox2/Framework/UI/ScrollViewerCorrector.cs
2,757
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rounding_Numbers_Away_from_Zero { class Program { static void Main(string[] args) { double[] arry = Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); for (int i = 0; i < arry.Length; i++) { double roundet = Math.Round(arry[i],0,MidpointRounding.AwayFromZero); Console.WriteLine("{0} => {1}", arry[i], roundet); } } } }
21.814815
89
0.561969
[ "MIT" ]
SvetlaYordanova/Programming-Fundamentals
12. Arrays/Rounding Numbers Away from Zero/Rounding Numbers Away from Zero/Program.cs
591
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; using Azure.ResourceManager.DnsResolver; namespace Azure.ResourceManager.DnsResolver.Models { internal partial class DnsResolverListResult { internal static DnsResolverListResult DeserializeDnsResolverListResult(JsonElement element) { Optional<IReadOnlyList<DnsResolverData>> value = default; Optional<string> nextLink = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<DnsResolverData> array = new List<DnsResolverData>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(DnsResolverData.DeserializeDnsResolverData(item)); } value = array; continue; } if (property.NameEquals("nextLink")) { nextLink = property.Value.GetString(); continue; } } return new DnsResolverListResult(Optional.ToList(value), nextLink.Value); } } }
33.6875
99
0.550402
[ "MIT" ]
ChenTanyi/azure-sdk-for-net
sdk/dnsresolver/Azure.ResourceManager.DnsResolver/src/Generated/Models/DnsResolverListResult.Serialization.cs
1,617
C#