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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// /* // Copyright 2008-2011 Alex Robson // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // */ using System; using System.Linq.Expressions; namespace Symbiote.Core.DI { public interface ISupplyPlugin<TPlugin> { IPluginConfiguration Add<TConcrete>() where TConcrete : TPlugin; IPluginConfiguration Add<TConcrete>( TConcrete instance ) where TConcrete : TPlugin; IPluginConfiguration Add( Type concreteType ); IPluginConfiguration Use<TConcrete>() where TConcrete : TPlugin; IPluginConfiguration Use<TConcrete>( TConcrete instance ) where TConcrete : TPlugin; IPluginConfiguration Use( Type concreteType ); IPluginConfiguration CreateWith<TConcrete>( Func<RequestContext, TConcrete> factory ) where TConcrete : TPlugin; } }
32.619048
93
0.69781
[ "Apache-2.0" ]
code-attic/Symbiote
src/Symbiote.Core/DI/ISupplyPlugin.cs
1,372
C#
using System; namespace RICADO.RabbitMQ { internal struct RedeliveredMessage { public Guid MessageID; public DateTime FirstTimestamp; public DateTime LastTimestamp; public int RedeliveredCount; } }
19.692308
40
0.644531
[ "MIT" ]
ricado-group/dotnet-rabbitmq
RICADO.RabbitMQ/RedeliveredMessage.cs
258
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Text; using System.Threading; using Gallio.Common; using Gallio.Model; using Gallio.Common.Reflection; using Gallio.Model.Tree; namespace Gallio.Framework.Pattern { /// <summary> /// A test builder applies contributions to a test under construction. /// </summary> public interface ITestBuilder : ITestComponentBuilder { /// <summary> /// Gets or sets the value of the <see cref="MetadataKeys.TestKind" /> /// metadata entry. (This is a convenience method.) /// </summary> /// <value> /// One of the <see cref="TestKinds" /> constants. /// </value> string Kind { get; set; } /// <summary> /// Gets or sets the apartment state to be used to run the test. /// </summary> /// <remarks> /// <para> /// If the apartment state is <see cref="System.Threading.ApartmentState.Unknown" /> /// the test will inherit the apartment state of its parent. Otherwise /// it will run in a thread with the specified apartment state. /// </para> /// <para> /// The test runner guarantees that the root test runs with the <see cref="System.Threading.ApartmentState.STA" /> /// apartment state. Consequently the apartment state only needs to be overridden to run /// a test in some mode that may differ from that which it would ordinarily inherit. /// </para> /// </remarks> /// <value> /// The default value of this property is <see cref="System.Threading.ApartmentState.Unknown" />. /// </value> ApartmentState ApartmentState { get; set; } /// <summary> /// Gets or sets the maximum amount of time the whole test including /// its setup, teardown and body should be permitted to run. /// </summary> /// <remarks> /// <para> /// If the test runs any longer than this, it will be aborted by the framework. /// The timeout may be null to indicate the absence of a timeout. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="value"/> /// represents a negative time span.</exception> /// <value>The timeout. Default value is null.</value> GallioFunc<TimeSpan?> TimeoutFunc { get; set; } /// <summary> /// Gets whether this test represents an individual test case /// as opposed to a test container such as a fixture or suite. /// </summary> /// <remarks> /// <para> /// The value of this property can be used by the test harness to avoid processing containers /// that have no test cases. It can also be used by the reporting infrastructure /// to constrain output statistics to test cases only. /// </para> /// <para> /// Not all test cases are leaf nodes in the test tree and vice-versa. /// </para> /// <para> /// This value is defined as a property rather than as a metadata key because it /// significantly changes the semantics of test execution. /// </para> /// </remarks> bool IsTestCase { get; set; } /// <summary> /// Gets or sets whether the test is parallelizable. /// </summary> /// <value> /// True if the test is parallelizable. The default value of this property is <c>false</c>. /// </value> bool IsParallelizable { get; set; } /// <summary> /// Gets or sets a number that defines an ordering for the test with respect to its siblings. /// </summary> /// <remarks> /// <para> /// Unless compelled otherwise by test dependencies, tests with a lower order number than /// their siblings will run before those siblings and tests with the same order number /// as their siblings with run in an arbitrary sequence with respect to those siblings. /// </para> /// <para> /// Some test frameworks may choose to ignore test order or may impose their own ordering schemes. /// </para> /// </remarks> /// <value>The test execution order with respect to siblings, initially zero.</value> int Order { get; set; } /// <summary> /// Gets a locally unique identifier for this test that satisfies some specific conditions. /// </summary> /// <remarks> /// The local identifier must satisfy the following conditions: /// <para> /// <list type="bullet"> /// <item>The identifier is unique among all siblings of this test belonging to the same parent.</item> /// <item>The identifier is likely to be stable across multiple sessions including /// changes and recompilations of the test projects.</item> /// <item>The identifier is non-null.</item> /// </list> /// </para> /// <para> /// The local identifier may be the same as the test's name. However since the name is /// intended for display to end-users, it may contain irrelevant details (such as version /// numbers) that would reduce its long-term stability. In that case, a different /// local identifier should be selected such as one based on the test's /// <see cref="TestComponent.CodeElement" /> and an ordering condition among siblings /// to guarantee uniqueness. /// </para> /// <para> /// The locally unique <see cref="LocalId" /> property may be used to generate the /// globally unique <see cref="TestComponent.Id" /> property of a test by combining /// it with the locally unique identifiers of its parents. /// </para> /// </remarks> /// <returns>The locally unique identifier.</returns> string LocalId { get; } /// <summary> /// Gets or sets a suggested <see cref="LocalId" /> hint, or null if none. /// </summary> /// <remarks> /// <para> /// The value returned by this method will be checked for uniqueness and amended as necessary /// to produce a truly unique <see cref="LocalId" />. /// </para> /// </remarks> /// <value> /// The default value of this property is <c>null</c> which causes the <see cref="ITestComponentBuilder.Name" /> /// property to be used as the local id hint. /// </value> /// <returns>The local id hint.</returns> string LocalIdHint { get; set; } /// <summary> /// Gets the set of actions that describe the behavior of the test. /// </summary> PatternTestActions TestActions { get; } /// <summary> /// Gets the set of actions that describe the behavior of the test's instances. /// </summary> PatternTestInstanceActions TestInstanceActions { get; } /// <summary> /// Creates a child test and returns its builder. /// </summary> /// <param name="name">The test name.</param> /// <param name="codeElement">The associated code element, or null if none.</param> /// <param name="dataContextBuilder">The data context builder for the new test.</param> /// <returns>The builder for the child test.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> or <paramref name="dataContextBuilder"/> is null.</exception> ITestBuilder CreateChild(string name, ICodeElementInfo codeElement, ITestDataContextBuilder dataContextBuilder); /// <summary> /// Creates a test parameter and returns its builder. /// </summary> /// <param name="name">The test parameter name.</param> /// <param name="codeElement">The associated code element, or null if none.</param> /// <param name="dataContextBuilder">The data context builder for the new test parameter.</param> /// <returns>The builder for the test parameter.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> or <paramref name="dataContextBuilder"/> is null.</exception> ITestParameterBuilder CreateParameter(string name, ICodeElementInfo codeElement, ITestDataContextBuilder dataContextBuilder); /// <summary> /// Gets a test parameter builder by name. /// </summary> /// <param name="name">The test parameter name.</param> /// <returns>The builder for the test parameter, or null if none.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> is null.</exception> ITestParameterBuilder GetParameter(string name); /// <summary> /// Adds a test dependency. /// </summary> /// <param name="testDependency">The test to add as a dependency.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="testDependency"/> is null.</exception> void AddDependency(Test testDependency); /// <summary> /// Gets the underlying test. /// </summary> /// <returns>The underlying test.</returns> PatternTest ToTest(); } }
47.036697
148
0.602984
[ "ECL-2.0", "Apache-2.0" ]
soelske/mbunit-v3
src/Gallio/Gallio/Framework/Pattern/ITestBuilder.cs
10,254
C#
using System; using System.Collections.Generic; using System.Text; namespace Hanabi.Flow.Model { /// <summary> /// 通用分页信息类 /// </summary> public class PageModel<T> { /// <summary> /// 当前页标 /// </summary> public int page { get; set; } = 1; /// <summary> /// 总页数 /// </summary> public int pageCount { get; set; } = 6; /// <summary> /// 数据总数 /// </summary> public int dataCount { get; set; } = 0; /// <summary> /// 每页大小 /// </summary> public int PageSize { set; get; } /// <summary> /// 返回数据 /// </summary> public List<T> data { get; set; } } }
20.828571
47
0.444444
[ "MIT" ]
GadHao/Hanabi.Flow.API
Hanabi.Flow.Model/PageModel.cs
783
C#
// Licensed to the Mixcore Foundation under one or more agreements. // The Mixcore Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.AspNet.OData; using Microsoft.AspNet.OData.Query; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; using Mix.Cms.Lib; using Mix.Cms.Lib.Models.Cms; using Mix.Cms.Lib.ViewModels; using Mix.Cms.Lib.ViewModels.MixAttributeSetDatas; using Mix.Domain.Core.ViewModels; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; namespace Mix.Cms.Api.Controllers.v1.OData.AttributeSetDatas { [Produces("application/json")] [Route("api/v1/odata/{culture}/attribute-set-data/read")] [AllowAnonymous] public class ApiODataAttributeSetDataReadController : BaseApiODataController<MixCmsContext, MixAttributeSetData> { public ApiODataAttributeSetDataReadController( IMemoryCache memoryCache , Microsoft.AspNetCore.SignalR.IHubContext<Mix.Cms.Service.SignalR.Hubs.PortalHub> hubContext) : base(memoryCache, hubContext) { } #region Get // GET api/AttributeSetDatas/id [EnableQuery] [HttpGet, HttpOptions] [Route("{id}")] [Route("{id}/{attributeSetId}")] public async Task<ActionResult<ReadViewModel>> Details(string culture, string id, int attributeSetId) { string msg = string.Empty; Expression<Func<MixAttributeSetData, bool>> predicate = null; MixAttributeSetData model = null; // Get Details if has id or else get default predicate = m => m.Id == id && m.Specificulture == _lang; var portalResult = await base.GetSingleAsync<ReadViewModel>(id.ToString(), predicate, model); return Ok(portalResult.Data); } // GET api/attribute-set-datas/portal/count [AllowAnonymous] [EnableQuery] [Route("count")] [HttpGet, HttpOptions] public async System.Threading.Tasks.Task<ActionResult<int>> CountAsync() { return (await ReadViewModel.Repository.CountAsync()).Data; } // GET api/attribute-set-datas/portal/count [AllowAnonymous] [EnableQuery] [Route("count/{name}")] [HttpGet, HttpOptions] public async System.Threading.Tasks.Task<ActionResult<int>> CountByName(string name) { return (await ReadViewModel.Repository.CountAsync(m => m.AttributeSetName == name && m.Specificulture == _lang)).Data; } // Save api/odata/{culture}/attribute-set-data/portal [HttpPost, HttpOptions] [Route("")] public async Task<ActionResult<ReadViewModel>> Save(string culture, [FromBody]ReadViewModel data) { var portalResult = await base.SaveAsync<ReadViewModel>(data, true); if (portalResult.IsSucceed) { return Ok(portalResult); } else { return BadRequest(portalResult); } } // Save api/odata/{culture}/attribute-set-data/portal/{id} [HttpPost, HttpOptions] [Route("{id}")] public async Task<ActionResult<ReadViewModel>> Save(string culture, string id, [FromBody]JObject data) { var portalResult = await base.SaveAsync<ReadViewModel>(data, p => p.Id == id && p.Specificulture == _lang); if (portalResult.IsSucceed) { return Ok(portalResult); } else { return BadRequest(portalResult); } } [HttpDelete, HttpOptions] [Route("{id}")] public async Task<ActionResult<ReadViewModel>> Delete(string culture, string id) { Expression<Func<MixAttributeSetData, bool>> predicate = model => model.Id == id && model.Specificulture == _lang; // Get Details if has id or else get default var portalResult = await base.GetSingleAsync<ReadViewModel>(id.ToString(), predicate); var result = await base.DeleteAsync<ReadViewModel>(portalResult.Data, true); if (result.IsSucceed) { return Ok(result); } else { return BadRequest(result); } } // GET api/AttributeSetDatas/id [EnableQuery(MaxExpansionDepth = 4)] [HttpGet, HttpOptions] public async Task<ActionResult<List<ReadViewModel>>> List(string culture, ODataQueryOptions<MixAttributeSetData> queryOptions) { var result = await base.GetListAsync<ReadViewModel>(queryOptions); return Ok(result); } #endregion Get [HttpPost, HttpOptions] [Route("apply-list")] public async Task<ActionResult<JObject>> ListActionAsync([FromBody]ListAction<string> data) { Expression<Func<MixAttributeSetData, bool>> predicate = model => model.Specificulture == _lang && data.Data.Contains(model.Id); var result = new RepositoryResponse<bool>(); switch (data.Action) { case "Delete": return Ok(JObject.FromObject(await base.DeleteListAsync<DeleteViewModel>(predicate, true))); case "Export": return Ok(JObject.FromObject(await base.ExportListAsync(predicate, MixEnums.MixStructureType.AttributeSet))); default: return JObject.FromObject(new RepositoryResponse<bool>()); } } } }
36.75
138
0.613776
[ "MIT" ]
habita73/mix.core
src/Mix.Cms.Api/Controllers/v1/OData/AttributeSetDatas/ApiODataAttributeSetDataReadController.cs
5,882
C#
using UnityEngine; using UnityEditor.Presets; // // DISCLAIMER // //This is really messy but working code, feel free to upgrade and modify //Made by Adrien Houdoux with the help of Sebastian Lague and libnoise.net. //I'm not an experienced developer so don't throw your keyboard out of the window if some code sucks, I'm 15. //Thanks for trying it out // public class RNG : MonoBehaviour { [HideInInspector()] public Planet planet; public UpdateMeshCollider[] meshUpdaters; ShapeSettings shape; ColourSettings colour; NoiseSettings noiseSettings0; NoiseSettings noiseSettings1; //0 is Simple Noise, 1 is Ridgid Noise. We are only using 2 layers otherwise it would be too heavy [Header("Global Graphics settings")] public bool maxResolution = false; public bool staticLOD = false; [Range(1,8)] public int staticLODValue = 1; [Header("X is min. value, Y is max.")] //public Vector2 planetRadiusMinMax = new Vector2(2.4f, 3.7f); [Header("Simple Noise Attributes")] public Vector2 s_Strength = new Vector2(0.01f, 0.1f); public Vector2 s_BaseRoughness = new Vector2(0.7f, 2f); public Vector2 s_Roughness = new Vector2(2.2f, 3.2f); public Vector2 s_Centre = new Vector2(0, 20); [Header("Ridgid Noise Attributes")] public Vector2 r_Strength = new Vector2(0.6f, 1f); public Vector2 r_BaseRoughness = new Vector2(0.1f, 4.5f); public Vector2 r_Roughness = new Vector2(0, 1); public Vector2 r_Persistence = new Vector2(.3f, .8f); public Vector2 r_Centre = new Vector2(0, 20); public Vector2 r_MinimalValue = new Vector2(0, 2); public Vector2 r_WeightMultiplier = new Vector2(0.3f, 2.5f); private void Start() { planet = GetComponent<Planet>(); shape = planet.shapeSettings; colour = planet.colourSettings; noiseSettings0 = shape.noiseLayers[0].noiseSettings; noiseSettings1 = shape.noiseLayers[1].noiseSettings; } public void Randomise() { //shape.planetRadius = Random.Range(planetRadiusMinMax.x, planetRadiusMinMax.y); if (maxResolution) { int lod = 8; Debug.Log("Max resolution (256) set, expect delays. LOD set to max value (8)."); planet.resolution = 256; noiseSettings0.simpleNoiseSettings.numLayers = lod; noiseSettings1.ridgidNoiseSettings.numLayers = lod; } else if (staticLOD) { int lod = staticLODValue; Debug.Log("Static LOD value enabled"); planet.resolution = 80 + (lod * 22); //Bad math stuff but works accordingly to LOD value noiseSettings0.simpleNoiseSettings.numLayers = lod; noiseSettings1.ridgidNoiseSettings.numLayers = lod; } else { int lod = Random.Range(3, 7); Debug.Log(lod); planet.resolution = 80 + (lod * 22); //Bad math stuff but works accordingly to LOD value noiseSettings0.simpleNoiseSettings.numLayers = lod; noiseSettings1.ridgidNoiseSettings.numLayers = lod; } //Simple noise RNG (highly unoptimised) noiseSettings0.simpleNoiseSettings.strength = Random.Range(s_Strength.x, s_Strength.y); noiseSettings0.simpleNoiseSettings.baseRoughness = Random.Range(s_BaseRoughness.x, s_BaseRoughness.y); noiseSettings0.simpleNoiseSettings.roughness = Random.Range(s_Roughness.x, s_Roughness.y); noiseSettings0.simpleNoiseSettings.centre = new Vector3(Random.Range(s_Centre.x, s_Centre.y), Random.Range(s_Centre.x, s_Centre.y), Random.Range(s_Centre.x, s_Centre.y)); //Ridgid noise RNG (highly unoptimised) noiseSettings1.ridgidNoiseSettings.strength = Random.Range(r_Strength.x, r_Strength.y); noiseSettings1.ridgidNoiseSettings.baseRoughness = Random.Range(r_BaseRoughness.x, r_BaseRoughness.y); noiseSettings1.ridgidNoiseSettings.roughness = Random.Range(r_Roughness.x, r_Roughness.y); noiseSettings1.ridgidNoiseSettings.persistence = Random.Range(r_Persistence.x, r_Persistence.y); noiseSettings1.ridgidNoiseSettings.centre = new Vector3(Random.Range(r_Centre.x, r_Centre.y), Random.Range(r_Centre.x, r_Centre.y), Random.Range(r_Centre.x, r_Centre.y)); noiseSettings1.ridgidNoiseSettings.weightMultiplier = Random.Range(r_WeightMultiplier.x, r_WeightMultiplier.y); noiseSettings1.ridgidNoiseSettings.minValue = Random.Range(r_MinimalValue.x, r_MinimalValue.y); planet.GeneratePlanet(); foreach (UpdateMeshCollider meshUpdater in meshUpdaters) { meshUpdater.RecalculateBounds(); } } [Header("Colour Presets")] public PresetsEnum presetSelector; public enum PresetsEnum { Earth = 0, Arctic = 1, Venus = 2 }; public bool autoRegenerate = false; public bool lockNoiseUpdate = true; [SerializeField] Preset[] presets; //add new conditions for new presets here public void ApplyPreset() { for (int i = 0; i < presets.Length; i++) { if (i == (int)presetSelector) { presets[i].ApplyTo(colour); if (autoRegenerate && !lockNoiseUpdate) { Randomise(); Debug.Log("Planet Generated"); } else if (!autoRegenerate && lockNoiseUpdate) { planet.GenerateColours(); Debug.Log("Colours updated"); } } } } }
32.895954
178
0.644351
[ "MIT" ]
TheSlippyPenguin/Procedural-Planets-in-Unity
Procedural Planets/Assets/RNG.cs
5,693
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PlanetWars.Shared; namespace CSharpAgent { public class Agent : AgentBase { public Agent(string name, string endpoint) : base(name, endpoint){} /// <summary> /// Do your cool AI stuff /// </summary> /// <param name="gameState"></param> public override void Update(StatusResult gameState) { Console.WriteLine($"[{DateTime.Now.ToShortTimeString()}] Current Turn: {gameState.CurrentTurn}"); Console.WriteLine($"Owned Planets: {string.Join(", ", gameState.Planets.Where(p => p.OwnerId == MyId).Select(p => p.Id))}"); // find the first planet we don't own var targetPlanet = gameState.Planets.FirstOrDefault(p => p.OwnerId != MyId && p.OwnerId != -1); if (targetPlanet == null) return; Console.WriteLine($"Target Planet: {targetPlanet.Id}:{targetPlanet.NumberOfShips}"); // send available ships from each planet we own foreach (var planet in gameState.Planets.Where(p => p.OwnerId == MyId)) { var ships = planet.NumberOfShips - 1; if (ships > 0) { SendFleet(planet.Id, targetPlanet.Id, ships); } } } } }
35.75
137
0.569231
[ "BSD-3-Clause" ]
charij/PlanetWars
Agent-EnemyHammer/Agent.cs
1,432
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FEA3D.elem; namespace FEA3D.material { public class Material { // StressContainer state (plstrain/plstress/axisym/threed) protected String stressState; // Elasticity modulus public double e; // Poisson's ratio public double nu; // Thermal expansion protected double alpha; // Yield stress protected double sY; // Hardening coefficient protected double km; // Hardening power protected double mm; public static Material newMaterial(String matPhysLaw, String stressState) { if (matPhysLaw.Equals("elastic")) return new ElasticMaterial(stressState); else return new ElasticPlasticMaterial(stressState); } // Given strain increment at integration point ip // element elm, compute stress dsig increment public virtual void strainToStress(Element elm, int ip) { } // Set elastic properties public void setElasticProp(double e, double nu, double alpha) { this.e = e; this.nu = nu; this.alpha = alpha; } // Set plastic properties public void setPlasticProp(double sY, double km, double mm) { this.sY = sY; this.km = km; this.mm = mm; } // Returns Lame constant lambda public double getLambda() { return (stressState.Equals("plstress")) ? e * nu / ((1.0 + nu) * (1.0 - nu)) : e * nu / ((1.0 + nu) * (1.0 - 2.0 * nu)); } // Returns shear modulus public double getMu() { return 0.5 * e / (1.0 + nu); } // Returns Poisson's ratio public double getNu() { return nu; } // Returns thermal expansion coefficient public double getAlpha() { return alpha; } // Returns Youngs Modulus public double getElasticModulus() { return e; } // Compute elasticity matrix emat public virtual void elasticityMatrix(double[][] emat) { } } }
26.821429
132
0.568575
[ "Apache-2.0" ]
ravi-2912/3D-Finite-Element-Analysis
3D Finite Element Analysis/material/Material.cs
2,255
C#
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Conventions; using Xunit; namespace MongoDB.Bson.Tests.Serialization.Conventions { public class DelegateClassMapConventionTests { private class TestClass { public string FirstName { get; set; } } [Fact] public void Test() { var convention = new DelegateClassMapConvention("test", c => c.SetDiscriminator("blah")); Assert.Equal("test", convention.Name); var classMap = new BsonClassMap<TestClass>(); convention.Apply(classMap); Assert.Equal("blah", classMap.Discriminator); } } }
29.045455
101
0.683099
[ "Apache-2.0" ]
Anarh2404/mongo-csharp-driver
tests/MongoDB.Bson.Tests/Serialization/Conventions/DelegateClassMapConventionTests.cs
1,280
C#
using System; using System.Xml.Serialization; namespace EZOper.NetSiteUtilities.AopApi { /// <summary> /// AlipayTradeBatchRefundQueryModel Data Structure. /// </summary> [Serializable] public class AlipayTradeBatchRefundQueryModel : AopObject { /// <summary> /// 商户请求批量退款时传递的批次号。 trade_no和batch_no不能同时为空 /// </summary> [XmlElement("batch_no")] public string BatchNo { get; set; } /// <summary> /// 退款明细的支付宝交易号。 trade_no和batch_no不能同时为空 /// </summary> [XmlElement("trade_no")] public string TradeNo { get; set; } } }
25.12
61
0.611465
[ "MIT" ]
erikzhouxin/CSharpSolution
NetSiteUtilities/AopApi/Domain/AlipayTradeBatchRefundQueryModel.cs
712
C#
using System; using System.Runtime.InteropServices; namespace CoreAudioAPI { /// <summary> /// Provides access to the control value of a device-specific hardware control. /// </summary> /// <remarks> /// MSDN Reference: http://msdn.microsoft.com/en-us/library/dd371121.aspx /// </remarks> public partial interface IDeviceSpecificProperty { /// <summary> /// Gets the data type of the device-specific property. /// </summary> /// <param name="dataType">Receives the data type of the device-specific property value.</param> /// <returns>An HRESULT code indicating whether the operation succeeded of failed.</returns> [PreserveSig] int GetType( [Out] [MarshalAs(UnmanagedType.SysInt)] out IntPtr dataType); // TODO: Fix this, C++ is (VARTYPE *) /// <summary> /// Gets the value of the device-specific property. /// </summary> /// <param name="propertyValue">Receives the property value.</param> /// <param name="propertySize">Sends the size in bytes of the property value, then receives the actual size of the property value written to the buffer.</param> /// <returns>An HRESULT code indicating whether the operation succeeded of failed.</returns> [PreserveSig] int GetValue( [Out] [MarshalAs(UnmanagedType.SysInt)] out IntPtr propertyValue, [In, Out] [MarshalAs(UnmanagedType.U4)] ref UInt32 propertySize); /// <summary> /// Sets the value of the device-specific property. /// </summary> /// <param name="propertyValue">The property value.</param> /// <param name="propertySize">The property value size.</param> /// <param name="eventContext">A user context value that is passed to the notification callback.</param> /// <returns>An HRESULT code indicating whether the operation succeeded of failed.</returns> [PreserveSig] int SetValue( [In] [MarshalAs(UnmanagedType.SysInt)] IntPtr propertyValue, [In] [MarshalAs(UnmanagedType.U4)] UInt32 propertySize, [In, Optional] [MarshalAs(UnmanagedType.LPStruct)] Guid eventContext); /// <summary> /// Gets the 4-byte range of the device-specific property. /// </summary> /// <param name="propertyMin">Receives the minimum property value.</param> /// <param name="propertyMax">Receives the maximum property value.</param> /// <param name="propertyInc">Receives the stepping value between consecutive property values in the range.</param> /// <returns>An HRESULT code indicating whether the operation succeeded of failed.</returns> [PreserveSig] int Get4BRange( [Out] [MarshalAs(UnmanagedType.I4)] out Int32 propertyMin, [Out] [MarshalAs(UnmanagedType.I4)] out Int32 propertyMax, [Out] [MarshalAs(UnmanagedType.I4)] out Int32 propertyInc); } }
48.354839
168
0.646097
[ "MIT" ]
vuplea/CoreAudioAPI
Interfaces/IDeviceSpecificProperty.cs
3,000
C#
// <auto-generated /> using DatingApp.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace DatingApp.Data.Migrations { [DbContext(typeof(DataContext))] partial class DataContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.3"); modelBuilder.Entity("DatingApp.Entities.AppUser", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("UserName") .HasColumnType("TEXT"); b.HasKey("Id"); b.ToTable("Users"); }); #pragma warning restore 612, 618 } } }
28.8
69
0.575397
[ "MIT" ]
Yaret3000/DatingApp
DatingApp/Data/Migrations/DataContextModelSnapshot.cs
1,010
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 codebuild-2016-10-06.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.CodeBuild.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CodeBuild.Model.Internal.MarshallTransformations { /// <summary> /// UpdateWebhook Request Marshaller /// </summary> public class UpdateWebhookRequestMarshaller : IMarshaller<IRequest, UpdateWebhookRequest> , 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((UpdateWebhookRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateWebhookRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeBuild"); string target = "CodeBuild_20161006.UpdateWebhook"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-10-06"; 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.IsSetBranchFilter()) { context.Writer.WritePropertyName("branchFilter"); context.Writer.Write(publicRequest.BranchFilter); } if(publicRequest.IsSetBuildType()) { context.Writer.WritePropertyName("buildType"); context.Writer.Write(publicRequest.BuildType); } if(publicRequest.IsSetFilterGroups()) { context.Writer.WritePropertyName("filterGroups"); context.Writer.WriteArrayStart(); foreach(var publicRequestFilterGroupsListValue in publicRequest.FilterGroups) { context.Writer.WriteArrayStart(); foreach(var publicRequestFilterGroupsListValueListValue in publicRequestFilterGroupsListValue) { context.Writer.WriteObjectStart(); var marshaller = WebhookFilterMarshaller.Instance; marshaller.Marshall(publicRequestFilterGroupsListValueListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetProjectName()) { context.Writer.WritePropertyName("projectName"); context.Writer.Write(publicRequest.ProjectName); } if(publicRequest.IsSetRotateSecret()) { context.Writer.WritePropertyName("rotateSecret"); context.Writer.Write(publicRequest.RotateSecret); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateWebhookRequestMarshaller _instance = new UpdateWebhookRequestMarshaller(); internal static UpdateWebhookRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateWebhookRequestMarshaller Instance { get { return _instance; } } } }
37.295775
141
0.592145
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/CodeBuild/Generated/Model/Internal/MarshallTransformations/UpdateWebhookRequestMarshaller.cs
5,296
C#
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.ComponentModel.Composition; using System.Reflection; using System.Xml.Schema; using Sce.Atf; using Sce.Atf.Dom; using Sce.Sled.Shared; using Sce.Sled.Shared.Dom; namespace Sce.Sled.Lua.Dom { [Export(typeof(IInitializable))] [Export(typeof(SledLuaDomLoader))] [PartCreationPolicy(CreationPolicy.Shared)] class SledLuaDomLoader : XmlSchemaTypeLoader, IInitializable { [ImportingConstructor] public SledLuaDomLoader() { // Stop a compiler warning if (m_sledSchemaLoader == null) m_sledSchemaLoader = null; var assembly = Assembly.GetAssembly(typeof(SledLuaDomLoader)); var schemaSet = new XmlSchemaSet(); var sledSharedSchemaSet = GetSledSharedSchemaSet(); if (sledSharedSchemaSet != null) schemaSet.Add(sledSharedSchemaSet); var strm = assembly.GetManifestResourceStream(SledLuaUtil.LuaSchemaPath); if (strm != null) { // Load schema from file var schema = XmlSchema.Read(strm, null); schemaSet.Add(schema); } Load(schemaSet); } #region IInitializable Interface void IInitializable.Initialize() { // What's the correct way to get the base loader to contain // all the types from all the loaded schemas? // This is a temp solution to get items from Lua // schema loader into base schema loader foreach (var nodeType in TypeCollection.GetNodeTypes()) { var baseNodeType = m_sledSchemaLoader.GetNodeType(nodeType.Name); // If not null then base schema loader already contains // the node type and we don't want to add it if (baseNodeType != null) continue; m_sledSchemaLoader.AddNodeType(nodeType.Name, nodeType); } } #endregion #region XmlSchemaTypeLoader Overrides protected override void OnSchemaSetLoaded(XmlSchemaSet schemaSet) { var typeCollections = GetTypeCollections(); foreach (var typeCollection in typeCollections) { Namespace = typeCollection.TargetNamespace; TypeCollection = typeCollection; SledLuaSchema.Initialize(TypeCollection); SledLuaSchema.SledLuaCompileAttributeType.Type.Define(new ExtensionInfo<SledLuaCompileAttributeType>()); SledLuaSchema.SledLuaCompileConfigurationType.Type.Define(new ExtensionInfo<SledLuaCompileConfigurationType>()); SledLuaSchema.SledLuaCompileSettingsType.Type.Define(new ExtensionInfo<SledLuaCompileSettingsType>()); SledLuaSchema.SledLuaFunctionType.Type.Define(new ExtensionInfo<SledLuaFunctionType>()); SledLuaSchema.SledLuaVarNameTypePairType.Type.Define(new ExtensionInfo<SledLuaVarNameTypePairType>()); SledLuaSchema.SledLuaVarLookUpType.Type.Define(new ExtensionInfo<SledLuaVarLookUpType>()); SledLuaSchema.SledLuaProjectFilesWatchType.Type.Define(new ExtensionInfo<SledLuaProjectFilesWatchType>()); SledLuaSchema.SledLuaStateListType.Type.Define(new ExtensionInfo<SledLuaStateListType>()); SledLuaSchema.SledLuaStateType.Type.Define(new ExtensionInfo<SledLuaStateType>()); SledLuaSchema.SledLuaVarEnvListType.Type.Define(new ExtensionInfo<SledLuaVarEnvListType>()); SledLuaSchema.SledLuaVarEnvType.Type.Define(new ExtensionInfo<SledLuaVarEnvType>()); SledLuaSchema.SledLuaVarFilterNameType.Type.Define(new ExtensionInfo<SledLuaVarFilterNameType>()); SledLuaSchema.SledLuaVarFilterNamesType.Type.Define(new ExtensionInfo<SledLuaVarFilterNamesType>()); SledLuaSchema.SledLuaVarFiltersType.Type.Define(new ExtensionInfo<SledLuaVarFiltersType>()); SledLuaSchema.SledLuaVarFilterType.Type.Define(new ExtensionInfo<SledLuaVarFilterType>()); SledLuaSchema.SledLuaVarFilterTypesType.Type.Define(new ExtensionInfo<SledLuaVarFilterTypesType>()); SledLuaSchema.SledLuaVarGlobalType.Type.Define(new ExtensionInfo<SledLuaVarGlobalType>()); SledLuaSchema.SledLuaVarGlobalListType.Type.Define(new ExtensionInfo<SledLuaVarGlobalListType>()); SledLuaSchema.SledLuaVarLocalListType.Type.Define(new ExtensionInfo<SledLuaVarLocalListType>()); SledLuaSchema.SledLuaVarLocalType.Type.Define(new ExtensionInfo<SledLuaVarLocalType>()); SledLuaSchema.SledLuaVarUpvalueListType.Type.Define(new ExtensionInfo<SledLuaVarUpvalueListType>()); SledLuaSchema.SledLuaVarUpvalueType.Type.Define(new ExtensionInfo<SledLuaVarUpvalueType>()); SledLuaSchema.SledLuaVarWatchListType.Type.Define(new ExtensionInfo<SledLuaVarWatchListType>()); SetupStringBasedEnumeration(SledLuaSchema.SledLuaVarLookUpType.scopeAttribute, typeof(SledLuaVarScopeType)); SetupStringBasedEnumeration(SledLuaSchema.SledLuaVarLookUpType.contextAttribute, typeof(SledLuaVarLookUpContextType)); SetupStringBasedEnumeration(SledLuaSchema.SledLuaProjectFilesWatchType.scopeAttribute, typeof(SledLuaVarScopeType)); SetupStringBasedEnumeration(SledLuaSchema.SledLuaProjectFilesWatchType.contextAttribute, typeof(SledLuaVarLookUpContextType)); break; // Only one namespace } } #endregion public string Namespace { get; private set; } public XmlSchemaTypeCollection TypeCollection { get; private set; } /// <summary> /// Set up any enumerations whose values are stored as strings /// </summary> /// <param name="attribute"></param> /// <param name="enumType"></param> public static void SetupStringBasedEnumeration(AttributeInfo attribute, Type enumType) { var strings = Enum.GetNames(enumType); AttributeRule rule = new StringEnumRule(strings); attribute.AddRule(rule); attribute.DefaultValue = strings[0]; } private static XmlSchemaSet GetSledSharedSchemaSet() { var assembly = Assembly.GetAssembly(typeof(SledShared)); var schemaSet = new XmlSchemaSet(); var strm = assembly.GetManifestResourceStream(SledShared.SchemaPath); if (strm != null) { // Load schema from file var schema = XmlSchema.Read(strm, null); schemaSet.Add(schema); } return schemaSet; } [Import] private SledSharedSchemaLoader m_sledSchemaLoader; } }
44.506329
142
0.665529
[ "Apache-2.0" ]
MasterScott/SLED
tool/SledLuaLanguagePlugin/Dom/SledLuaDomLoader.cs
7,032
C#
// <auto-generated /> using System; using Aguacongas.IdentityServer.EntityFramework.Store; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; #nullable disable namespace Aguacongas.TheIdServer.Oracle.Migrations.OperationalDb { [DbContext(typeof(OperationalDbContext))] [Migration("20220114083050_Ciba")] partial class Ciba { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.8"); modelBuilder.Entity("Aguacongas.IdentityServer.KeysRotation.EntityFrameworkCore.KeyRotationKey", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("FriendlyName") .HasColumnType("nclob"); b.Property<string>("Xml") .HasColumnType("nclob"); b.HasKey("Id"); b.ToTable("KeyRotationKeys"); }); modelBuilder.Entity("Aguacongas.IdentityServer.Store.Entity.AuthorizationCode", b => { b.Property<string>("Id") .HasColumnType("nvarchar2(450)"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nclob"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp"); b.Property<string>("Data") .HasColumnType("nclob"); b.Property<DateTime?>("Expiration") .HasColumnType("timestamp"); b.Property<DateTime?>("ModifiedAt") .HasColumnType("timestamp"); b.Property<string>("SessionId") .HasColumnType("nclob"); b.Property<string>("UserId") .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.HasKey("Id"); b.ToTable("AuthorizationCodes"); }); modelBuilder.Entity("Aguacongas.IdentityServer.Store.Entity.DeviceCode", b => { b.Property<string>("Id") .HasColumnType("nvarchar2(450)"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nclob"); b.Property<string>("Code") .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp"); b.Property<string>("Data") .HasColumnType("nclob"); b.Property<DateTime>("Expiration") .HasColumnType("timestamp"); b.Property<DateTime?>("ModifiedAt") .HasColumnType("timestamp"); b.Property<string>("SubjectId") .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.Property<string>("UserCode") .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.HasKey("Id"); b.ToTable("DeviceCodes"); }); modelBuilder.Entity("Aguacongas.IdentityServer.Store.Entity.OneTimeToken", b => { b.Property<string>("Id") .HasColumnType("nvarchar2(450)"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nclob"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp"); b.Property<string>("Data") .HasColumnType("nclob"); b.Property<DateTime?>("Expiration") .HasColumnType("timestamp"); b.Property<DateTime?>("ModifiedAt") .HasColumnType("timestamp"); b.Property<string>("SessionId") .HasColumnType("nclob"); b.Property<string>("UserId") .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.HasKey("Id"); b.ToTable("OneTimeTokens"); }); modelBuilder.Entity("Aguacongas.IdentityServer.Store.Entity.ReferenceToken", b => { b.Property<string>("Id") .HasColumnType("nvarchar2(450)"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nclob"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp"); b.Property<string>("Data") .HasColumnType("nclob"); b.Property<DateTime?>("Expiration") .HasColumnType("timestamp"); b.Property<DateTime?>("ModifiedAt") .HasColumnType("timestamp"); b.Property<string>("SessionId") .HasColumnType("nclob"); b.Property<string>("UserId") .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.HasKey("Id"); b.ToTable("ReferenceTokens"); }); modelBuilder.Entity("Aguacongas.IdentityServer.Store.Entity.BackChannelAuthenticationRequest", b => { b.Property<string>("Id") .HasColumnType("nvarchar2(450)"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nclob"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp"); b.Property<string>("Data") .HasColumnType("nclob"); b.Property<DateTime?>("Expiration") .HasColumnType("timestamp"); b.Property<DateTime?>("ModifiedAt") .HasColumnType("timestamp"); b.Property<string>("SessionId") .HasColumnType("nclob"); b.Property<string>("UserId") .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.HasKey("Id"); b.ToTable("BackChannelAuthenticationRequest"); }); modelBuilder.Entity("Aguacongas.IdentityServer.Store.Entity.RefreshToken", b => { b.Property<string>("Id") .HasColumnType("nvarchar2(450)"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nclob"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp"); b.Property<string>("Data") .HasColumnType("nclob"); b.Property<DateTime?>("Expiration") .HasColumnType("timestamp"); b.Property<DateTime?>("ModifiedAt") .HasColumnType("timestamp"); b.Property<string>("SessionId") .HasColumnType("nclob"); b.Property<string>("UserId") .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.HasKey("Id"); b.ToTable("RefreshTokens"); }); modelBuilder.Entity("Aguacongas.IdentityServer.Store.Entity.UserConsent", b => { b.Property<string>("Id") .HasColumnType("nvarchar2(450)"); b.Property<string>("ClientId") .IsRequired() .HasColumnType("nclob"); b.Property<DateTime>("CreatedAt") .HasColumnType("timestamp"); b.Property<string>("Data") .HasColumnType("nclob"); b.Property<DateTime?>("Expiration") .HasColumnType("timestamp"); b.Property<DateTime?>("ModifiedAt") .HasColumnType("timestamp"); b.Property<string>("SessionId") .HasColumnType("nclob"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar2(200)") .HasMaxLength(200); b.HasKey("Id"); b.ToTable("UserConstents"); }); modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("FriendlyName") .HasColumnType("nclob"); b.Property<string>("Xml") .HasColumnType("nclob"); b.HasKey("Id"); b.ToTable("DataProtectionKeys"); }); #pragma warning restore 612, 618 } } } }
31.818792
113
0.48186
[ "Apache-2.0" ]
aguacongas/TheIdServer
src/IdentityServer/Migrations/Aguacongas.TheIdServer.Migrations.Oracle/Migrations/OperationalDb/20220114083050_Ciba.Designer.cs
9,484
C#
using System; namespace Joke.Joke.Tree { public interface IVisitor { void Visit(IType type) => throw new NotImplementedException(); void Visit(IntersectionType type); void Visit(UnionType type); void Visit(TupleType type); void Visit(NominalType type); void Visit(Class @class); void Visit(LambdaType lambda); void Visit(ThisType @this); void Visit(IExpression expression) => throw new NotImplementedException(); void Visit(Unit unit); void Visit(Field field); void Visit(Method method); } }
26.166667
83
0.611465
[ "MIT" ]
knutjelitto/Joke
Joke.Joke/Tree/Visiting/IVisitor.cs
630
C#
using System; using CUE4Parse.UE4.Assets.Readers; using CUE4Parse.UE4.Objects.Core.i18N; using Newtonsoft.Json; namespace CUE4Parse.UE4.Assets.Objects { [JsonConverter(typeof(TextPropertyConverter))] public class TextProperty : FPropertyTagType<FText> { public TextProperty(FAssetArchive Ar, ReadType type) { Value = type switch { ReadType.ZERO => new FText(0, ETextHistoryType.None, new FTextHistory.None()), _ => new FText(Ar) }; } } public class TextPropertyConverter : JsonConverter<TextProperty> { public override void WriteJson(JsonWriter writer, TextProperty value, JsonSerializer serializer) { serializer.Serialize(writer, value.Value); } public override TextProperty ReadJson(JsonReader reader, Type objectType, TextProperty existingValue, bool hasExistingValue, JsonSerializer serializer) { throw new NotImplementedException(); } } }
31.029412
132
0.645498
[ "MIT" ]
Mrzzbelladonna/ProSwapper
CUE4Parse/CUE4Parse/UE4/Assets/Objects/Properties/TextProperty.cs
1,057
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Azure.Core.Testing; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Azure.AI.TextAnalytics.Samples { [LiveOnly] public partial class TextAnalyticsSamples { [Test] public void ExtractKeyPhrasesBatch() { string endpoint = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_ENDPOINT"); string apiKey = Environment.GetEnvironmentVariable("TEXT_ANALYTICS_API_KEY"); // Instantiate a client that will be used to call the service. var client = new TextAnalyticsClient(new Uri(endpoint), new TextAnalyticsApiKeyCredential(apiKey)); #region Snippet:TextAnalyticsSample3ExtractKeyPhrasesBatch var inputs = new List<TextDocumentInput> { new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.") { Language = "en", }, new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.") { Language = "en", }, new TextDocumentInput("3", "My cat might need to see a veterinarian.") { Language = "en", } }; ExtractKeyPhrasesResultCollection results = client.ExtractKeyPhrasesBatch(inputs, new TextAnalyticsRequestOptions { IncludeStatistics = true }); #endregion int i = 0; Debug.WriteLine($"Results of Azure Text Analytics \"Extract Key Phrases\" Model, version: \"{results.ModelVersion}\""); Debug.WriteLine(""); foreach (ExtractKeyPhrasesResult result in results) { TextDocumentInput document = inputs[i++]; Debug.WriteLine($"On document (Id={document.Id}, Language=\"{document.Language}\", Text=\"{document.Text}\"):"); if (result.HasError) { Debug.WriteLine($" Document error: {result.Error.Code}."); Debug.WriteLine($" Message: {result.Error.Message}."); } else { Debug.WriteLine($" Extracted the following {result.KeyPhrases.Count()} key phrases:"); foreach (string keyPhrase in result.KeyPhrases) { Debug.WriteLine($" {keyPhrase}"); } Debug.WriteLine($" Document statistics:"); Debug.WriteLine($" Character count: {result.Statistics.CharacterCount}"); Debug.WriteLine($" Transaction count: {result.Statistics.TransactionCount}"); Debug.WriteLine(""); } } Debug.WriteLine($"Batch operation statistics:"); Debug.WriteLine($" Document count: {results.Statistics.DocumentCount}"); Debug.WriteLine($" Valid document count: {results.Statistics.ValidDocumentCount}"); Debug.WriteLine($" Invalid document count: {results.Statistics.InvalidDocumentCount}"); Debug.WriteLine($" Transaction count: {results.Statistics.TransactionCount}"); Debug.WriteLine(""); } } }
41.141176
156
0.565342
[ "MIT" ]
LijuanZ/azure-sdk-for-net
sdk/textanalytics/Azure.AI.TextAnalytics/tests/samples/Sample3_ExtractKeyPhrasesBatch.cs
3,499
C#
namespace Book.ViewModels.Samples.Chapter17.Sample02 { using System; using ReactiveUI; public sealed class TopicViewModel { private readonly string name; private readonly Func<IRoutableViewModel> createViewModel; public TopicViewModel( string name, Func<IRoutableViewModel> createViewModel) { this.name = name; this.createViewModel = createViewModel; } public string Name => this.name; public Func<IRoutableViewModel> CreateViewModel => this.createViewModel; } }
25.652174
80
0.644068
[ "MIT" ]
AlexejLiebenthal/YouIandReactiveUI
ViewModels/Samples/Chapter 17/Sample 02/TopicViewModel.cs
590
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** ** Purpose: For writing text to streams in a particular ** encoding. ** ** ===========================================================*/ using System; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Permissions; using System.Runtime.Serialization; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. // [Serializable] [ComVisible(true)] public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. internal const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; private const Int32 DontCopyOnWriteLineThreshold = 512; // Bit bucket - Null has no backing store. Non closable. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true); private Stream stream; private Encoding encoding; private Encoder encoder; private byte[] byteBuffer; private char[] charBuffer; private int charPos; private int charLen; private bool autoFlush; private bool haveWrittenPreamble; private bool closable; #if MDA_SUPPORTED [NonSerialized] // For StreamWriterBufferedDataLost MDA private MdaHelper mdaHelper; #endif // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. [NonSerialized] private volatile Task _asyncWriteTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. Task t = _asyncWriteTask; if (t != null && !t.IsCompleted) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress")); } // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the // internal StreamWriter's state to be irrecoverable as it would have buffered the // illegal chars and any subsequent call to Flush() would hit the encoding error again. // Even Close() will hit the exception as it would try to flush the unwritten data. // Maybe we can add a DiscardBufferedData() method to get out of such situation (like // StreamReader though for different reason). Either way, the buffered data will be lost! private static volatile Encoding _UTF8NoBOM; internal static Encoding UTF8NoBOM { [FriendAccessAllowed] get { if (_UTF8NoBOM == null) { // No need for double lock - we just want to avoid extra // allocations in the common case. UTF8Encoding noBOM = new UTF8Encoding(false, true); Thread.MemoryBarrier(); _UTF8NoBOM = noBOM; } return _UTF8NoBOM; } } internal StreamWriter(): base(null) { // Ask for CurrentCulture all the time } public StreamWriter(Stream stream) : this(stream, UTF8NoBOM, DefaultBufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, DefaultBufferSize, false) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter(Stream stream, Encoding encoding, int bufferSize) : this(stream, encoding, bufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : base(null) // Ask for CurrentCulture all the time { if (stream == null || encoding == null) throw new ArgumentNullException((stream == null ? "stream" : "encoding")); if (!stream.CanWrite) throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable")); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); Init(stream, encoding, bufferSize, leaveOpen); } public StreamWriter(String path) : this(path, false, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(String path, bool append) : this(path, append, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(String path, bool append, Encoding encoding) : this(path, append, encoding, DefaultBufferSize) { } [System.Security.SecuritySafeCritical] public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) { } [System.Security.SecurityCritical] internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost) : base(null) { // Ask for CurrentCulture all the time if (path == null) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); Stream stream = CreateFile(path, append, checkHost); Init(stream, encoding, bufferSize, false); } [System.Security.SecuritySafeCritical] private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen) { this.stream = streamArg; this.encoding = encodingArg; this.encoder = encoding.GetEncoder(); if (bufferSize < MinBufferSize) bufferSize = MinBufferSize; charBuffer = new char[bufferSize]; byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)]; charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if (stream.CanSeek && stream.Position > 0) haveWrittenPreamble = true; closable = !shouldLeaveOpen; #if MDA_SUPPORTED if (Mda.StreamWriterBufferedDataLost.Enabled) { String callstack = null; if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack) callstack = Environment.GetStackTrace(null, false); mdaHelper = new MdaHelper(this, callstack); } #endif } [System.Security.SecurityCritical] private static Stream CreateFile(String path, bool append, bool checkHost) { FileMode mode = append? FileMode.Append: FileMode.Create; FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost); return f; } public override void Close() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if (stream != null) { // Note: flush on the underlying stream can throw (ex., low disk space) if (disposing || (LeaveOpen && stream is __ConsoleStream)) { CheckAsyncTaskInProgress(); Flush(true, true); #if MDA_SUPPORTED // Disable buffered data loss mda if (mdaHelper != null) GC.SuppressFinalize(mdaHelper); #endif } } } finally { // Dispose of our resources if this StreamWriter is closable. // Note: Console.Out and other such non closable streamwriters should be left alone if (!LeaveOpen && stream != null) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if (disposing) stream.Close(); } finally { stream = null; byteBuffer = null; charBuffer = null; encoding = null; encoder = null; charLen = 0; base.Dispose(disposing); } } } } public override void Flush() { CheckAsyncTaskInProgress(); Flush(true, true); } private void Flush(bool flushStream, bool flushEncoder) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (stream == null) __Error.WriterClosed(); // Perf boost for Flush on non-dirty writers. if (charPos==0 && ((!flushStream && !flushEncoder) || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)) return; if (!haveWrittenPreamble) { haveWrittenPreamble = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) stream.Write(preamble, 0, preamble.Length); } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); charPos = 0; if (count > 0) stream.Write(byteBuffer, 0, count); // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) stream.Flush(); } public virtual bool AutoFlush { get { return autoFlush; } set { CheckAsyncTaskInProgress(); autoFlush = value; if (value) Flush(true, false); } } public virtual Stream BaseStream { get { return stream; } } internal bool LeaveOpen { get { return !closable; } } internal bool HaveWrittenPreamble { set { haveWrittenPreamble= value; } } public override Encoding Encoding { get { return encoding; } } public override void Write(char value) { CheckAsyncTaskInProgress(); if (charPos == charLen) Flush(false, false); charBuffer[charPos] = value; charPos++; if (autoFlush) Flush(true, false); } public override void Write(char[] buffer) { // This may be faster than the one with the index & count since it // has to do less argument checking. if (buffer==null) return; CheckAsyncTaskInProgress(); int index = 0; int count = buffer.Length; while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } public override void Write(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); CheckAsyncTaskInProgress(); while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } public override void Write(String value) { if (value != null) { CheckAsyncTaskInProgress(); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } } #region Task based Async APIs [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, Char value, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = value; charPos++; if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(String value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(value); if (value != null) { if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } else { return Task.CompletedTask; } } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, String value, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { Contract.Requires(value != null); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(buffer, index, count); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, Char[] buffer, Int32 index, Int32 count, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { Contract.Requires(count == 0 || (count > 0 && buffer != null)); Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count)); while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(String value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(buffer, index, count); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task FlushAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overriden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.FlushAsync(); // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = FlushAsyncInternal(true, true, charBuffer, charPos); _asyncWriteTask = task; return task; } private Int32 CharPos_Prop { set { this.charPos = value; } } private bool HaveWrittenPreamble_Prop { set { this.haveWrittenPreamble = value; } } private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, Char[] sCharBuffer, Int32 sCharPos) { // Perf boost for Flush on non-dirty writers. if (sCharPos == 0 && !flushStream && !flushEncoder) return Task.CompletedTask; Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, this.haveWrittenPreamble, this.encoding, this.encoder, this.byteBuffer, this.stream); this.charPos = 0; return flushTask; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, Char[] charBuffer, Int32 charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream) { if (!haveWrittenPreamble) { _this.HaveWrittenPreamble_Prop = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false); } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); if (count > 0) await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false); // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) await stream.FlushAsync().ConfigureAwait(false); } #endregion #if MDA_SUPPORTED // StreamWriterBufferedDataLost MDA // Instead of adding a finalizer to StreamWriter for detecting buffered data loss // (ie, when the user forgets to call Close/Flush on the StreamWriter), we will // have a separate object with normal finalization semantics that maintains a // back pointer to this StreamWriter and alerts about any data loss private sealed class MdaHelper { private StreamWriter streamWriter; private String allocatedCallstack; // captures the callstack when this streamwriter was allocated internal MdaHelper(StreamWriter sw, String cs) { streamWriter = sw; allocatedCallstack = cs; } // Finalizer ~MdaHelper() { // Make sure people closed this StreamWriter, exclude StreamWriter::Null. if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) { String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>"; String callStack = allocatedCallstack; if (callStack == null) callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled"); String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack); Mda.StreamWriterBufferedDataLost.ReportError(message); } } } // class MdaHelper #endif // MDA_SUPPORTED } // class StreamWriter } // namespace
43.583527
163
0.571482
[ "MIT" ]
CyberSys/coreclr-mono
src/mscorlib/src/System/IO/StreamWriter.cs
37,569
C#
#if !UNITY_EDITOR && UNITY_WEBGL using System; using System.Collections.Generic; using System.Runtime.InteropServices; using AOT; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Sweet.Unity.Amazon.JavaScript { public sealed class JavaScriptSQSClient : IAmazonSQS { private static readonly JsonSerializerSettings _ErrorSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; private static readonly Dictionary<int, CallParameters> _CallParameters = new Dictionary<int, CallParameters>(); private static int _CallId; private int _nativeId; public JavaScriptSQSClient(ICredentials credentials, string region) { _nativeId = SQS_Construct( credentials.AccessKey, credentials.SecretKey, credentials.Token, region); } ~JavaScriptSQSClient() { SQS_Destroy(_nativeId); } [DllImport("__Internal")] private static extern int SQS_Construct(string accessKey, string secretKey, string token, string region); [DllImport("__Internal")] private static extern void SQS_Destroy(int nativeId); [DllImport("__Internal")] private static extern void SQS_DeleteMessageAsync(int nativeId, string request, WebGLCallback callback, int callId); [DllImport("__Internal")] private static extern void SQS_DeleteMessageBatchAsync(int nativeId, string request, WebGLCallback callback, int callId); [DllImport("__Internal")] private static extern void SQS_ReceiveMessageAsync(int nativeId, string request, WebGLCallback callback, int callId); public void DeleteMessageAsync(SQSDeleteMessageRequest request, ServiceCallback<SQSDeleteMessageRequest, SQSDeleteMessageResponse> callback) { string requestJson = JsonConvert.SerializeObject(request); _CallParameters[_CallId] = new CallParameters { Request = request, Callback = callback }; SQS_DeleteMessageAsync(_nativeId, requestJson, DeleteMessageCallback, _CallId++); } [MonoPInvokeCallback(typeof(WebGLCallback))] private static void DeleteMessageCallback(int callId, string result, int isError) { CallParameters callParameters = _CallParameters[callId]; _CallParameters.Remove(callId); var request = (SQSDeleteMessageRequest)callParameters.Request; var callback = (ServiceCallback<SQSDeleteMessageRequest, SQSDeleteMessageResponse>)callParameters.Callback; callback(new ServiceResult<SQSDeleteMessageRequest, SQSDeleteMessageResponse>( request, isError == 1 ? null : JsonConvert.DeserializeObject<SQSDeleteMessageResponse>(result), isError == 1 ? new WebGLServiceErrorException(JsonConvert.DeserializeObject<WebGLServiceError>(result, _ErrorSerializerSettings)) : null )); } public void DeleteMessageBatchAsync(SQSDeleteMessageBatchRequest request, ServiceCallback<SQSDeleteMessageBatchRequest, SQSDeleteMessageBatchResponse> callback) { string requestJson = JsonConvert.SerializeObject(request); _CallParameters[_CallId] = new CallParameters { Request = request, Callback = callback }; SQS_DeleteMessageBatchAsync(_nativeId, requestJson, DeleteMessageBatchCallback, _CallId++); } [MonoPInvokeCallback(typeof(WebGLCallback))] private static void DeleteMessageBatchCallback(int callId, string result, int isError) { CallParameters callParameters = _CallParameters[callId]; _CallParameters.Remove(callId); var request = (SQSDeleteMessageBatchRequest)callParameters.Request; var callback = (ServiceCallback<SQSDeleteMessageBatchRequest, SQSDeleteMessageBatchResponse>)callParameters.Callback; callback(new ServiceResult<SQSDeleteMessageBatchRequest, SQSDeleteMessageBatchResponse>( request, isError == 1 ? null : JsonConvert.DeserializeObject<SQSDeleteMessageBatchResponse>(result), isError == 1 ? new WebGLServiceErrorException(JsonConvert.DeserializeObject<WebGLServiceError>(result, _ErrorSerializerSettings)) : null )); } public void ReceiveMessageAsync(SQSReceiveMessageRequest request, ServiceCallback<SQSReceiveMessageRequest, SQSReceiveMessageResponse> callback) { string requestJson = JsonConvert.SerializeObject(request); _CallParameters[_CallId] = new CallParameters { Request = request, Callback = callback }; SQS_ReceiveMessageAsync(_nativeId, requestJson, ReceiveMessageCallback, _CallId++); } [MonoPInvokeCallback(typeof(WebGLCallback))] private static void ReceiveMessageCallback(int callId, string result, int isError) { CallParameters callParameters = _CallParameters[callId]; _CallParameters.Remove(callId); var request = (SQSReceiveMessageRequest)callParameters.Request; var callback = (ServiceCallback<SQSReceiveMessageRequest, SQSReceiveMessageResponse>)callParameters.Callback; callback(new ServiceResult<SQSReceiveMessageRequest, SQSReceiveMessageResponse>( request, isError == 1 ? null : JsonConvert.DeserializeObject<SQSReceiveMessageResponse>(result), isError == 1 ? new WebGLServiceErrorException(JsonConvert.DeserializeObject<WebGLServiceError>(result, _ErrorSerializerSettings)) : null )); } private struct CallParameters { public ServiceRequest Request; public Delegate Callback; } } } #endif
45.446154
177
0.699729
[ "MIT" ]
SweetDigitalEntertainment/aws-sdk
src/SQS/JavaScriptSQSClient.cs
5,908
C#
using System; using System.Collections.Generic; namespace OceanChip.Queue.Protocols.Brokers { [Serializable] public class BrokerConsumerListInfo { public BrokerInfo BrokerInfo { get; set; } public IList<ConsumerInfo> ConsumerList { get; set; } public BrokerConsumerListInfo() { this.ConsumerList = new List<ConsumerInfo>(); } } }
23.529412
61
0.65
[ "Apache-2.0" ]
OceanChip/OQueue
OQueue/Protocols/NameServers/BrokerConsumerListInfo.cs
402
C#
using System; namespace CHD.Common.Breaker { public sealed class Breaker<TException> : IBreaker where TException : Exception { private volatile bool _shouldBreak = false; public string BreakMessage { get; private set; } public bool ShouldBreak { get { return _shouldBreak; } } public Breaker( ) { } public void FireBreak( string message = "" ) { BreakMessage = message; _shouldBreak = true; } public void ResetBreak() { BreakMessage = string.Empty; _shouldBreak = false; } public void RaiseExceptionIfBreak(string message = "") { if (!_shouldBreak) { return; } var prefix = string.IsNullOrEmpty(BreakMessage) ? "Unspecified break signal: " : BreakMessage; throw (TException)Activator.CreateInstance( typeof(TException), new object[] { string.Format("{0} {1}", prefix, message) } ); } } }
22.354839
107
0.422078
[ "MIT" ]
lsoft/CHD
CHD.Common/Breaker/Breaker.cs
1,388
C#
using System; using System.Diagnostics.Contracts; using System.Security; using System.Threading; namespace Helios.Concurrency { /// <summary> /// An instanced, dedicated thread pool. /// </summary> internal class DedicatedThreadPool : IDisposable { public DedicatedThreadPool(DedicatedThreadPoolSettings settings) { Settings = settings; WorkQueue = new ThreadPoolWorkQueue(); } public DedicatedThreadPoolSettings Settings { get; private set; } public int ThreadCount { get { return Settings.NumThreads; } } public ThreadType ThreadType { get { return Settings.ThreadType; } } /// <summary> /// The global work queue, shared by all threads. /// /// Each local thread has its own work-stealing local queue. /// </summary> public ThreadPoolWorkQueue WorkQueue { get; private set; } public bool WasDisposed { get; private set; } private volatile bool _shutdownRequested; private void Shutdown() { _shutdownRequested = true; } private volatile int numOutstandingThreadRequests = 0; public bool EnqueueWorkItem(Action callback) { bool success = true; if (callback != null) { // // If we are able to create the workitem, we need to get it in the queue without being interrupted // by a ThreadAbortException. // try { } finally { var heliosActionCallback = new ActionWorkItem(callback); WorkQueue.Enqueue(heliosActionCallback, false); EnsureThreadRequested(); success = true; } } else { throw new ArgumentNullException("callback"); } return success; } /// <summary> /// Method run internally by each worker thread /// </summary> private bool Dispatch() { var workQueue = WorkQueue; // // Update our records to indicate that an outstanding request for a thread has now been fulfilled. // From this point on, we are responsible for requesting another thread if we stop working for any // reason, and we believe there might still be work in the queue. MarkThreadRequestSatisfied(); bool needAnotherThread = true; IHeliosWorkItem workItem = null; try { //Set up thread-local data ThreadPoolWorkQueueThreadLocals tl = workQueue.EnsureCurrentThreadHasQueue(); while (!_shutdownRequested && tl.ConsecutiveQueueMissCount < workQueue.QueueMissUpperLimit) //look for work until explicitly shut down or too many queue misses { bool missedSteal = false; workQueue.Dequeue(tl, out workItem, out missedSteal); try { } finally { if (workItem == null) { // // No work. We're going to return to the VM once we leave this protected region. // If we missed a steal, though, there may be more work in the queue. // Instead of looping around and trying again, we'll just request another thread. This way // we won't starve other AppDomains while we spin trying to get locks, and hopefully the thread // that owns the contended work-stealing queue will pick up its own workitems in the meantime, // which will be more efficient than this thread doing it anyway. // needAnotherThread = missedSteal; } else { // // If we found work, there may be more work. Ask for another thread so that the other work can be processed // in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue. // EnsureThreadRequested(); } } if (workItem == null) { tl.IncrementQueueMiss(); } else //execute our work { tl.ResetQueueMiss(); workItem.ExecuteWorkItem(); workItem = null; } } return true; } finally { //had an exception in the course of executing some work, and this thread is going to die. if(needAnotherThread) EnsureThreadRequested(); } //should never hit this code, unless something catastrophically bad happened (like an aborted thread) Contract.Assert(false); return true; } internal void RequestWorkerThread() { //don't acknowledge thread create requests when disposing or stopping if (!_shutdownRequested) { var thread = new Thread(_ => Dispatch()) { IsBackground = ThreadType == ThreadType.Background }; thread.Start(); } } [SecurityCritical] internal void EnsureThreadRequested() { // // If we have not yet requested #procs threads from the VM, then request a new thread. // Note that there is a separate count in the VM which will also be incremented in this case, // which is handled by RequestWorkerThread. // int count = numOutstandingThreadRequests; while (count < ThreadCount) { int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count); if (prev == count) { RequestWorkerThread(); break; } count = prev; } } [SecurityCritical] internal void MarkThreadRequestSatisfied() { // // The VM has called us, so one of our outstanding thread requests has been satisfied. // Decrement the count so that future calls to EnsureThreadRequested will succeed. // Note that there is a separate count in the VM which has already been decremented by the VM // by the time we reach this point. // int count = numOutstandingThreadRequests; while (count > 0) { int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count); if (prev == count) { break; } count = prev; } } #region IDisposable members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool isDisposing) { if (!WasDisposed) { if (isDisposing) { Shutdown(); } } WasDisposed = true; } #endregion } }
35.630631
175
0.495954
[ "Apache-2.0" ]
rogeralsing/DedicatedThreadPool
src/core/Helios.DedicatedThreadPool/ThreadPool.cs
7,912
C#
using System.IO; using System.Numerics; using ProjEuler; using ProjEuler.Resources; namespace ProjectEuler.adventOfCode._2018 { public class Day01 : IProblem { public Day01() { } private string MyFunc(StreamReader sr) { var result = new BigInteger(); while (!sr.EndOfStream) { result += BigInteger.Parse(sr.ReadLine()); } return result.ToString(); } private string FirstAttempt() { return Util.ReadEmbeddedFile("ProjectEuler.Resources.Advent01.txt", MyFunc); } public Answer Solution() { var result = FirstAttempt(); return new Answer(){Description = result}; } } }
20.666667
88
0.531017
[ "MIT" ]
davemfletcher/ProjectEuler
ProjectEuler/adventOfCode/2018/Day01.cs
808
C#
//----------------------------------------------------------------------- // <copyright file="VersionInformationWindow.xaml.cs" company="dc1394's software"> // Copyright © 2014-2018 @dc1394 All Rights Reserved. // </copyright> //----------------------------------------------------------------------- namespace ASB2 { using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Navigation; using MyLogic; /// <summary> /// VersionInformationWindow.xaml の相互作用ロジック /// </summary> public partial class VersionInformationWindow { #region 構築 /// <summary> /// コンストラクタ /// </summary> internal VersionInformationWindow() { this.InitializeComponent(); } #endregion 構築 #region イベントハンドラ /// <summary> /// Twitterの私のページに対するハイパーリンクをクリックしたとき呼び出される /// </summary> /// <param name="sender">The parameter is not used.</param> /// <param name="e">The parameter is not used.</param> private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { Process.Start(e.Uri.AbsoluteUri); e.Handled = true; } /// <summary> /// 「readme.txtを見る」ボタンをクリックしたとき呼び出される /// </summary> /// <param name="sender">The parameter is not used.</param> /// <param name="e">The parameter is not used.</param> private void OpenTextFileButton_Click(object sender, RoutedEventArgs e) { try { Process.Start("readme.txt"); } catch (Win32Exception) { MyError.CallErrorMessageBox($"カレントフォルダにreadme.txtが見つかりません。{Environment.NewLine}readme.txtを削除しないで下さい。"); } } #endregion イベントハンドラ } }
29.430769
119
0.533194
[ "Unlicense" ]
dc1394/ASB2
ASB2/VersionInformationWindow.xaml.cs
2,156
C#
using System.Reflection; using System.Runtime.InteropServices; // 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("d99fe4cd-0566-43f0-a339-b6fd7e603d10")]
44.6
84
0.775785
[ "Apache-2.0" ]
ArtemGontar/aws-logging-dotnet
src/AWS.Logger.Core/Properties/AssemblyInfo.cs
448
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.Cdn.Latest { [Obsolete(@"The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:cdn:getRule'.")] public static class GetRule { /// <summary> /// Friendly Rules name mapping to the any Rules or secret related information. /// Latest API Version: 2020-09-01. /// </summary> public static Task<GetRuleResult> InvokeAsync(GetRuleArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetRuleResult>("azure-native:cdn/latest:getRule", args ?? new GetRuleArgs(), options.WithVersion()); } public sealed class GetRuleArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the CDN profile which is unique within the resource group. /// </summary> [Input("profileName", required: true)] public string ProfileName { get; set; } = null!; /// <summary> /// Name of the Resource group within the Azure subscription. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// Name of the delivery rule which is unique within the endpoint. /// </summary> [Input("ruleName", required: true)] public string RuleName { get; set; } = null!; /// <summary> /// Name of the rule set under the profile. /// </summary> [Input("ruleSetName", required: true)] public string RuleSetName { get; set; } = null!; public GetRuleArgs() { } } [OutputType] public sealed class GetRuleResult { /// <summary> /// A list of actions that are executed when all the conditions of a rule are satisfied. /// </summary> public readonly ImmutableArray<object> Actions; /// <summary> /// A list of conditions that must be matched for the actions to be executed /// </summary> public readonly ImmutableArray<object> Conditions; public readonly string DeploymentStatus; /// <summary> /// Resource ID. /// </summary> public readonly string Id; /// <summary> /// If this rule is a match should the rules engine continue running the remaining rules or stop. If not present, defaults to Continue. /// </summary> public readonly string? MatchProcessingBehavior; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// The order in which the rules are applied for the endpoint. Possible values {0,1,2,3,………}. A rule with a lesser order will be applied before a rule with a greater order. Rule with order 0 is a special rule. It does not require any condition and actions listed in it will always be applied. /// </summary> public readonly int Order; /// <summary> /// Provisioning status /// </summary> public readonly string ProvisioningState; /// <summary> /// Read only system data /// </summary> public readonly Outputs.SystemDataResponse SystemData; /// <summary> /// Resource type. /// </summary> public readonly string Type; [OutputConstructor] private GetRuleResult( ImmutableArray<object> actions, ImmutableArray<object> conditions, string deploymentStatus, string id, string? matchProcessingBehavior, string name, int order, string provisioningState, Outputs.SystemDataResponse systemData, string type) { Actions = actions; Conditions = conditions; DeploymentStatus = deploymentStatus; Id = id; MatchProcessingBehavior = matchProcessingBehavior; Name = name; Order = order; ProvisioningState = provisioningState; SystemData = systemData; Type = type; } } }
34.083333
300
0.599244
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Cdn/Latest/GetRule.cs
4,505
C#
using LinqToDB; using SchulIT.SchildExport.Data; using SchulIT.SchildExport.Models; using System.Collections.Generic; using System.Linq; namespace SchulIT.SchildExport.Repository { class StudyGroupRepository { private const string GradeStudyGroupMembershipType = "PUK"; private GradeRefRepository gradeRefRepository; private SubjectRefRepository subjectRefRepository; public StudyGroupRepository(GradeRefRepository gradeRefRepository, SubjectRefRepository subjectRefRepository) { this.gradeRefRepository = gradeRefRepository; this.subjectRefRepository = subjectRefRepository; } public List<StudyGroup> FindAll(SchildNRWConnection connection, IEnumerable<Student> students, short year, short section) { var gradeRefs = gradeRefRepository.FindAll(connection); var currentStudentIds = students.Select(x => x.Id).Distinct().ToList(); var studyGroups = new List<StudyGroup>(); var gradeStudyGroups = GetGradeStudyGroups(connection, gradeRefs, currentStudentIds, year, section); studyGroups.AddRange(gradeStudyGroups); studyGroups.AddRange(GetRemainingGradeStudyGroups(gradeStudyGroups, gradeRefs, students)); studyGroups.AddRange(GetCourseStudyGroups(connection, gradeRefs, currentStudentIds, year, section)); return studyGroups; } private List<StudyGroup> GetRemainingGradeStudyGroups(List<StudyGroup> existingStudyGroups, List<GradeRef> gradeRefs, IEnumerable<Student> students) { var studyGroups = new List<StudyGroup>(); var existingGrades = existingStudyGroups.Select(x => x.Grades.FirstOrDefault()).Where(x => x != null).Select(x => x.Id); foreach(var gradeRef in gradeRefs) { if (existingGrades.Contains(gradeRef.Id)) { continue; } var studyGroup = new StudyGroup { Id = null, Name = gradeRef.Name, Type = StudyGroupType.Grade, Grades = new List<GradeRef> { gradeRef } }; foreach(var student in students.Where(x => x.Grade != null && x.Grade.Id == gradeRef.Id)) { studyGroup.Memberships.Add(new StudyGroupMembership { Student = student, Type = null }); } if (studyGroup.Memberships.Count > 0) { studyGroups.Add(studyGroup); } } return studyGroups; } private List<StudyGroup> GetGradeStudyGroups(SchildNRWConnection connection, IEnumerable<GradeRef> gradeRefs, IEnumerable<int> currentStudentIds, short year, short section) { var results = from a in connection.SchuelerLernabschnittsdaten from l in connection.SchuelerLeistungsdaten.InnerJoin(sld => sld.AbschnittId == a.Id) where a.Jahr == year && a.Abschnitt == section && l.Kursart == GradeStudyGroupMembershipType group a by a.Klasse into x select new { Grade = x.Key, StudentData = x.ToList() }; var studyGroups = new List<StudyGroup>(); foreach (var result in results) { var studyGroup = new StudyGroup { Id = null, Name = result.Grade, Type = StudyGroupType.Grade }; var gradeRef = gradeRefs.FirstOrDefault(x => x.Name == result.Grade); if (gradeRef != null) { studyGroup.Grades.Add(gradeRef); } // Save already added student IDs // TODO: Modify code so we only have distinct memberships?! var studentIds = new List<int>(); foreach (var data in result.StudentData) { if (!studentIds.Contains(data.SchuelerId) && currentStudentIds.Contains(data.SchuelerId) && data.SemesterWertung == '+') { var membership = new StudyGroupMembership { Student = new StudentRef { Id = data.SchuelerId }, Type = GradeStudyGroupMembershipType }; studyGroup.Memberships.Add(membership); studentIds.Add(data.SchuelerId); } } studyGroups.Add(studyGroup); } return studyGroups; } private List<StudyGroup> GetCourseStudyGroups(SchildNRWConnection connection, IEnumerable<GradeRef> gradeRefs, IEnumerable<int> currentStudentIds, short year, short section) { var courses = connection.Kurse.Where(x => x.Jahr == year && x.Abschnitt == section).ToList(); var subjectRefs = subjectRefRepository.FindAll(connection); var memberships = from a in connection.SchuelerLernabschnittsdaten from l in connection.SchuelerLeistungsdaten.InnerJoin(sld => sld.AbschnittId == a.Id) where a.Jahr == year && a.Abschnitt == section && l.Kursart != GradeStudyGroupMembershipType select new { CourseId = l.KursId, StudentId = a.SchuelerId, Type = l.Kursart, Grade = a.Klasse, a.SemesterWertung }; var studyGroups = new List<StudyGroup>(); foreach(var course in courses) { var studyGroup = new StudyGroup { Id = course.Id, Type = StudyGroupType.Course, Name = course.KurzBez, DisplayName = course.Zeugnisbez }; var studentIds = new List<int>(); foreach(var membership in memberships.Where(x => x.CourseId == course.Id)) { var gradeRef = gradeRefs.FirstOrDefault(x => x.Name == membership.Grade); if (!studyGroup.Grades.Contains(gradeRef)) { studyGroup.Grades.Add(gradeRef); } if (!studentIds.Contains(membership.StudentId)) { studyGroup.Memberships.Add(new StudyGroupMembership { Student = new StudentRef { Id = membership.StudentId }, Type = membership.Type, Grade = membership.Grade }) ; studentIds.Add(membership.StudentId); } } /** * Wenn keine Mitglieder im Kurs sind, dann füge alle Jahrgänge an, in denen * der Kurs potentiell stattfinden kann. */ if (studyGroup.Grades.Count == 0) { var jahrgaenge = new List<int>(); if (!string.IsNullOrEmpty(course.Jahrgaenge)) { jahrgaenge.AddRange(course.Jahrgaenge.Split(',').Select(x => int.Parse(x))); } if(course.JahrgangId.HasValue) { jahrgaenge.Add(course.JahrgangId.Value); } foreach (var jahrgang in jahrgaenge) { foreach (var grade in gradeRefs.Where(x => x.GradeYearId == jahrgang)) { if (!studyGroup.Grades.Contains(grade)) { studyGroup.Grades.Add(grade); } } } } studyGroups.Add(studyGroup); } return studyGroups; } } }
39.504505
181
0.485405
[ "MIT" ]
SchulIT/schildexport
SchildExport/Repository/StudyGroupRepository.cs
8,774
C#
using Nager.Country.Currencies; namespace Nager.Country.CountryInfos { /// <summary> /// French Polynesia /// </summary> public class FrenchPolynesiaCountryInfo : ICountryInfo { ///<inheritdoc/> public string CommonName => "French Polynesia"; ///<inheritdoc/> public string OfficialName => "French Polynesia"; ///<inheritdoc/> public Alpha2Code Alpha2Code => Alpha2Code.PF; ///<inheritdoc/> public Alpha3Code Alpha3Code => Alpha3Code.PYF; ///<inheritdoc/> public int NumericCode => 258; ///<inheritdoc/> public string[] TLD => new [] { ".pf" }; ///<inheritdoc/> public Region Region => Region.Oceania; ///<inheritdoc/> public SubRegion SubRegion => SubRegion.Polynesia; ///<inheritdoc/> public Alpha2Code[] BorderCountries => new Alpha2Code[] { }; ///<inheritdoc/> public ICurrency[] Currencies => new [] { new XpfCurrency() }; ///<inheritdoc/> public string[] CallingCodes => new [] { "689" }; } }
28.692308
70
0.565684
[ "MIT" ]
Tri125/Nager.Country
src/Nager.Country/CountryInfos/FrenchPolynesiaCountryInfo.cs
1,119
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace invertFrase { class Program { static void Main(string[] args) { /*Faça um programa que receba uma frase digitada pelo usuário e exiba a mesma frase com cada palavra invertida. Exemplo: ETEC Albert Einstein – CETE treblA nietsniE */ string fraseInvertida=""; //variavel para guardar a frase invertida Console.WriteLine("Digite uma frase - iremos inverter todas as palavras nela"); string frase = Console.ReadLine(); char[] fraseArray = frase.ToCharArray(); //convert frase original p charArray for(int i=0; i<fraseArray.Length; i++) // loop crescente pelos chars da frase até encontrar um elemento que marque fim de palavra (' ' || . || , ||último elemento da array) { if(fraseArray[i]==32 || i==(fraseArray.Length-1) || fraseArray[i] == 44 || fraseArray[i] == 46) //32 == ascii para ' ' && \0 == final da array && 44==ascii para ',' && 46==ascii para '.' { if (i == (fraseArray.Length - 1)) // caso estivermos no último elemento, loop decrescente pelos chars incrementando o char atual na frase invertida, começando-a então pelos últimos chars da palavra até os primeiros { for (int z = i; z >= 0; z--) // caso o elemento atual seja o primeiro elemento, voltamos ao loop pai, em busca da proxima palavra { if (fraseArray[z] == 32 || fraseArray[i] == 44 || fraseArray[i] == 46) // caso o elemento atual seja um marcador de fim de palavra, indicando que terminamos a palavra atual, voltamos ao loop pai { break; } fraseInvertida += fraseArray[z]; } } else { for (int z = i - 1; z >= 0; z--) // caso não estivermos no ultimo elemento, pulamos o atual, que é marcador de fim de palavra, para começar pela ultima letra da palavra atual e incrementala como primeira na frase invertida { if (fraseArray[z] == 32) { break; } fraseInvertida += fraseArray[z]; } fraseInvertida += " "; // adicionamos na frase invertida o espaço que pulamos ao inverter a palvra atual, para manter a ordem das palavras e espaços na fraseaer } } } Console.WriteLine("Aqui está: {0}", fraseInvertida); Console.ReadKey(); //poderia ter sido feito de um modo muito mais facil usando .split(' ') para separar a string original antes de cada espaço e criando um vetor de strints para armazenar, depois inverter cada uma com o algo invert palavra } } }
59.178571
249
0.514786
[ "MIT" ]
danielspositocoelho/DS-EtecAlbertEinstein-Programacao_e_Algoritmos
Vetores/invertFrase/Program.cs
3,334
C#
using System.Diagnostics; using System.Linq; using Feedpipes.Rss20; using Feedpipes.Tests.SampleData; using Feedpipes.Utils.Xml; using Xunit; namespace Feedpipes.Tests { public class DebuggerBreakTests { [Fact] public void DebugInvalidXml() { var sampleFeeds = SampleFeedDirectory.GetSampleFeeds(); var feed = sampleFeeds .First(x => x.FileName == "feeds-feedburner-com-seomoz.xml"); // ReSharper disable once UnusedVariable var doc = feed.XDocument; Debugger.Break(); } [Fact] public void DebugPossibleNamespaceDeclarations() { var sampleFeeds = SampleFeedDirectory.GetSampleFeeds(); var namespaceSet = new XNamespaceAliasSet(); foreach (var feed in sampleFeeds) { var documentRoot = feed.XDocument?.Root; if (documentRoot == null) continue; var namespaceDeclarations = documentRoot .Attributes() .Where(x => x.IsNamespaceDeclaration) .ToList(); foreach (var namespaceDeclaration in namespaceDeclarations) { var alias = namespaceDeclaration.Name.LocalName; if (alias == "xmlns") { alias = null; } namespaceSet.EnsureNamespaceAlias(alias, namespaceDeclaration.Value); } } Debugger.Break(); // take a look at "namespaceSet" } [Fact] public void DebugRootNodes() { var sampleFeeds = SampleFeedDirectory.GetSampleFeeds(); // ReSharper disable once UnusedVariable var feedsByRoot = sampleFeeds .Where(x => x.XDocument != null) .GroupBy(feed => feed.XDocument.Root?.Name.LocalName) .ToDictionary(x => x.Key, x => x.ToList()); Debugger.Break(); // take a look at "feedsByRoot" } [Fact] public void DebugRssGenerators() { var sampleFeeds = SampleFeedDirectory.GetSampleFeeds(); // ReSharper disable once UnusedVariable var feedsByGenerator = sampleFeeds .Where(x => x.XDocument != null) .Select(x => { var tryParseResult = Rss20FeedParser.TryParseRss20Feed(x.XDocument, out var rss20Feed); return (feed: x, rss20Feed, tryParseResult); }) .Where(x => x.tryParseResult) .Select(x => (x.feed, generator: x.rss20Feed.Channel?.Generator)) .GroupBy(x => x.generator ?? string.Empty, x => x.feed) .ToDictionary(x => x.Key, x => x.ToList()); Debugger.Break(); // take a look at "feedsByGenerator" } } }
32.957447
108
0.510652
[ "MIT" ]
tompazourek/Feedpipes
tests/Feedpipes.Tests/DebuggerBreakTests.cs
3,007
C#
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace INZFS.MVC.Services.FileUpload { public interface IFileUploadService { public string ModifyFileName(string originalFileName); public Task<string> SaveFile(IFormFile file, string directoryName); public string Validate(IFormFile file, Page currentPage, bool virusScanningEnabled, string cloudmersiveApiKey); public Task<bool> CreateDirectory(string directoryName); public Task<bool> DeleteFile(string fileLocation); } }
33.157895
119
0.763492
[ "MIT" ]
BEIS-Digital-Services/INZFS
INZFS.MVC/Services/FileUpload/IFileUploadService.cs
632
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using System.Collections.Generic; using System.Text; partial class XTend { [TextUtility, Closures(Closure)] public static string FormatList<T>(this ReadOnlySpan<T> src, char sep = Chars.Comma, int offset = 0, int pad = 0, bool bracketed = true) { var count = src.Length; if(count == 0) return string.Empty; var sb = new StringBuilder(); for(var i = offset; i<count; i++) { var item =$"{src[i]}"; sb.Append(pad != 0 ? item.PadLeft(pad) : item); if(i != count - 1) { sb.Append(sep); sb.Append(Chars.Space); } } return bracketed ? $"[{sb.ToString()}]" : sb.ToString(); } static ReadOnlySpan<T> RO<T>(Span<T> src) => src; [TextUtility] public static string FormatList<T>(this Span<T> src, char sep = Chars.Comma, int offset = 0, int pad = 0, bool bracketed = true) => RO(src).FormatList(sep, offset, pad, bracketed); [TextUtility] public static string FormatList<T>(this T[] src, char sep = Chars.Comma, int offset = 0, int pad = 0, bool bracketed = true) => src.ToSpan().FormatList(sep, offset); /// <summary> /// Formats a sequence of objects as a delimited list /// </summary> /// <param name="src">The source span</param> /// <param name="delimiter">The delimiter, if specified; otherwise, a system default is chosen</param> /// <typeparam name="T">A formattable type</typeparam> [TextUtility] public static string FormatList(this IEnumerable<object> items, char sep = Chars.Comma) => string.Join(sep, items); } }
37.482143
144
0.495474
[ "BSD-3-Clause" ]
0xCM/z0
src/root/src/text/x/FormatList.cs
2,099
C#
namespace Presentation.ViewModel { public interface IWindow { void Show(); } }
12.5
33
0.6
[ "MIT" ]
Tomek742/ProgTech
LibraryTask2/Presentation/ViewModel/IWindow.cs
102
C#
using MediatR; using NoDaysOffApp.Data; using NoDaysOffApp.Features.Core; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using System.Data.Entity; namespace NoDaysOffApp.Features.Profiles { public class GetProfileByIdQuery { public class Request : BaseRequest, IRequest<Response> { public int Id { get; set; } } public class Response { public ProfileApiModel Profile { get; set; } } public class Handler : IAsyncRequestHandler<Request, Response> { public Handler(NoDaysOffAppContext context, ICache cache) { _context = context; _cache = cache; } public async Task<Response> Handle(Request request) { return new Response() { Profile = ProfileApiModel.FromProfile(await _context.Profiles .Include(x => x.Tenant) .SingleAsync(x=>x.Id == request.Id && x.Tenant.UniqueId == request.TenantUniqueId)) }; } private readonly NoDaysOffAppContext _context; private readonly ICache _cache; } } }
27.020833
89
0.564379
[ "MIT" ]
QuinntyneBrown/no-days-off-app
Features/Profiles/GetProfileByIdQuery.cs
1,297
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.SecurityInsights { /// <summary> /// Represents a relation between two resources /// API Version: 2019-01-01-preview. /// </summary> [AzureNativeResourceType("azure-native:securityinsights:BookmarkRelation")] public partial class BookmarkRelation : Pulumi.CustomResource { /// <summary> /// Etag of the azure resource /// </summary> [Output("etag")] public Output<string?> Etag { get; private set; } = null!; /// <summary> /// Azure resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The resource ID of the related resource /// </summary> [Output("relatedResourceId")] public Output<string> RelatedResourceId { get; private set; } = null!; /// <summary> /// The resource kind of the related resource /// </summary> [Output("relatedResourceKind")] public Output<string> RelatedResourceKind { get; private set; } = null!; /// <summary> /// The name of the related resource /// </summary> [Output("relatedResourceName")] public Output<string> RelatedResourceName { get; private set; } = null!; /// <summary> /// The resource type of the related resource /// </summary> [Output("relatedResourceType")] public Output<string> RelatedResourceType { get; private set; } = null!; /// <summary> /// Azure resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a BookmarkRelation resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public BookmarkRelation(string name, BookmarkRelationArgs args, CustomResourceOptions? options = null) : base("azure-native:securityinsights:BookmarkRelation", name, args ?? new BookmarkRelationArgs(), MakeResourceOptions(options, "")) { } private BookmarkRelation(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:securityinsights:BookmarkRelation", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:securityinsights:BookmarkRelation"}, new Pulumi.Alias { Type = "azure-native:securityinsights/v20190101preview:BookmarkRelation"}, new Pulumi.Alias { Type = "azure-nextgen:securityinsights/v20190101preview:BookmarkRelation"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing BookmarkRelation resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static BookmarkRelation Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new BookmarkRelation(name, id, options); } } public sealed class BookmarkRelationArgs : Pulumi.ResourceArgs { /// <summary> /// Bookmark ID /// </summary> [Input("bookmarkId", required: true)] public Input<string> BookmarkId { get; set; } = null!; /// <summary> /// Etag of the azure resource /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// The namespace of workspaces resource provider- Microsoft.OperationalInsights. /// </summary> [Input("operationalInsightsResourceProvider", required: true)] public Input<string> OperationalInsightsResourceProvider { get; set; } = null!; /// <summary> /// The resource ID of the related resource /// </summary> [Input("relatedResourceId", required: true)] public Input<string> RelatedResourceId { get; set; } = null!; /// <summary> /// Relation Name /// </summary> [Input("relationName")] public Input<string>? RelationName { get; set; } /// <summary> /// The name of the resource group within the user's subscription. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the workspace. /// </summary> [Input("workspaceName", required: true)] public Input<string> WorkspaceName { get; set; } = null!; public BookmarkRelationArgs() { } } }
38.72956
144
0.599221
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/SecurityInsights/BookmarkRelation.cs
6,158
C#
// This file is part of the re-linq project (relinq.codeplex.com) // Copyright (C) 2005-2009 rubicon informationstechnologie gmbh, www.rubicon.eu // // re-linq is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 2.1 of the License, // or (at your option) any later version. // // re-linq is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with re-linq; if not, see http://www.gnu.org/licenses. // using System; using System.Diagnostics; using System.Linq.Expressions; using Remotion.Linq.Clauses.ExpressionTreeVisitors; using Remotion.Linq.Utilities; namespace Remotion.Linq.Clauses { /// <summary> /// Represents a single ordering instruction in an <see cref="OrderByClause"/>. /// </summary> public class Ordering { private Expression _expression; /// <summary> /// Initializes a new instance of the <see cref="Ordering"/> class. /// </summary> /// <param name="expression">The expression used to order the data items returned by the query.</param> /// <param name="direction">The <see cref="OrderingDirection"/> to use for sorting.</param> public Ordering (Expression expression, OrderingDirection direction) { ArgumentUtility.CheckNotNull ("expression", expression); _expression = expression; OrderingDirection = direction; } /// <summary> /// Gets or sets the expression used to order the data items returned by the query. /// </summary> /// <value>The expression.</value> [DebuggerDisplay ("{Remotion.Data.Linq.Clauses.ExpressionTreeVisitors.FormattingExpressionTreeVisitor.Format (Expression),nq}")] public Expression Expression { get { return _expression; } set { _expression = ArgumentUtility.CheckNotNull ("value", value); } } /// <summary> /// Gets or sets the direction to use for ordering data items. /// </summary> public OrderingDirection OrderingDirection { get; set; } /// <summary> /// Accepts the specified visitor by calling its <see cref="IQueryModelVisitor.VisitOrdering"/> method. /// </summary> /// <param name="visitor">The visitor to accept.</param> /// <param name="queryModel">The query model in whose context this clause is visited.</param> /// <param name="orderByClause">The <see cref="OrderByClause"/> in whose context this item is visited.</param> /// <param name="index">The index of this item in the <paramref name="orderByClause"/>'s <see cref="OrderByClause.Orderings"/> collection.</param> public virtual void Accept (IQueryModelVisitor visitor, QueryModel queryModel, OrderByClause orderByClause, int index) { ArgumentUtility.CheckNotNull ("visitor", visitor); ArgumentUtility.CheckNotNull ("queryModel", queryModel); ArgumentUtility.CheckNotNull ("orderByClause", orderByClause); visitor.VisitOrdering (this, queryModel, orderByClause, index); } /// <summary> /// Clones this item. /// </summary> /// <param name="cloneContext">The clones of all query source clauses are registered with this <see cref="CloneContext"/>.</param> /// <returns>A clone of this item.</returns> virtual public Ordering Clone (CloneContext cloneContext) { ArgumentUtility.CheckNotNull ("cloneContext", cloneContext); var clone = new Ordering (Expression, OrderingDirection); return clone; } /// <summary> /// Transforms all the expressions in this item via the given <paramref name="transformation"/> delegate. /// </summary> /// <param name="transformation">The transformation object. This delegate is called for each <see cref="Expression"/> within this /// item, and those expressions will be replaced with what the delegate returns.</param> public void TransformExpressions (Func<Expression, Expression> transformation) { ArgumentUtility.CheckNotNull ("transformation", transformation); Expression = transformation (Expression); } public override string ToString () { return FormattingExpressionTreeVisitor.Format (Expression) + (OrderingDirection == OrderingDirection.Asc ? " asc" : " desc"); } } }
42.504673
150
0.704485
[ "MIT" ]
rajcybage/BrightstarDB
src/portable/BrightstarDB.Portable/relinq/RelinqCore/Clauses/Ordering.cs
4,548
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chain { class App { List<IMiddleware> middlewares = new List<IMiddleware>(); public void Use(IMiddleware middleware) { middlewares.Add(middleware); } public async void HandleRequest(Request request) { Response response = new Response(); foreach (var middleware in middlewares) { if (await middleware.Handle(request, response)) { return; } } response.Send("404 not found"); } } }
22.40625
64
0.541144
[ "MIT" ]
isbdnt/csharp-design-patterns
Chain/App.cs
719
C#
namespace RDotNet.Internals { /// <summary> /// Type of R's working. /// </summary> public enum BusyType { /// <summary> /// Terminated states of business. /// </summary> None = 0, /// <summary> /// Embarks on an extended computation /// </summary> ExtendedComputation = 1, } }
20.333333
46
0.494536
[ "MIT" ]
David-McCarty/rdotnet
R.NET/Internals/BusyType.cs
366
C#
namespace Restaurant { public class Beverage : Product { public Beverage(string name, decimal price, double milliliters) :base(name, price) { Milliliters = milliliters; } public double Milliliters { get; set; } } }
20.357143
71
0.568421
[ "MIT" ]
StasiS-web/SoftuniCourse
C# OOP/Inheritance - Exercise/Restaurant/Beverage.cs
287
C#
using System.IO; using Xunit; using YellowCounter.FileSystemState; public class FileSystemStateSerializableTests { [Fact] public void RoundTripDoesNotAffectOriginalTest() { string currentDir = Utility.GetRandomDirectory(); string fileName = Path.GetRandomFileName() + ".txt"; string fullName = Path.Combine(currentDir, fileName); FileSystemState state = new FileSystemState(currentDir, "*.csv"); FileSystemState state2 = new FileSystemState(currentDir, "*.txt"); state.LoadState(); RoundTrip(state, state2); using (var file = File.Create(fullName)) { } try { Assert.Empty(state.GetChanges()); Assert.Single(state2.GetChanges()); } finally { Directory.Delete(currentDir, true); } } [Fact] public void RoundTripVersionReset_NoChanges_Test() { string currentDir = Utility.GetRandomDirectory(); string fileName = Path.GetRandomFileName(); string fullName = Path.Combine(currentDir, fileName); using (var file = File.Create(fullName)) { } FileSystemState state = new FileSystemState(currentDir); state.LoadState(); state.GetChanges(); FileSystemState state2 = new FileSystemState(currentDir); RoundTrip(state, state2); try { Assert.Empty(state.GetChanges()); Assert.Empty(state2.GetChanges()); } finally { Directory.Delete(currentDir, true); } } [Fact] public void RoundTripVersionReset_Deletion_Test() { string currentDir = Utility.GetRandomDirectory(); string fileName = Path.GetRandomFileName(); string fullName = Path.Combine(currentDir, fileName); using (var file = File.Create(fullName)) { } FileSystemState state = new FileSystemState(currentDir); state.LoadState(); FileSystemState state2 = new FileSystemState(currentDir); RoundTrip(state, state2); File.Delete(fullName); try { Assert.Single(state.GetChanges()); Assert.Single(state2.GetChanges()); } finally { Directory.Delete(currentDir, true); } } private static void RoundTrip(FileSystemState source, FileSystemState destination) { using (MemoryStream stream = new MemoryStream()) { source.SaveState(stream); stream.Position = 0; destination.LoadState(stream); } } }
27.302083
86
0.602823
[ "MIT" ]
MisinformedDNA/YellowCounter.FileSystemState
YellowCounter.FileSystemState.Tests/SerializableTests.cs
2,623
C#
using Proxem.NumNet; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace Proxem.Word2Vec.Test { public class TestSortingNeighbors: IClassFixture<Shared> { private Word2Vec _w2v; // random matrix of shape (10, 4) private readonly Array<float> _test_1; // random vector of shape (1, 4) private readonly Array<float> _test_2; // random vector of shape (1, 4) private Array<float> _test_3; // [_test_1, _test_2] concatenation, shape (4, 2) public TestSortingNeighbors(Shared shared) { this._w2v = shared.W2v; this._test_1 = shared.Test1; this._test_2 = shared.Test2; this._test_3 = shared.Test3; } [Fact] public void TestBaseline() { var bestd = new float[4]; var bestw = new int[4]; var expectedd = new float[4] { 1.34889853f, 1.17417169f, 1.15919185f, 0.866888f }; var expectedw = new int[4] { 8, 2, 0, 5 }; _w2v.NBest(_test_1, bestd, bestw); AssertArray.AreAlmostEqual(expectedd, bestd); AssertArray.AreEqual(expectedw, bestw); } [Fact] public void TestBuildVPTree() { _w2v.NBestVPTree(_test_1, new double[5], new int[5]); } [Fact] public void TestVPTree() { var bestd = new double[4]; var bestw = new int[4]; // with this test the order is not exactly the same due to the vector normalisation required by the VPTree // this is not a problem as it is often better to normalize before doing the neighbors search var expectedd = new double[4] { 0.132890641689301, 0.480090379714966, 0.648832619190216, 0.662571460008621 }; var expectedw = new int[4] { 8, 2, 5, 0 }; _w2v.NBestVPTree(_test_1, bestd, bestw); AssertArray.AreAlmostEqual(expectedd, bestd); AssertArray.AreEqual(expectedw, bestw); } [Fact] public void TestHeapsortSingle() { var bestd = new float[4]; var bestw = new int[4]; var expectedd = new float[4] { 1.34889853f, 1.17417169f, 1.15919185f, 0.866888f }; var expectedw = new int[4] { 8, 2, 0, 5 }; _w2v.NBestHeap(_test_1, bestd, bestw); AssertArray.AreAlmostEqual(expectedd, bestd); AssertArray.AreEqual(expectedw, bestw); expectedd = new float[4] { 4.63800335f, 4.19298649f, 3.162262f, 1.9904952f }; expectedw = new int[4] { 1, 7, 3, 4 }; _w2v.NBestHeap(_test_2, bestd, bestw); AssertArray.AreAlmostEqual(expectedd, bestd); AssertArray.AreEqual(expectedw, bestw); } [Fact] public void TestHeapsortBatch() { var bestd = new float[_test_3.Shape[1]][]; var bestw = new int[_test_3.Shape[1]][]; int neighbors = 3; for (int i = 0; i < bestd.Length; i++) { bestd[i] = new float[neighbors]; bestw[i] = new int[neighbors]; } var expectedd = new float[6] { 1.34889853f, 1.17417169f, 1.15919185f, 4.63800335f, 4.19298649f, 3.162262f }; var expectedw = new int[6] { 8, 2, 0, 1, 7, 3 }; _w2v.NBestHeap(_test_3, bestd, bestw); AssertArray.AreAlmostEqual(expectedd, (from bd in bestd from d in bd select d).ToArray()); AssertArray.AreEqual(expectedw, (from bw in bestw from w in bw select w).ToArray()); } [Fact] public void TestHeapsortBatchParallel() { var bestd = new float[_test_3.Shape[1]][]; var bestw = new int[_test_3.Shape[1]][]; int neighbors = 3; for (int i = 0; i < bestd.Length; i++) { bestd[i] = new float[neighbors]; bestw[i] = new int[neighbors]; } var expectedd = new float[6] { 1.34889853f, 1.17417169f, 1.15919185f, 4.63800335f, 4.19298649f, 3.162262f }; var expectedw = new int[6] { 8, 2, 0, 1, 7, 3 }; _w2v.NBestHeapParallel(_test_3, bestd, bestw); AssertArray.AreAlmostEqual(expectedd, (from bd in bestd from d in bd select d).ToArray()); AssertArray.AreEqual(expectedw, (from bw in bestw from w in bw select w).ToArray()); } [Fact] public void TestCompatibilityHeapsortBatchSingle() { // test that batch and single line heapsort have same results var test = NN.Random.Normal(0.1f, 0.1f, 4, 20); var bestd = new float[test.Shape[1]][]; var bestw = new int[test.Shape[1]][]; int neighbors = 3; for (int i = 0; i < bestd.Length; i++) { bestd[i] = new float[neighbors]; bestw[i] = new int[neighbors]; } _w2v.NBestHeap(test, bestd, bestw); var singleBestd = new float[neighbors]; var singleBestw = new int[neighbors]; for (int i = 0; i < test.Shape[1]; i++) { _w2v.NBestHeap(test[Slicer._, i], singleBestd, singleBestw); AssertArray.AreEqual(singleBestw, bestw[i]); AssertArray.AreAlmostEqual(singleBestd, bestd[i]); } } [Fact] public void TestCompatibilityHeapsortBatchBatchParallel() { // test that heapsort batch parallel and batch have same results var test = NN.Random.Normal(0f, 0.1f, 4, 30); var bestd_1 = new float[test.Shape[1]][]; var bestd_2 = new float[test.Shape[1]][]; var bestw_1 = new int[test.Shape[1]][]; var bestw_2 = new int[test.Shape[1]][]; int neighbors = 6; for (int i = 0; i < test.Shape[1]; i++) { bestd_1[i] = new float[neighbors]; bestd_2[i] = new float[neighbors]; bestw_1[i] = new int[neighbors]; bestw_2[i] = new int[neighbors]; } _w2v.NBestHeap(test, bestd_1, bestw_1); _w2v.NBestHeapParallel(test, bestd_2, bestw_2); for (int i = 0; i < test.Shape[1]; i++) { AssertArray.AreAlmostEqual(bestd_1[i], bestd_2[i]); AssertArray.AreEqual(bestw_1[i], bestw_2[i]); } } [Fact] public void TestCompatibilityHeapsortSort() { // test that heapsort single and sort single have same results var test = NN.Random.Normal(0f, 0.1f, 4, 10); int neighbors = 6; var bestd_1 = new float[neighbors]; var bestd_2 = new float[neighbors]; var bestw_1 = new int[neighbors]; var bestw_2 = new int[neighbors]; for (int i = 0; i < test.Shape[1]; i++) { _w2v.NBestHeap(test[Slicer._, i], bestd_1, bestw_1); _w2v.NBest(test[Slicer._, i], bestd_2, bestw_2); AssertArray.AreAlmostEqual(bestd_1, bestd_2); AssertArray.AreEqual(bestw_1, bestw_2); } } [Fact] public void TestQuicksortSingle() { var bestd = new float[4]; var bestw = new int[4]; var expectedd = new float[4] { 1.34889853f, 1.17417169f, 1.15919185f, 0.866888f }; var expectedw = new int[4] { 8, 2, 0, 5 }; _w2v.NBestQs(_test_1, bestd, bestw); AssertArray.AreAlmostEqual(expectedd, bestd); AssertArray.AreEqual(expectedw, bestw); expectedd = new float[4] { 4.63800335f, 4.19298649f, 3.162262f, 1.9904952f }; expectedw = new int[4] { 1, 7, 3, 4 }; _w2v.NBestQs(_test_2, bestd, bestw); AssertArray.AreAlmostEqual(expectedd, bestd); AssertArray.AreEqual(expectedw, bestw); } [Fact] public void TestQuicksortBatch() { // quicksort batch is not implemented yet } [Fact] public void TestCompatibilityQuicksortBatchSingle() { // quicksort batch is not implemented yet } [Fact] public void TestCompatibilityQuicksortBatchParallel() { // quicksort batch is not implemented yet } [Fact] public void TestCompatibilityQuicksortSort() { // test that quicksort single and sort single have same results var test = NN.Random.Normal(0f, 0.1f, 4, 15); int neighbors = 5; var bestd_1 = new float[neighbors]; var bestd_2 = new float[neighbors]; var bestw_1 = new int[neighbors]; var bestw_2 = new int[neighbors]; for (int i = 0; i < test.Shape[1]; i++) { _w2v.NBestQs(test[Slicer._, i], bestd_1, bestw_1); _w2v.NBest(test[Slicer._, i], bestd_2, bestw_2); AssertArray.AreAlmostEqual(bestd_1, bestd_2); AssertArray.AreEqual(bestw_1, bestw_2); } } } }
37.195402
121
0.519056
[ "Apache-2.0" ]
Proxem/Word2Vec
Proxem.Word2Vec.Test/TestSortingNeighbors.cs
9,710
C#
using DataClassHierarchy; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using System.Threading.Tasks; using ServersWithLayers; namespace Compiler.Tests { [TestClass] public class ReturnTests : LangTest { [TestMethod] public void InRootContext() { var tokens = _lex.Tokenize(@" return 5" + _dslSuf); Assert.IsTrue(_parser.TryParse(tokens, out var ast)); var ctx = new Context(); Assert.IsFalse(ast.Validate(ctx)); } [TestMethod] public void DeepButNotInFunction() { var tokens = _lex.Tokenize(@" if 3 > 5 { if 20 > 30 { let a = [3] if 3 == 7 { return 5 } } }" + _dslSuf); Assert.IsTrue(_parser.TryParse(tokens, out var ast)); var ctx = new Context(); Assert.IsFalse(ast.Validate(ctx)); } [TestMethod] public void NearOfFunctionButNotInside() { var tokens = _lex.Tokenize(@" fun f(x) { return x+1 } if 3 > 5 { if 20 > 30 { let a = [3] if 3 == 7 { return 5 } } }" + _dslSuf); Assert.IsTrue(_parser.TryParse(tokens, out var ast)); var ctx = new Context(); Assert.IsFalse(ast.Validate(ctx)); } [TestMethod] public void InsideFunctionWithFunction() { var tokens = _lex.Tokenize(@" fun f(x) { let a = 5 fun g(y) { return y+3 } return 3 }" + _dslSuf); Assert.IsTrue(_parser.TryParse(tokens, out var ast)); var ctx = new Context(); Assert.IsTrue(ast.Validate(ctx)); } [TestCleanup] public void Clean() { Dispose(); } } }
23.035714
65
0.538501
[ "MIT" ]
CSProjectsAvatar/SimCopIA
Gos/Compiler/Tests/ReturnTests.cs
1,937
C#
using System; using System.Collections.Generic; using System.IO; using Amazon.IdentityManagement.Model; using Calamari.Commands.Support; using Calamari.Common.Commands; using Calamari.Common.Features.Packages; using Calamari.Common.Features.Packages.NuGet; using Calamari.Common.Plumbing.Variables; using Calamari.Integration.Packages; using Calamari.Integration.Packages.NuGet; using Calamari.Testing.Helpers; using Calamari.Tests.Fixtures.Util; using Calamari.Tests.Helpers; using NUnit.Framework; using InMemoryLog = Calamari.Tests.Helpers.InMemoryLog; using TestCommandLineRunner = Calamari.Testing.Helpers.TestCommandLineRunner; namespace Calamari.Tests.Fixtures.Integration.Packages { [TestFixture] public class CombinedPackageExtractorFixture : CalamariFixture { [Test] [TestCaseSource(nameof(PackageNameTestCases))] public void GettingFileByExtension(string filename, Type expectedType) { var combinedExtractor = CreateCombinedPackageExtractor(); var specificExtractor = combinedExtractor.GetExtractor(filename); Assert.AreEqual(expectedType, specificExtractor.GetType()); } static IEnumerable<object> PackageNameTestCases() { var fileNames = new[] { "foo.1.0.0", "foo.1.0.0-tag", "foo.1.0.0-tag-release.tag", "foo.1.0.0+buildmeta", "foo.1.0.0-tag-release.tag+buildmeta", }; var extractorMapping = new (string extension, Type extractor)[] { ("zip", typeof(ZipPackageExtractor)), ("nupkg", typeof(NupkgExtractor)), ("tar", typeof(TarPackageExtractor)), ("tar.gz", typeof(TarGzipPackageExtractor)), ("tar.bz2", typeof(TarBzipPackageExtractor)), }; foreach (var filename in fileNames) { foreach (var (extension, type) in extractorMapping) { yield return new TestCaseData($"{filename}.{extension}", type); } } } [Test] [ExpectedException(typeof(CommandException), ExpectedMessage = "Package is missing file extension. This is needed to select the correct extraction algorithm.")] public void FileWithNoExtensionThrowsError() { CreateCombinedPackageExtractor().GetExtractor("blah"); } [Test] [ExpectedException(typeof(CommandException), ExpectedMessage = "Unsupported file extension `.7z`")] public void FileWithUnsupportedExtensionThrowsError() { CreateCombinedPackageExtractor().GetExtractor("blah.1.0.0.7z"); } static CombinedPackageExtractor CreateCombinedPackageExtractor() { var log = new InMemoryLog(); var variables = new CalamariVariables(); var combinedExtractor = new CombinedPackageExtractor(log, variables, new TestCommandLineRunner(log, variables)); return combinedExtractor; } } }
36.55814
168
0.638359
[ "Apache-2.0" ]
OctopusDeploy/Calamari
source/Calamari.Tests/Fixtures/Integration/Packages/CombinedPackageExtractorFixture.cs
3,146
C#
/* * LeagueClient * * 7.23.209.3517 * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace LeagueClientApi.Model { /// <summary> /// CollectionsLcdsChampionDTO /// </summary> [DataContract] public partial class CollectionsLcdsChampionDTO : IEquatable<CollectionsLcdsChampionDTO>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CollectionsLcdsChampionDTO" /> class. /// </summary> /// <param name="Active">Active.</param> /// <param name="BotEnabled">BotEnabled.</param> /// <param name="ChampionId">ChampionId.</param> /// <param name="ChampionSkins">ChampionSkins.</param> /// <param name="EndDate">EndDate.</param> /// <param name="FreeToPlay">FreeToPlay.</param> /// <param name="FreeToPlayReward">FreeToPlayReward.</param> /// <param name="Owned">Owned.</param> /// <param name="PurchaseDate">PurchaseDate.</param> /// <param name="Purchased">Purchased.</param> /// <param name="RankedPlayEnabled">RankedPlayEnabled.</param> /// <param name="Sources">Sources.</param> /// <param name="WinCountRemaining">WinCountRemaining.</param> public CollectionsLcdsChampionDTO(bool? Active = default(bool?), bool? BotEnabled = default(bool?), int? ChampionId = default(int?), List<CollectionsLcdsChampionSkinDTO> ChampionSkins = default(List<CollectionsLcdsChampionSkinDTO>), long? EndDate = default(long?), bool? FreeToPlay = default(bool?), bool? FreeToPlayReward = default(bool?), bool? Owned = default(bool?), long? PurchaseDate = default(long?), long? Purchased = default(long?), bool? RankedPlayEnabled = default(bool?), List<string> Sources = default(List<string>), int? WinCountRemaining = default(int?)) { this.Active = Active; this.BotEnabled = BotEnabled; this.ChampionId = ChampionId; this.ChampionSkins = ChampionSkins; this.EndDate = EndDate; this.FreeToPlay = FreeToPlay; this.FreeToPlayReward = FreeToPlayReward; this.Owned = Owned; this.PurchaseDate = PurchaseDate; this.Purchased = Purchased; this.RankedPlayEnabled = RankedPlayEnabled; this.Sources = Sources; this.WinCountRemaining = WinCountRemaining; } /// <summary> /// Gets or Sets Active /// </summary> [DataMember(Name="active", EmitDefaultValue=false)] public bool? Active { get; set; } /// <summary> /// Gets or Sets BotEnabled /// </summary> [DataMember(Name="botEnabled", EmitDefaultValue=false)] public bool? BotEnabled { get; set; } /// <summary> /// Gets or Sets ChampionId /// </summary> [DataMember(Name="championId", EmitDefaultValue=false)] public int? ChampionId { get; set; } /// <summary> /// Gets or Sets ChampionSkins /// </summary> [DataMember(Name="championSkins", EmitDefaultValue=false)] public List<CollectionsLcdsChampionSkinDTO> ChampionSkins { get; set; } /// <summary> /// Gets or Sets EndDate /// </summary> [DataMember(Name="endDate", EmitDefaultValue=false)] public long? EndDate { get; set; } /// <summary> /// Gets or Sets FreeToPlay /// </summary> [DataMember(Name="freeToPlay", EmitDefaultValue=false)] public bool? FreeToPlay { get; set; } /// <summary> /// Gets or Sets FreeToPlayReward /// </summary> [DataMember(Name="freeToPlayReward", EmitDefaultValue=false)] public bool? FreeToPlayReward { get; set; } /// <summary> /// Gets or Sets Owned /// </summary> [DataMember(Name="owned", EmitDefaultValue=false)] public bool? Owned { get; set; } /// <summary> /// Gets or Sets PurchaseDate /// </summary> [DataMember(Name="purchaseDate", EmitDefaultValue=false)] public long? PurchaseDate { get; set; } /// <summary> /// Gets or Sets Purchased /// </summary> [DataMember(Name="purchased", EmitDefaultValue=false)] public long? Purchased { get; set; } /// <summary> /// Gets or Sets RankedPlayEnabled /// </summary> [DataMember(Name="rankedPlayEnabled", EmitDefaultValue=false)] public bool? RankedPlayEnabled { get; set; } /// <summary> /// Gets or Sets Sources /// </summary> [DataMember(Name="sources", EmitDefaultValue=false)] public List<string> Sources { get; set; } /// <summary> /// Gets or Sets WinCountRemaining /// </summary> [DataMember(Name="winCountRemaining", EmitDefaultValue=false)] public int? WinCountRemaining { 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 CollectionsLcdsChampionDTO {\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" BotEnabled: ").Append(BotEnabled).Append("\n"); sb.Append(" ChampionId: ").Append(ChampionId).Append("\n"); sb.Append(" ChampionSkins: ").Append(ChampionSkins).Append("\n"); sb.Append(" EndDate: ").Append(EndDate).Append("\n"); sb.Append(" FreeToPlay: ").Append(FreeToPlay).Append("\n"); sb.Append(" FreeToPlayReward: ").Append(FreeToPlayReward).Append("\n"); sb.Append(" Owned: ").Append(Owned).Append("\n"); sb.Append(" PurchaseDate: ").Append(PurchaseDate).Append("\n"); sb.Append(" Purchased: ").Append(Purchased).Append("\n"); sb.Append(" RankedPlayEnabled: ").Append(RankedPlayEnabled).Append("\n"); sb.Append(" Sources: ").Append(Sources).Append("\n"); sb.Append(" WinCountRemaining: ").Append(WinCountRemaining).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 CollectionsLcdsChampionDTO); } /// <summary> /// Returns true if CollectionsLcdsChampionDTO instances are equal /// </summary> /// <param name="other">Instance of CollectionsLcdsChampionDTO to be compared</param> /// <returns>Boolean</returns> public bool Equals(CollectionsLcdsChampionDTO other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Active == other.Active || this.Active != null && this.Active.Equals(other.Active) ) && ( this.BotEnabled == other.BotEnabled || this.BotEnabled != null && this.BotEnabled.Equals(other.BotEnabled) ) && ( this.ChampionId == other.ChampionId || this.ChampionId != null && this.ChampionId.Equals(other.ChampionId) ) && ( this.ChampionSkins == other.ChampionSkins || this.ChampionSkins != null && this.ChampionSkins.SequenceEqual(other.ChampionSkins) ) && ( this.EndDate == other.EndDate || this.EndDate != null && this.EndDate.Equals(other.EndDate) ) && ( this.FreeToPlay == other.FreeToPlay || this.FreeToPlay != null && this.FreeToPlay.Equals(other.FreeToPlay) ) && ( this.FreeToPlayReward == other.FreeToPlayReward || this.FreeToPlayReward != null && this.FreeToPlayReward.Equals(other.FreeToPlayReward) ) && ( this.Owned == other.Owned || this.Owned != null && this.Owned.Equals(other.Owned) ) && ( this.PurchaseDate == other.PurchaseDate || this.PurchaseDate != null && this.PurchaseDate.Equals(other.PurchaseDate) ) && ( this.Purchased == other.Purchased || this.Purchased != null && this.Purchased.Equals(other.Purchased) ) && ( this.RankedPlayEnabled == other.RankedPlayEnabled || this.RankedPlayEnabled != null && this.RankedPlayEnabled.Equals(other.RankedPlayEnabled) ) && ( this.Sources == other.Sources || this.Sources != null && this.Sources.SequenceEqual(other.Sources) ) && ( this.WinCountRemaining == other.WinCountRemaining || this.WinCountRemaining != null && this.WinCountRemaining.Equals(other.WinCountRemaining) ); } /// <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.Active != null) hash = hash * 59 + this.Active.GetHashCode(); if (this.BotEnabled != null) hash = hash * 59 + this.BotEnabled.GetHashCode(); if (this.ChampionId != null) hash = hash * 59 + this.ChampionId.GetHashCode(); if (this.ChampionSkins != null) hash = hash * 59 + this.ChampionSkins.GetHashCode(); if (this.EndDate != null) hash = hash * 59 + this.EndDate.GetHashCode(); if (this.FreeToPlay != null) hash = hash * 59 + this.FreeToPlay.GetHashCode(); if (this.FreeToPlayReward != null) hash = hash * 59 + this.FreeToPlayReward.GetHashCode(); if (this.Owned != null) hash = hash * 59 + this.Owned.GetHashCode(); if (this.PurchaseDate != null) hash = hash * 59 + this.PurchaseDate.GetHashCode(); if (this.Purchased != null) hash = hash * 59 + this.Purchased.GetHashCode(); if (this.RankedPlayEnabled != null) hash = hash * 59 + this.RankedPlayEnabled.GetHashCode(); if (this.Sources != null) hash = hash * 59 + this.Sources.GetHashCode(); if (this.WinCountRemaining != null) hash = hash * 59 + this.WinCountRemaining.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
40.781646
577
0.536354
[ "MIT" ]
wildbook/LeagueClientApi
Model/CollectionsLcdsChampionDTO.cs
12,887
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The interface IWorkbookFunctionsSumRequest. /// </summary> public partial interface IWorkbookFunctionsSumRequest : IBaseRequest { /// <summary> /// Gets the request body. /// </summary> WorkbookFunctionsSumRequestBody RequestBody { get; } /// <summary> /// Issues the POST request. /// </summary> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(); /// <summary> /// Issues the POST request. /// </summary> /// /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>TheWorkbookFunctionResult</returns> System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsSumRequest Expand(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IWorkbookFunctionsSumRequest Select(string value); } }
36.296296
153
0.583673
[ "MIT" ]
MIchaelMainer/GraphAPI
src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsSumRequest.cs
1,960
C#
using System; class MissCat2011 { static void Main() { uint N; uint VoteFor; uint Winner = 0; uint WinnerVotes=0; uint[] cat = new uint[10]; N = uint.Parse(Console.ReadLine()); for (int i = 0; i < N; i++) { VoteFor = uint.Parse(Console.ReadLine()); switch (VoteFor) { case 1: cat[0]++; break; case 2: cat[1]++; break; case 3: cat[2]++; break; case 4: cat[3]++; break; case 5: cat[4]++; break; case 6: cat[5]++; break; case 7: cat[6]++; break; case 8: cat[7]++; break; case 9: cat[8]++; break; case 10: cat[9]++; break; default: break; } } for (uint i = 0; i < 10; i++) if (WinnerVotes < cat[i]) { Winner = i+1; WinnerVotes = cat[i]; } Console.WriteLine(Winner); } }
23.52381
53
0.275304
[ "MIT" ]
Ico093/TelerikAcademy
C#1/Exams/C#Part1-SampleExam/MissCat2011/MissCat2011.cs
1,484
C#
using System; //library delegate int Sum(int sum); //delegate namespace TutorialCSharp //namespace { class Program //class { static void Main(string[] args) //method special, automatic run program on this Main method and call a statement { Sum plus = new Sum(Plus); Sum minus = new Sum(Minus); Print print = new Print(Hello); Console.WriteLine(minus(10)); print("Hello World!"); SendHello(print); } delegate void Print(string print); //delegate static int sum = 5; static int Plus(int plus) { sum += plus; return sum; } static int Minus(int minus) { sum -= minus; return sum; } static void Hello(string hello) { Console.WriteLine("Delegate test: {0}", hello); } static void SendHello(Print send) { send("Say Hello!"); } } }
23.409091
120
0.503883
[ "MIT" ]
fauzigalih/TutorialCSharp
data/070 Delegate Type.cs
1,030
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using JetBrains.Annotations; #pragma warning disable SA1649 // File name must match first type name namespace BuildXL.FrontEnd.Script.Util { /// <summary> /// Abstract representation of lightweight array. /// </summary> public interface IReadOnlyArraySlim<out T> { /// <summary> /// The length of the array. /// </summary> int Length { get; } /// <summary> /// Gets the element at the specified index. /// </summary> T this[int index] { get; } /// <summary> /// For performance reasons of copy operation, slim arrays should expose underlying array. /// This is used only for <see cref="StructArraySlimWrapper{T}"/> in <see cref="ReadOnlyArrayExtensions.CopyTo{TArray,T}"/> method /// and should not be used by any other clients. /// </summary> /// <remarks> /// There are other potential solutions for the perf problem, but none of them are perfect. /// For instance, adding CopyTo method to this interface will require generic argument T to be invariant (currently it is contravariant). /// This is possible, but it will require other changes in the entire codebase. /// So current solution with exposing underlying array is not perfect, but not worst. /// </remarks> [CanBeNull] [SuppressMessage("Microsoft.Performance", "CA1819")] T[] UnderlyingArrayUnsafe { get; } } /// <nodoc/> public static class ReadOnlyArrayExtensions { /// <nodoc/> public static void CopyTo<TArray, T>(this TArray array, int sourceIndex, T[] destination, int destinationIndex, int length) where TArray : IReadOnlyArraySlim<T> { // Using more efficient implementation if array is a wrapper around real array. var underlyingArray = array.UnderlyingArrayUnsafe; if (underlyingArray != null) { Array.Copy(underlyingArray, sourceIndex, destination, destinationIndex, length); } // Otherwise (for small arrays) using regular for-based copy. for (int i = 0; i < length; i++) { destination[i + destinationIndex] = array[i + sourceIndex]; } } /// <summary> /// Method that throw an <see cref="IndexOutOfRangeException"/>. /// </summary> /// <remarks> /// This method is not generic which means that the underlying array would be boxed. /// This will lead to additional memory allocation in a failure case, but will /// lead to more readable code, because C# langauge doesn't have partial generic arguments /// inferece. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] public static Exception ThrowOutOfRange<T>(this IReadOnlyArraySlim<T> array, int index) { string message = string.Format( CultureInfo.InvariantCulture, "Index '{0}' was outside the bounds of the array with length '{1}'", index, array.Length); throw new IndexOutOfRangeException(message); } /// <nodoc/> [System.Diagnostics.Contracts.Pure] public static IReadOnlyList<T> ToReadOnlyList<TArray, T>(this TArray array) where TArray : IReadOnlyArraySlim<T> { return new ReadOnlyArrayList<T, TArray>(array); } /// <nodoc/> [System.Diagnostics.Contracts.Pure] public static IReadOnlyList<T> ToReadOnlyList<T>(this IReadOnlyArraySlim<T> array) { return new ReadOnlyArrayList<T, IReadOnlyArraySlim<T>>(array); } private sealed class ReadOnlyArrayList<T, TArray> : IReadOnlyList<T> where TArray : IReadOnlyArraySlim<T> { // Intentionally leaving this field as non-readonly to avoid defensive copy on each access. private readonly TArray m_array; public ReadOnlyArrayList(TArray array) { m_array = array; } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < m_array.Length; i++) { yield return m_array[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count => m_array.Length; public T this[int index] { get { return m_array[index]; } } } } /// <summary> /// Factory class that responsible for creating different struct arrays by different input. /// </summary> internal static class StructArray { /// <nodoc /> public static StructArray0<T> Create<T>() { return default(StructArray0<T>); } /// <nodoc /> public static StructArray1<T> Create<T>(T item) { return new StructArray1<T>(item); } /// <nodoc /> public static StructArray2<T> Create<T>(T item1, T item2) { return new StructArray2<T>(item1, item2); } /// <nodoc /> public static StructArray3<T> Create<T>(T item1, T item2, T item3) { return new StructArray3<T>(item1, item2, item3); } /// <nodoc /> public static StructArray4<T> Create<T>(T item1, T item2, T item3, T item4) { return new StructArray4<T>(item1, item2, item3, item4); } /// <nodoc /> public static StructArray5<T> Create<T>(T item1, T item2, T item3, T item4, T item5) { return new StructArray5<T>(item1, item2, item3, item4, item5); } /// <nodoc /> public static StructArraySlimWrapper<T> Create<T>(T[] items) { return new StructArraySlimWrapper<T>(items); } } /// <summary> /// Lightweight empty struct array. /// </summary> internal readonly struct StructArray0<T> : IReadOnlyArraySlim<T> { public T this[int index] { get { throw this.ThrowOutOfRange(index); } } public int Length => 0; public T[] UnderlyingArrayUnsafe => null; } /// <summary> /// Lightweight struct array that holds one element. /// </summary> internal readonly struct StructArray1<T> : IReadOnlyArraySlim<T> { private readonly T m_item; public StructArray1(T item) { m_item = item; } public T this[int index] { get { if (index != 0) { throw this.ThrowOutOfRange(index); } return m_item; } } public int Length => 1; public T[] UnderlyingArrayUnsafe => null; } /// <summary> /// Lightweight struct array that holds 2 elements. /// </summary> internal readonly struct StructArray2<T> : IReadOnlyArraySlim<T> { private readonly T m_item0; private readonly T m_item1; public StructArray2(T item0, T item1) { m_item0 = item0; m_item1 = item1; } public T this[int index] { get { switch (index) { case 0: return m_item0; case 1: return m_item1; default: throw this.ThrowOutOfRange(index); } } } public int Length => 2; public T[] UnderlyingArrayUnsafe => null; } /// <summary> /// Lightweight struct array that holds 3 elements. /// </summary> internal readonly struct StructArray3<T> : IReadOnlyArraySlim<T> { private readonly T m_item0; private readonly T m_item1; private readonly T m_item2; public StructArray3(T item0, T item1, T item2) { m_item0 = item0; m_item1 = item1; m_item2 = item2; } public T this[int index] { get { switch (index) { case 0: return m_item0; case 1: return m_item1; case 2: return m_item2; default: throw this.ThrowOutOfRange(index); } } } public int Length => 3; public T[] UnderlyingArrayUnsafe => null; } /// <summary> /// Lightweight struct array that holds 4 elements. /// </summary> internal readonly struct StructArray4<T> : IReadOnlyArraySlim<T> { private readonly T m_item0; private readonly T m_item1; private readonly T m_item2; private readonly T m_item3; public StructArray4(T item0, T item1, T item2, T item3) { m_item0 = item0; m_item1 = item1; m_item2 = item2; m_item3 = item3; } public T this[int index] { get { switch (index) { case 0: return m_item0; case 1: return m_item1; case 2: return m_item2; case 3: return m_item3; default: throw this.ThrowOutOfRange(index); } } } public int Length => 4; public T[] UnderlyingArrayUnsafe => null; } /// <summary> /// Lightweight struct array that holds 5 elements. /// </summary> internal readonly struct StructArray5<T> : IReadOnlyArraySlim<T> { private readonly T m_item0; private readonly T m_item1; private readonly T m_item2; private readonly T m_item3; private readonly T m_item4; public StructArray5(T item0, T item1, T item2, T item3, T item4) { m_item0 = item0; m_item1 = item1; m_item2 = item2; m_item3 = item3; m_item4 = item4; } public T this[int index] { get { switch (index) { case 0: return m_item0; case 1: return m_item1; case 2: return m_item2; case 3: return m_item3; case 4: return m_item4; default: throw this.ThrowOutOfRange(index); } } } public int Length => 5; public T[] UnderlyingArrayUnsafe => null; } /// <summary> /// Lightweight struct array that holds one element. /// </summary> internal readonly struct StructArraySlimWrapper<T> : IReadOnlyArraySlim<T> { private readonly T[] m_items; /// <nodoc/> public StructArraySlimWrapper(T[] items) { m_items = items; } /// <inheritdoc/> public T this[int index] { get { return m_items[index]; } } /// <inheritdoc/> public int Length => m_items.Length; /// <inheritdoc/> public T[] UnderlyingArrayUnsafe => m_items; } }
30.06235
146
0.498165
[ "MIT" ]
BearerPipelineTest/BuildXL
Public/Src/FrontEnd/Script/Util/StructArray.cs
12,536
C#
using NUnit.Framework; using SimpleEventSourcing.Tests; namespace SimpleEventSourcing.EntityFramework.Tests { [TestFixture] public class PersistenceEngineEntityFrameworkTests : PersistenceEngineTests { public PersistenceEngineEntityFrameworkTests() : base(new EntityFrameworkTestConfig()) { } } }
22.9375
80
0.686649
[ "MIT" ]
warappa/SimpleEventSourcing
SimpleEventSourcing.EntityFramework.Tests/WriteModel/PersistenceEngineEntityFrameworkTests.cs
369
C#
using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.Storage; using Windows.System.UserProfile; using Unsplasharp.Models; using Tasks.Data; using Unsplasharp; namespace Tasks { public sealed class WallUpdater : IBackgroundTask { #region variables BackgroundTaskDeferral _Deferral; private static string WallTaskName { get { return "WallUpdaterTask"; } } private static string LockscreenTaskName { get { return "LockscreenUpdaterTask"; } } private static string BestPhotoResolutionKey { get { return "BestPhotoResolution"; } } #endregion variables /// <summary> /// Task's Entry Point /// </summary> /// <param name="taskInstance">Task starting the method</param> async void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance) { taskInstance.Canceled += OnCanceled; _Deferral = taskInstance.GetDeferral(); SaveTime(taskInstance); Photo photo = await GetRandom(); var urlFormat = ChooseBestPhotoFormat(photo); StorageFile file = await DownloadImagefromServer(urlFormat, photo.Id); if (taskInstance.Task.Name == WallTaskName) { await SetWallpaperAsync(file); } else { await SetLockscreenAsync(file); } //SaveLockscreenBackgroundName(lockImage.Name); //SaveAppBackground(lockImage); _Deferral.Complete(); } string GetActivityKey(IBackgroundTaskInstance instance) { string key = instance.Task.Name == WallTaskName ? WallTaskName : LockscreenTaskName; key += "Activity"; return key; } private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { // Indicate that the background task is canceled. string key = GetActivityKey(sender); ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; ApplicationDataCompositeValue activityError = new ApplicationDataCompositeValue { ["DateTime"] = DateTime.Now.ToLocalTime(), ["Exception"] = reason.ToString() }; localSettings.Values[key] = activityError; } private void SaveTime(IBackgroundTaskInstance instance) { var key = GetActivityKey(instance); ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; ApplicationDataCompositeValue stats = new ApplicationDataCompositeValue { ["DateTime"] = DateTime.Now.ToString(), ["Exception"] = null }; localSettings.Values[key] = stats; } private async Task<Photo> GetRandom() { var client = new UnsplasharpClient(Credentials.ApplicationId); return await client.GetRandomPhoto(); } private async Task<StorageFile> DownloadImagefromServer(string URI, string filename) { filename += ".png"; var rootFolder = ApplicationData.Current.LocalFolder; var coverpic = await rootFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); try { HttpClient client = new HttpClient(); byte[] buffer = await client.GetByteArrayAsync(URI); // Download file using (Stream stream = await coverpic.OpenStreamForWriteAsync()) stream.Write(buffer, 0, buffer.Length); // Save return coverpic; } catch { return null; } } // Pass in a relative path to a file inside the local appdata folder private async Task<bool> SetLockscreenAsync(StorageFile file) { bool success = false; if (UserProfilePersonalizationSettings.IsSupported()) { UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current; success = await profileSettings.TrySetLockScreenImageAsync(file); } return success; } private async Task<bool> SetWallpaperAsync(StorageFile file) { bool success = false; if (UserProfilePersonalizationSettings.IsSupported()) { UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current; success = await profileSettings.TrySetWallpaperImageAsync(file); } return success; } private string ChooseBestPhotoFormat(Photo photo) { var url = photo.Urls.Raw; ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; if (!localSettings.Values.ContainsKey(BestPhotoResolutionKey)) { return url; } localSettings.Values.TryGetValue(BestPhotoResolutionKey, out var resolution); var format = (string)resolution; switch (format) { case "small": url = photo.Urls.Small; break; case "regular": url = photo.Urls.Regular; break; case "full": url = photo.Urls.Full; break; default: break; } return url; } } }
34.593939
112
0.59513
[ "MIT" ]
rootasjey/Hangon
Tasks/WallUpdater.cs
5,710
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SelfServiceConfigXmlEditor.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.870968
151
0.587419
[ "MIT" ]
Draeniky/Office-IT-Pro-Deployment-Scripts
Office-ProPlus-Deployment/SelfServiceWebDeployment/SelfServiceConfigXmlEditor/Properties/Settings.Designer.cs
1,083
C#
using Alphaleonis.Win32.Vss; using BitShelter.Agent.Controls; using BitShelter.Models; using BitShelter.Models.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitShelter.Agent.Forms { partial class EditSnapshotRuleForm { public void InitBaseAdvanced() { cbSnapContext.FillWithEnum(VssSnapshotContextInternal.ClientAccessible); cbSnapType.FillWithEnum(VssBackupTypeInternal.Incremental); cbPruningStrategy.FillWithEnum(PruningStrategy.Global); cbSnapFailRestartVSS.Enabled = cbPruningStrategy.Enabled = false; // FIXME } public void InitEditAdvanced(SnapshotRule rule) { cbSnapContext.SelectedIndex = cbSnapContext.Items.IndexOf(rule.VssContext); cbSnapType.SelectedIndex = cbSnapType.Items.IndexOf(rule.VssBackupType); tbSnapInclWriters.Text = String.Join(",", rule.VssIncludeWriters); tbSnapExclWriters.Text = String.Join(",", rule.VssExcludeWriters); nbSnapFailRetryCount.Value = rule.MaxRetryCount; cbSnapFailRestartVSS.Checked = rule.RetryRestartVSSService; //cbPruningStrategy.SelectedIndex = cbPruningStrategy.Items.IndexOf(rule.PruningStrategy); } // // Misc private void FillAdvanced(SnapshotRule rule) { rule.VssContext = (VssSnapshotContextInternal)cbSnapContext.SelectedValue; rule.VssBackupType = (VssBackupTypeInternal)cbSnapType.SelectedValue; rule.VssIncludeWriters = new List<string>(tbSnapInclWriters.Text.Split(',')); rule.VssExcludeWriters = new List<string>(tbSnapExclWriters.Text.Split(',')); rule.MaxRetryCount = (int)nbSnapFailRetryCount.Value; rule.RetryRestartVSSService = cbSnapFailRestartVSS.Checked; //rule.PruningStrategy = (PruningStrategy)cbPruningStrategy.SelectedItem; } // // Validation public void ValidateAdvanced() { //Valid = ValidateGeneric(() => ) } } }
32.83871
97
0.720039
[ "MIT" ]
alexis-/BitShelter
BitShelter.Agent/Forms/EditSnapshotRuleForm.Advanced.cs
2,038
C#
using System.Reflection; using SentinelMission; using HarmonyLib; using KSP.Localization; using UnityEngine; namespace KERBALISM { public class KerbalismSentinel : SentinelModule, IContractObjectiveModule { // ec consumed per-second [KSPField] public double ec_rate = 0.0; // required comms data rate in Mb/s [KSPField] public double comms_rate = 0.0; // track user activation independentely of the current isTracking state, // in order to have the stock SentinelMission scenario still work while we can // alter isTracking to reflect the powered/connected state of the module. [KSPField(isPersistant = true)] public bool isTrackingEnabled; // trick the stock generator check by making the sentinel module itself a generator contract objective public string GetContractObjectiveType() { return "Generator"; } public bool CheckContractObjectiveValidity() { return true; } public override void OnStart(StartState state) { if (isTrackingEnabled) { base.Events["StartTracking"].active = false; base.Events["StopTracking"].active = true; } else { base.Events["StartTracking"].active = true; base.Events["StopTracking"].active = false; } } public static void BackgroundUpdate(Vessel v, ProtoPartModuleSnapshot m, KerbalismSentinel prefab, VesselData vd, ResourceInfo ec, double elapsed_s) { if (Lib.Proto.GetBool(m, "isTrackingEnabled")) { if (!vd.Connection.linked || vd.Connection.rate < prefab.comms_rate) { Lib.Proto.Set(m, "isTracking", false); return; } ec.Consume(prefab.ec_rate * elapsed_s, ResourceBroker.Scanner); if (ec.Amount <= double.Epsilon) { Lib.Proto.Set(m, "isTracking", false); return; } Lib.Proto.Set(m, "isTracking", true); } } public static void ApplyHarmonyPatches(Harmony harmonyInstance) { if (!Features.Science) { return; } MethodInfo startTracking = typeof(SentinelModule).GetMethod("StartTracking", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo startTrackingPostfix = typeof(KerbalismSentinel).GetMethod("StartTrackingPostfix", BindingFlags.Static | BindingFlags.NonPublic); harmonyInstance.Patch(startTracking, null, new HarmonyMethod(startTrackingPostfix)); MethodInfo stopTracking = typeof(SentinelModule).GetMethod("StopTracking", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo stopTrackingPostfix = typeof(KerbalismSentinel).GetMethod("StopTrackingPostfix", BindingFlags.Static | BindingFlags.NonPublic); harmonyInstance.Patch(stopTracking, null, new HarmonyMethod(stopTrackingPostfix)); MethodInfo fixedUpdate = typeof(SentinelModule).GetMethod("FixedUpdate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo fixedUpdatePrefix = typeof(KerbalismSentinel).GetMethod("FixedUpdatePrefix", BindingFlags.Static | BindingFlags.NonPublic); harmonyInstance.Patch(fixedUpdate, new HarmonyMethod(fixedUpdatePrefix)); MethodInfo telescopeCanActivate = typeof(SentinelModule).GetMethod("TelescopeCanActivate", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo telescopeCanActivatePrefix = typeof(KerbalismSentinel).GetMethod("TelescopeCanActivatePrefix", BindingFlags.Static | BindingFlags.NonPublic); harmonyInstance.Patch(telescopeCanActivate, new HarmonyMethod(telescopeCanActivatePrefix)); } private static void StartTrackingPostfix(KerbalismSentinel __instance) { if (__instance.isTracking) { __instance.isTrackingEnabled = true; __instance.isTracking = false; } else { __instance.isTrackingEnabled = false; } } private static void StopTrackingPostfix(KerbalismSentinel __instance) { __instance.isTrackingEnabled = false; } private static bool FixedUpdatePrefix(KerbalismSentinel __instance) { if (__instance.isTrackingEnabled) { VesselData vd = __instance.vessel.KerbalismData(); if (!vd.Connection.linked || vd.Connection.rate < __instance.comms_rate) { __instance.isTracking = false; __instance.status = "Comms connection too weak"; return false; } ResourceInfo ec = ResourceCache.GetResource(__instance.vessel, "ElectricCharge"); ec.Consume(__instance.ec_rate * Kerbalism.elapsed_s, ResourceBroker.Scanner); if (ec.Amount <= double.Epsilon) { __instance.isTracking = false; __instance.status = Local.Module_Experiment_issue4; // "no Electricity" return false; } __instance.isTracking = true; } return true; } private static bool TelescopeCanActivatePrefix(KerbalismSentinel __instance, ref bool __result) { if (__instance.vessel.orbit.referenceBody != Planetarium.fetch.Sun) { string msg = Localizer.Format("#autoLOC_6002295", SentinelUtilities.SentinelPartTitle); ScreenMessages.PostScreenMessage(msg, SentinelUtilities.CalculateReadDuration(msg), ScreenMessageStyle.UPPER_CENTER); __result = false; } __result = true; return false; } public override string GetModuleDisplayName() { return Localizer.Format("#autoLOC_6002283"); } public override string GetInfo() { Specifics specs = new Specifics(); specs.Add(Lib.Color(Local.Module_Experiment_Specifics_info8, Lib.Kolor.Cyan, true));//"Needs:" if (ec_rate > 0.0) specs.Add(Local.Module_Experiment_Specifics_info9, Lib.HumanReadableRate(ec_rate));//"EC" if (comms_rate > 0.0) specs.Add(Local.Module_Experiment_Specifics_info2, Lib.HumanReadableDataRate(comms_rate)); // "Data rate" return specs.Info(); } } }
34.229412
165
0.724867
[ "Unlicense" ]
Bellabong/Kerbalism
src/Kerbalism/Modules/KebalismSentinel.cs
5,652
C#
using System; using System.Net.Http; using System.Threading.Tasks; namespace Discord_UncrateGO_SkinCasesGenerator { /// <summary> /// Handles fetching html data from internet /// </summary> internal static class HtmlFetcher { public static async Task<string> RetrieveFromUrl(string url) { try { using (HttpClient client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(url)) using (HttpContent content = response.Content) { string result = await content.ReadAsStringAsync(); Logger.Log($"Fetched site at URL {url}", Logger.LogLevel.Debug); return result; } } catch (Exception) { Logger.Log("Failed to retrieve from url | " + url, Logger.LogLevel.Error); return ""; } } } }
28
90
0.527778
[ "MIT" ]
jaihysc/Csgo-CaseDataFetcher
Discord-UncrateGO-SkinCasesGenerator/HtmlFetcher.cs
1,010
C#
// Copyright (c) Brian Reichle. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; namespace CausalityDbg.Core { static partial class NativeMethods { // HRESULT CLRCreateInstance( // [in] REFCLSID clsid, // [in] REFIID riid, // [out] LPVOID *ppInterface // ); [DllImport("mscoree.dll")] public static extern void CLRCreateInstance( [MarshalAs(UnmanagedType.LPStruct)] Guid clsid, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, [MarshalAs(UnmanagedType.Interface)] out object metahostInterface); } }
32.380952
164
0.720588
[ "Apache-2.0" ]
brian-reichle/CausalityDbg
src/CausalityDbg.Core/Native/Win32/NativeMethods.MsCorEE.cs
680
C#
using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using AgentMulder.ReSharper.Domain.Patterns; using AgentMulder.ReSharper.Domain.Registrations; using AgentMulder.ReSharper.Domain.Utils; using JetBrains.ReSharper.Feature.Services.CSharp.StructuralSearch; using JetBrains.ReSharper.Feature.Services.CSharp.StructuralSearch.Placeholders; using JetBrains.ReSharper.Feature.Services.StructuralSearch; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace AgentMulder.Containers.SimpleInjector.Patterns { [Export("ComponentRegistration", typeof(IRegistrationPattern))] public class RegisterAll : RegisterWithService { private static readonly IStructuralSearchPattern pattern = new CSharpStructuralSearchPattern("$container$.RegisterAll($arguments$)", new ExpressionPlaceholder("container", "global::SimpleInjector.Container", true), new ArgumentPlaceholder("arguments", -1, -1)); public RegisterAll() : base(pattern) { } protected override IEnumerable<IComponentRegistration> FromGenericArguments(IInvocationExpression invocationExpression) { var serviceType = invocationExpression.TypeArguments.First() as IDeclaredType; if (serviceType == null) { yield break; } var typeElement = serviceType.GetTypeElement(); if (typeElement == null) { yield break; } IEnumerable<ITypeElement> concreteTypes = invocationExpression.Arguments.SelectMany(argument => argument.Value.GetRegisteredTypes()); yield return CreateRegistrations(invocationExpression, typeElement, concreteTypes); } protected override IEnumerable<IComponentRegistration> FromArguments(IInvocationExpression invocationExpression) { if (invocationExpression.Arguments.Count != 2) { yield break; } ICSharpArgument arg1 = invocationExpression.Arguments.First(); ITypeElement typeElement = arg1.With(f => f.Value as ITypeofExpression) .With(f => f.ArgumentType as IDeclaredType) .With(f => f.GetTypeElement()); if (typeElement == null) { yield break; } ICSharpArgument arg2 = invocationExpression.Arguments.Last(); IEnumerable<ITypeElement> concreteTypes = arg2.With(f => f.Value) .With(f => f.GetRegisteredTypes()).ToList(); if (concreteTypes.Any()) { yield return CreateRegistrations(invocationExpression, typeElement, concreteTypes); } } private static IComponentRegistration CreateRegistrations(IInvocationExpression invocationExpression, ITypeElement serviceType, IEnumerable<ITypeElement> concreteTypes) { return new TypesBasedOnRegistration(concreteTypes, new ServiceRegistration(invocationExpression, serviceType)); } } }
41.164557
176
0.649139
[ "MIT" ]
ERNICommunity/AgentMulder
src/AgentMulder.Containers.SimpleInjector/Patterns/RegisterAll.cs
3,254
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Sumo.Data { [TestClass] public class SqlReader_Tests { [TestMethod] public void NotFinished() { Assert.Fail($"todo: implement {GetType().FullName}"); } } }
18.666667
65
0.596429
[ "MIT" ]
SumoSoftware/Data
test/Test.Sumo.Data/Core/Readers/SqlReader_Tests.cs
282
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; internal partial class Interop { internal partial class Kernel32 { /// <summary> /// WARNING: This method does not implicitly handle long paths. Use GetFullPath/PathHelper. /// </summary> [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)] internal static extern uint GetLongPathNameW(ref char lpszShortPath, ref char lpszLongPath, uint cchBuffer); } }
40.111111
133
0.722992
[ "MIT" ]
Azure-2019/corefx
src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs
722
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace SkbKontur.Cassandra.DistributedTaskQueue.Monitoring.TestService { public static class MonitoringServiceEntryPoint { public static void Main(string[] args) { Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()) .Build() .Run(); } } }
29.0625
89
0.647312
[ "MIT" ]
skbkontur/cassandra-distributed-task-queue
Cassandra.DistributedTaskQueue.Monitoring.TestService/MonitoringServiceEntryPoint.cs
467
C#
/* Copyright (C) 2020 Jean-Camille Tournier ([email protected]) This file is part of QLCore Project https://github.com/OpenDerivatives/QLCore QLCore is free software: you can redistribute it and/or modify it under the terms of the QLCore and QLNet license. You should have received a copy of the license along with this program; if not, license is available at https://github.com/OpenDerivatives/QLCore/LICENSE. QLCore is a forked of QLNet which is a based on QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ The QuantLib license is available online at http://quantlib.org/license.shtml and the QLNet license is available online at https://github.com/amaggiulli/QLNet/blob/develop/LICENSE. 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 PARTICAR PURPOSE. See the license for more details. */ using System; using System.Collections.Generic; namespace QLCore { //! %Abcd functional form /*! \f[ f(t) = [ a + b*t ] e^{-c*t} + d \f] following Rebonato's notation. */ public class AbcdMathFunction { public AbcdMathFunction(double a = 0.002, double b = 0.001, double c = 0.16, double d = 0.0005) { a_ = a; b_ = b; c_ = c; d_ = d; abcd_ = new InitializedList<double>(4); dabcd_ = new InitializedList<double>(4); abcd_[0] = a_; abcd_[1] = b_; abcd_[2] = c_; abcd_[3] = d_; initialize_(); } public AbcdMathFunction(List<double> abcd) { abcd_ = new List<double>(abcd); dabcd_ = new InitializedList<double>(4); a_ = abcd_[0]; b_ = abcd_[1]; c_ = abcd_[2]; d_ = abcd_[3]; initialize_(); } //! function value at time t: \f[ f(t) \f] public double value(double t) { return t < 0 ? 0.0 : (a_ + b_ * t) * Math.Exp(-c_ * t) + d_; } //! time at which the function reaches maximum (if any) public double maximumLocation() { if (b_ .IsEqual(0.0)) { if (a_ >= 0.0) return 0.0; else return Double.MaxValue; } // stationary point // TODO check if minimum // TODO check if maximum at +inf double zeroFirstDerivative = 1.0 / c_ - a_ / b_; return (zeroFirstDerivative > 0.0 ? zeroFirstDerivative : 0.0); } //! maximum value of the function public double maximumValue() { if (b_.IsEqual(0.0) || a_ <= 0.0) return d_; return this.value(maximumLocation()); } //! function value at time +inf: \f[ f(\inf) \f] public double longTermValue() { return d_; } /*! first derivative of the function at time t \f[ f'(t) = [ (b-c*a) + (-c*b)*t) ] e^{-c*t} \f] */ public double derivative(double t) { return t < 0 ? 0.0 : (da_ + db_ * t) * Math.Exp(-c_ * t); } /*! indefinite integral of the function at time t \f[ \int f(t)dt = [ (-a/c-b/c^2) + (-b/c)*t ] e^{-c*t} + d*t \f] */ public double primitive(double t) { return t < 0 ? 0.0 : (pa_ + pb_ * t) * Math.Exp(-c_ * t) + d_ * t + K_; } /*! definite integral of the function between t1 and t2 \f[ \int_{t1}^{t2} f(t)dt \f] */ public double definiteIntegral(double t1, double t2) { return primitive(t2) - primitive(t1); } /*! Inspectors */ public double a() { return a_; } public double b() { return b_; } public double c() { return c_; } public double d() { return d_; } public List<double> coefficients() { return abcd_; } public List<double> derivativeCoefficients() { return dabcd_; } // the primitive is not abcd /*! coefficients of a AbcdMathFunction defined as definite integral on a rolling window of length tau, with tau = t2-t */ public List<double> definiteIntegralCoefficients(double t, double t2) { double dt = t2 - t; double expcdt = Math.Exp(-c_ * dt); List<double> result = new InitializedList<double>(4); result[0] = diacplusbcc_ - (diacplusbcc_ + dibc_ * dt) * expcdt; result[1] = dibc_ * (1.0 - expcdt); result[2] = c_; result[3] = d_ * dt; return result; } /*! coefficients of a AbcdMathFunction defined as definite derivative on a rolling window of length tau, with tau = t2-t */ public List<double> definiteDerivativeCoefficients(double t, double t2) { double dt = t2 - t; double expcdt = Math.Exp(-c_ * dt); List<double> result = new InitializedList<double>(4); result[1] = b_ * c_ / (1.0 - expcdt); result[0] = a_ * c_ - b_ + result[1] * dt * expcdt; result[0] /= 1.0 - expcdt; result[2] = c_; result[3] = d_ / dt; return result; } public static void validate(double a, double b, double c, double d) { Utils.QL_REQUIRE(c > 0, () => "c (" + c + ") must be positive"); Utils.QL_REQUIRE(d >= 0, () => "d (" + d + ") must be non negative"); Utils.QL_REQUIRE(a + d >= 0, () => "a+d (" + a + "+" + d + ") must be non negative"); if (b >= 0.0) return; // the one and only stationary point... double zeroFirstDerivative = 1.0 / c - a / b; if (zeroFirstDerivative >= 0.0) { // ... is a minimum // must be abcd(zeroFirstDerivative)>=0 Utils.QL_REQUIRE(b >= -(d * c) / Math.Exp(c * a / b - 1.0), () => "b (" + b + ") less than " + -(d * c) / Math.Exp(c * a / b - 1.0) + ": negative function value at stationary point " + zeroFirstDerivative); } } protected double a_, b_, c_, d_; private void initialize_() { validate(a_, b_, c_, d_); da_ = b_ - c_ * a_; db_ = -c_ * b_; dabcd_[0] = da_; dabcd_[1] = db_; dabcd_[2] = c_; dabcd_[3] = 0.0; pa_ = -(a_ + b_ / c_) / c_; pb_ = -b_ / c_; K_ = 0.0; dibc_ = b_ / c_; diacplusbcc_ = a_ / c_ + dibc_ / c_; } private List<double> abcd_; private List<double> dabcd_; private double da_, db_; private double pa_, pb_, K_; private double dibc_, diacplusbcc_; } }
33.253731
140
0.54234
[ "BSD-3-Clause" ]
OpenDerivatives/QLCore
QLCore/Math/AbcdMathFunction.cs
6,686
C#
using DotNetNuke.Entities.Users; using System.Collections.Generic; using System.Linq; using Vanjaro.Common.Engines.UIEngine.AngularBootstrap; using Vanjaro.Common.Entities.Apps; namespace Vanjaro.UXManager.Extensions.Menu.MemberProfile.Factories { public class AppFactory { private const string ModuleRuntimeVersion = "1.0.0"; internal static string GetAllowedRoles(string Identifier) { AngularView template = GetViews().Where(t => t.Identifier == Identifier).FirstOrDefault(); if (template != null) { return template.AccessRoles; } return string.Empty; } public static List<AngularView> Views = new List<AngularView>(); public static List<AngularView> GetViews() { AngularView memberprofile_memberprofile = new AngularView { AccessRoles = "admin", UrlPaths = new List<string> { "memberprofile" }, IsDefaultTemplate = true, TemplatePath = "MemberProfile/memberprofile.html", Identifier = Identifier.memberprofile_memberprofile.ToString(), Defaults = new Dictionary<string, string> { } }; Views.Add(memberprofile_memberprofile); AngularView Addmemberprofile = new AngularView { AccessRoles = "admin", UrlPaths = new List<string> { "memberprofilesettings" }, IsDefaultTemplate = false, TemplatePath = "memberprofile/memberprofilesettings.html", Identifier = Identifier.memberprofile_memberprofilesettings.ToString(), Defaults = new Dictionary<string, string> { } }; Views.Add(Addmemberprofile); AngularView Updatememberprofile = new AngularView { AccessRoles = "admin", UrlPaths = new List<string> { "memberprofilesettings/:mpid" }, IsDefaultTemplate = false, TemplatePath = "memberprofile/memberprofilesettings.html", Identifier = Identifier.memberprofile_memberprofilesettings.ToString(), Defaults = new Dictionary<string, string> { } }; Views.Add(Updatememberprofile); AngularView setting = new AngularView { AccessRoles = "admin", UrlPaths = new List<string> { "settings" }, IsDefaultTemplate = false, TemplatePath = "memberprofile/settings.html", Identifier = Identifier.memberprofile_settings.ToString(), Defaults = new Dictionary<string, string> { } }; Views.Add(setting); return Views; } public static string GetAccessRoles(UserInfo UserInfo) { List<string> AccessRoles = new List<string>(); if (UserInfo.UserID > 0) { AccessRoles.Add("user"); } else { AccessRoles.Add("anonymous"); } if (UserInfo.UserID > -1 && (UserInfo.IsInRole("Administrators"))) { AccessRoles.Add("admin"); } if (UserInfo.IsSuperUser) { AccessRoles.Add("host"); } return string.Join(",", AccessRoles); } public static AppInformation GetAppInformation() { return new AppInformation(ExtensionInfo.Name, ExtensionInfo.FriendlyName, ExtensionInfo.GUID, GetRuntimeVersion, "http://www.mandeeps.com/store", "http://www.mandeeps.com/Activation", 14, 7, new List<string> { "Domain", "Server" }, false); } public AppInformation AppInformation => GetAppInformation(); public static string GetRuntimeVersion { get { try { return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); } catch { } return ModuleRuntimeVersion; } } public enum Identifier { common_licensing, common_activation, memberprofile_settings, memberprofile_memberprofile, memberprofile_memberprofilesettings } } }
35.92126
251
0.546471
[ "MIT" ]
dowdian/VanjaroPlatform
DesktopModules/Vanjaro/UXManager/Extensions/Menu/MemberProfile/Factories/AppFactory.cs
4,564
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using Xunit; namespace System.Globalization.CalendarsTests { // System.Globalization.TaiwanCalendar.ToDateTime(Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32) public class TaiwanCalendarToDateTime { #region Positive Tests // PosTest1: Verify the year is a random year [Fact] public void PosTest1() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era = 0; for (int i = 0; i < tc.Eras.Length; i++) { era = tc.Eras[i]; DateTime dt = tc.ToDateTime(year, month, day, hour, minute, second, milliSecond); DateTime desiredDT = new DateTime(year + 1911, month, day, hour, minute, second, milliSecond); Assert.Equal(desiredDT, dt); } } // PosTest2: Verify the DateTime is 8088-12-31 23:59:29:999 [Fact] public void PosTest2() { System.Globalization.Calendar tc = new TaiwanCalendar(); int year = 8088; int month = 12; int day = 31; int hour = 23; int minute = 59; int second = 59; int milliSecond = 999; int era; for (int i = 0; i < tc.Eras.Length; i++) { era = tc.Eras[i]; DateTime dt = tc.ToDateTime(year, month, day, hour, minute, second, milliSecond); DateTime desireDT = new DateTime(year + 1911, month, day, hour, minute, second, milliSecond); Assert.Equal(desireDT, dt); } } // PosTest3: Verify the DateTime is TaiwanCalendar MinSupportedDateTime [Fact] public void PosTest3() { System.Globalization.Calendar tc = new TaiwanCalendar(); DateTime minDT = tc.MinSupportedDateTime; int year = 1; int month = 1; int day = 1; int hour = 0; int minute = 0; int second = 0; int milliSecond = 0; int era; for (int i = 0; i < tc.Eras.Length; i++) { era = tc.Eras[i]; DateTime dt = tc.ToDateTime(year, month, day, hour, minute, second, milliSecond); Assert.Equal(minDT, dt); } } #endregion #region Negative Tests // NegTest1: The year outside the range supported by the TaiwanCalendar [Fact] public void NegTest1() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MaxSupportedDateTime.Year - 1910, Int32.MaxValue); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); year = rand.Next(Int32.MinValue, tc.MinSupportedDateTime.Year); era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest2: The month outside the range supported by the TaiwanCalendar [Fact] public void NegTest2() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(Int32.MinValue, 1); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); month = rand.Next(13, Int32.MaxValue); era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest3: The day outside the range supported by the TaiwanCalendar [Fact] public void NegTest3() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(Int32.MinValue, 1); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); day = rand.Next(tc.GetDaysInMonth(year, month, era) + 1, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest4: The hour is less than zero or greater than 23 [Fact] public void NegTest4() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(Int32.MinValue, 0); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); hour = rand.Next(24, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest5: The minute is less than zero or greater than 59 [Fact] public void NegTest5() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(Int32.MinValue, 0); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); //minute greater than 59; minute = rand.Next(60, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest6: The second is less than zero or greater than 59 [Fact] public void NegTest6() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(Int32.MinValue, 0); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); //second greater than 59; second = rand.Next(60, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest7: The milliSecond is less than zero or greater than 999 [Fact] public void NegTest7() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(Int32.MinValue, 0); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); //milliSecond greater than 999; second = rand.Next(1000, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } #endregion } }
38.280702
110
0.529239
[ "MIT" ]
benjamin-bader/corefx
src/System.Globalization.Calendars/tests/TaiwanCalendar/TaiwanCalendarToDateTime.cs
10,910
C#
namespace Win.Tienda { partial class FormMenu { /// <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.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.mantenimientoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mantenimiento1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mantenimiento2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.transaccionesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.transaccion1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reportesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reporte1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reporte2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reporte3ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.seguridadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.loginToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.usuariosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mantenimientoToolStripMenuItem, this.transaccionesToolStripMenuItem, this.reportesToolStripMenuItem, this.seguridadToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(504, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // mantenimientoToolStripMenuItem // this.mantenimientoToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mantenimiento1ToolStripMenuItem, this.mantenimiento2ToolStripMenuItem}); this.mantenimientoToolStripMenuItem.Name = "mantenimientoToolStripMenuItem"; this.mantenimientoToolStripMenuItem.Size = new System.Drawing.Size(68, 20); this.mantenimientoToolStripMenuItem.Text = "Producto"; // // mantenimiento1ToolStripMenuItem // this.mantenimiento1ToolStripMenuItem.Name = "mantenimiento1ToolStripMenuItem"; this.mantenimiento1ToolStripMenuItem.Size = new System.Drawing.Size(116, 22); this.mantenimiento1ToolStripMenuItem.Text = "Modelo"; this.mantenimiento1ToolStripMenuItem.Click += new System.EventHandler(this.mantenimiento1ToolStripMenuItem_Click); // // mantenimiento2ToolStripMenuItem // this.mantenimiento2ToolStripMenuItem.Name = "mantenimiento2ToolStripMenuItem"; this.mantenimiento2ToolStripMenuItem.Size = new System.Drawing.Size(116, 22); this.mantenimiento2ToolStripMenuItem.Text = "Clientes"; this.mantenimiento2ToolStripMenuItem.Click += new System.EventHandler(this.mantenimiento2ToolStripMenuItem_Click); // // transaccionesToolStripMenuItem // this.transaccionesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.transaccion1ToolStripMenuItem}); this.transaccionesToolStripMenuItem.Name = "transaccionesToolStripMenuItem"; this.transaccionesToolStripMenuItem.Size = new System.Drawing.Size(92, 20); this.transaccionesToolStripMenuItem.Text = "Transacciones"; // // transaccion1ToolStripMenuItem // this.transaccion1ToolStripMenuItem.Name = "transaccion1ToolStripMenuItem"; this.transaccion1ToolStripMenuItem.Size = new System.Drawing.Size(113, 22); this.transaccion1ToolStripMenuItem.Text = "Factura"; this.transaccion1ToolStripMenuItem.Click += new System.EventHandler(this.transaccion1ToolStripMenuItem_Click); // // reportesToolStripMenuItem // this.reportesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.reporte1ToolStripMenuItem, this.reporte2ToolStripMenuItem, this.reporte3ToolStripMenuItem}); this.reportesToolStripMenuItem.Name = "reportesToolStripMenuItem"; this.reportesToolStripMenuItem.Size = new System.Drawing.Size(65, 20); this.reportesToolStripMenuItem.Text = "Reportes"; // // reporte1ToolStripMenuItem // this.reporte1ToolStripMenuItem.Name = "reporte1ToolStripMenuItem"; this.reporte1ToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.reporte1ToolStripMenuItem.Text = "Reporte de Modelos"; this.reporte1ToolStripMenuItem.Click += new System.EventHandler(this.reporte1ToolStripMenuItem_Click); // // reporte2ToolStripMenuItem // this.reporte2ToolStripMenuItem.Name = "reporte2ToolStripMenuItem"; this.reporte2ToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.reporte2ToolStripMenuItem.Text = "Reporte de Clientes"; this.reporte2ToolStripMenuItem.Click += new System.EventHandler(this.reporte2ToolStripMenuItem_Click); // // reporte3ToolStripMenuItem // this.reporte3ToolStripMenuItem.Name = "reporte3ToolStripMenuItem"; this.reporte3ToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.reporte3ToolStripMenuItem.Text = "Reporte de Facturas"; this.reporte3ToolStripMenuItem.Click += new System.EventHandler(this.reporte3ToolStripMenuItem_Click); // // seguridadToolStripMenuItem // this.seguridadToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.loginToolStripMenuItem, this.usuariosToolStripMenuItem}); this.seguridadToolStripMenuItem.Name = "seguridadToolStripMenuItem"; this.seguridadToolStripMenuItem.Size = new System.Drawing.Size(72, 20); this.seguridadToolStripMenuItem.Text = "Seguridad"; // // loginToolStripMenuItem // this.loginToolStripMenuItem.Name = "loginToolStripMenuItem"; this.loginToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.loginToolStripMenuItem.Text = "Login"; this.loginToolStripMenuItem.Click += new System.EventHandler(this.loginToolStripMenuItem_Click); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1}); this.statusStrip1.Location = new System.Drawing.Point(0, 371); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(504, 22); this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(50, 17); this.toolStripStatusLabel1.Text = "Usuario:"; // // usuariosToolStripMenuItem // this.usuariosToolStripMenuItem.Name = "usuariosToolStripMenuItem"; this.usuariosToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.usuariosToolStripMenuItem.Text = "Usuarios"; this.usuariosToolStripMenuItem.Click += new System.EventHandler(this.usuariosToolStripMenuItem_Click); // // FormMenu // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.BackgroundImage = global::Win.Tienda.Properties.Resources.a3570047_a6f4_467f_ab14_8cb5ccf3b4ed; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.ClientSize = new System.Drawing.Size(504, 393); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.menuStrip1); this.IsMdiContainer = true; this.MainMenuStrip = this.menuStrip1; this.Name = "FormMenu"; this.Text = "Menú Principal"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.FormMenu_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem mantenimientoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mantenimiento1ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mantenimiento2ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem transaccionesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem transaccion1ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reportesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reporte1ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reporte2ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reporte3ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem seguridadToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem loginToolStripMenuItem; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.ToolStripMenuItem usuariosToolStripMenuItem; } }
54.632075
126
0.664997
[ "MIT" ]
Roxanadubon1/Ventas
Vinyl Store/Win.Tienda/FormMenu.Designer.cs
11,585
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("OurSchedule.Android")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OurSchedule.Android")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // 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")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
36.714286
84
0.757198
[ "MIT" ]
michaelbowman1024/OurSchedule
OurSchedule/OurSchedule.Android/Properties/AssemblyInfo.cs
1,288
C#
using System; using System.Numerics; using Windows.UI; using Windows.UI.Composition; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Hosting; using Microsoft.Graphics.Canvas.Effects; namespace Ignite.Features.Views { public sealed partial class EffectsView { private CompositionEffectBrush brush; private Compositor compositor; public EffectsView() { InitializeComponent(); } private void SetupBlur() { compositor = ElementCompositionPreview.GetElementVisual(this).Compositor; var blur = new GaussianBlurEffect { Name = "Blur", Source = new CompositionEffectSourceParameter("Backdrop"), BlurAmount = 0.0f, BorderMode = EffectBorderMode.Hard }; var blend = new BlendEffect { Name = "Blend", Foreground = new ColorSourceEffect { Color = Color.FromArgb(128, 30, 30, 220), Name = "ColorSource" }, Background = blur, Mode = BlendEffectMode.Overlay }; var effectFactory = compositor.CreateEffectFactory(blend, new[] {"Blur.BlurAmount"}); brush = effectFactory.CreateBrush(); var backdrop = compositor.CreateBackdropBrush(); brush.SetSourceParameter("Backdrop", backdrop); var sprite = compositor.CreateSpriteVisual(); sprite.Brush = brush; sprite.Size = new Vector2((float) TargetImage.ActualWidth, (float) TargetImage.ActualHeight); ElementCompositionPreview.SetElementChildVisual(TargetImage, sprite); } private void OnBlurValueChanged(object sender, RangeBaseValueChangedEventArgs e) { brush?.Properties.InsertScalar("Blur.BlurAmount", (float) e.NewValue); } private void OnImageOpened(object sender, RoutedEventArgs e) { SetupBlur(); } } }
30.295775
105
0.582985
[ "MIT" ]
derekjwilliams/talks
ignite-2016/Ignite.Features/Views/EffectsView.xaml.cs
2,153
C#
using InTheHand.Net; using InTheHand.Net.Bluetooth; using InTheHand.Net.Sockets; using log4net; using System; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace More.Net.Channels.Bluetooth { /// <summary> /// /// </summary> public class BluetoothChannel// : IBluetoothChannel { #region Constructors /// <summary> /// /// </summary> static BluetoothChannel() { Logger = new BluetoothChannelLogger(); } /// <summary> /// /// </summary> /// <param name="address"></param> /// <param name="pin"></param> public BluetoothChannel(BluetoothAddress address) : this(new BluetoothDeviceInfo(address.ToInTheHandBluetoothAddress())) { } /// <summary> /// /// </summary> /// <param name="address"></param> /// <param name="pin"></param> internal BluetoothChannel(BluetoothDeviceInfo deviceInfo) { this.canRead = false; this.canWrite = false; this.deviceInfo = deviceInfo; this.endPoint = new BluetoothEndPoint( deviceInfo.DeviceAddress, BluetoothService.SerialPort); } #endregion #region IBluetoothChannel #region IChannel #region IDisposable ///// <summary> ///// ///// </summary> //void IDisposable.Dispose() //{ // DisconnectAsync().Wait(); //} #endregion /// <summary> /// /// </summary> public Boolean IsConnected { get { return client != null ? client.Connected : false; } } /// <summary> /// /// </summary> public Boolean CanRead { get { return canRead; } } /// <summary> /// /// </summary> public Boolean CanWrite { get { return canWrite; } } /// <summary> /// /// </summary> /// <returns></returns> public async Task<Boolean> ConnectAsync() { Boolean connected = false; try { Logger.OnConnectionBegin(deviceInfo); this.client = new BluetoothClient(); await client .ConnectAsync(endPoint) .ConfigureAwait(false); connected = client.Connected; if (connected) { this.networkStream = client.GetStream(); this.canRead = this.networkStream.CanRead; this.canWrite = this.networkStream.CanWrite; } else { this.client.Dispose(); } Logger.OnConnectionCompleted(deviceInfo); } catch (Exception ex) { Logger.OnConnectionCompleted(deviceInfo, ex); this.client.Dispose(); throw; } return connected; } /// <summary> /// /// </summary> /// <returns></returns> public async Task<Boolean> DisconnectAsync() { if (client.Connected) client.Close(); return await Task .FromResult(client.Connected == false) .ConfigureAwait(false); } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public async Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count) { Int32 bytesRead = 0; try { Logger.OnReadBegin(deviceInfo); if (this.canRead == false) throw new InvalidOperationException(); this.canRead = false; bytesRead = await networkStream .ReadAsync(buffer, offset, count) .ConfigureAwait(false); this.canRead = true; Logger.OnReadCompleted(deviceInfo, buffer, offset, bytesRead); } catch (Exception ex) { Logger.OnReadCompleted(deviceInfo, ex); throw; } return bytesRead; } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public async Task<Int32> WriteAsync(Byte[] buffer, Int32 offset, Int32 count) { if (this.canWrite == false) throw new InvalidOperationException(); this.canWrite = false; await networkStream .WriteAsync(buffer, offset, count) .ConfigureAwait(false); this.canWrite = true; return count; } #endregion /// <summary> /// /// </summary> public BluetoothAddress Address { get { return deviceInfo.DeviceAddress.ToBluetoothAddress(); } } /// <summary> /// /// </summary> public Boolean IsAuthenticated { get { return deviceInfo.Authenticated; } } /// <summary> /// /// </summary> public String Name { get { return deviceInfo.DeviceName; } } /// <summary> /// Asynchronously attempts to pair the local device with the remote device. /// </summary> /// <param name="pin"></param> /// <returns></returns> /// <remarks> /// This is not actually asynchronous - The pair request is created using Task.Run(). /// This is exposed as an asynchronous method, however, to keep symmetry with the other /// methods. /// </remarks> public async Task<Boolean> AuthenticateAsync(String pin) { deviceInfo.Refresh(); Logger.OnAuthenticationBegin(pin, deviceInfo); if (deviceInfo.Authenticated == false) await Task .Run(() => BluetoothSecurity.PairRequest(endPoint.Address, pin)) .ConfigureAwait(false); deviceInfo.Refresh(); Logger.OnAuthenticationCompleted(pin, deviceInfo); return deviceInfo.Authenticated; } /// <summary> /// /// </summary> /// <returns></returns> public Task<Double> GetRssiAsync() { throw new NotSupportedException(); } #endregion #region Overrides /// <summary> /// /// </summary> /// <returns></returns> public override String ToString() { return Address.ToString(); } #endregion #region Private Fields private Boolean canRead; private Boolean canWrite; private BluetoothClient client; private NetworkStream networkStream; private readonly BluetoothDeviceInfo deviceInfo; private readonly BluetoothEndPoint endPoint; private static readonly BluetoothChannelLogger Logger; #endregion } }
26.823944
96
0.487267
[ "MIT" ]
fallfromgrace/More.Net.Windows.Desktop
More.Net.Windows.Desktop/Channels/Bluetooth/BluetoothChannel.cs
7,620
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("05. Order students")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05. Order students")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("aee7f311-a430-463a-880c-b33e3c153e24")] // 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.081081
84
0.74308
[ "MIT" ]
todorm85/TelerikAcademy
Courses/Programming/Object-Orineted Programming/03.Extensions,Lambda,LINQ/05. Order students/Properties/AssemblyInfo.cs
1,412
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using MlHostSdk.Repository; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Toolbox.Models; using Toolbox.Repository; using Toolbox.Services; using Toolbox.Tools; namespace MlHostCli.Test.Application { public class ModelFixture { internal const string _resourceId = "MlHostCli.Test.TestConfig.TestConfig.json"; private static ModelFixture? _current; private static object _lock = new object(); private const string _secretId = "MlHostCli.Test"; private ModelFixture(IModelStore modelRepository) { ModelRepository = modelRepository; } public IModelStore ModelRepository { get; } public async Task<IReadOnlyList<DatalakePathItem>> ListFiles() => await ModelRepository.Search(null, "*", CancellationToken.None); /// <summary> /// Global singleton constructor required because MS Test does not support test fixtures /// </summary> public static ModelFixture GetModelFixture() { lock (_lock) { if (_current != null) return _current; using Stream configStream = typeof(ModelFixture).GetResourceStream(_resourceId); IConfiguration config = new ConfigurationBuilder() .AddJsonStream(configStream) .AddUserSecrets(_secretId) .AddEnvironmentVariables("mlhostcli") .Build(); var blobStoreOption = new StoreOption(); config.Bind(blobStoreOption, x => x.BindNonPublicProperties = true); blobStoreOption.Verify(); return _current = new ModelFixture(new DatalakeModelStore(new DatalakeStore(blobStoreOption, new NullLogger<DatalakeStore>()))); } } } }
33.491803
144
0.656877
[ "MIT" ]
khooversoft/MlHost
Src/MlHostServer/MlHostCli.Test/Application/ModelFixture.cs
2,045
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime:4.0.30319.42000 // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("Listas1.MainPage.xaml", "MainPage.xaml", typeof(global::Listas1.MainPage))] namespace Listas1 { [global::Xamarin.Forms.Xaml.XamlFilePathAttribute("MainPage.xaml")] public partial class MainPage : global::Xamarin.Forms.ContentPage { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "2.0.0.0")] private void InitializeComponent() { global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(MainPage)); } } }
40.84
138
0.587659
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
srdelsalto/XamarinProject
Xamarin Curse/Listas1/Listas1/Listas1/obj/Debug/netstandard2.0/MainPage.xaml.g.cs
1,026
C#
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.iMote2 { using System; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class Storage : RT.Storage { const uint DRAMSize = 2 * 8 * 1024 * 1024; const uint DRAMBase = 0xA0000000 + DRAMSize; const uint DRAMEnd = DRAMBase + DRAMSize; const uint DRAMMask = ~(DRAMSize - 1); const byte ErasedValueByte = (byte)0xFFu; const ushort ErasedValue = (ushort)0xFFFFu; const uint ErasedValuePair = 0xFFFFFFFFu; // // State // // // Helper Methods // public override unsafe void InitializeStorage() { } //--// public override unsafe bool EraseSectors( UIntPtr addressStart , UIntPtr addressEnd ) { if(ValidateAddress ( addressStart ) && ValidateAddressPlus1( addressEnd ) ) { RT.Memory.Fill( addressStart, addressEnd, ErasedValueByte ); return true; } return false; } public override unsafe bool WriteByte( UIntPtr address , byte val ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); *ptr = val; return true; } return false; } public override unsafe bool WriteShort( UIntPtr address , ushort val ) { if(IsOddAddress( address )) { return WriteByte( address, (byte) val ) && WriteByte( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (byte)(val >> 8) ) ; } else { if(ValidateAddress( address )) { ushort* wordAddress = (ushort*)address.ToPointer(); *wordAddress = val; return true; } return false; } } public override bool WriteWord( UIntPtr address , uint val ) { if(IsOddAddress( address )) { return WriteByte ( address, (byte ) val ) && WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (ushort)(val >> 8) ) && WriteByte ( Microsoft.Zelig.AddressMath.Increment( address, 3 ), (byte )(val >> 24) ) ; } else { return WriteShort( address, (ushort) val ) && WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 2 ), (ushort)(val >> 16) ) ; } } public override bool Write( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { if(numBytes > 0) { if(IsOddAddress( address )) { if(WriteByte( address, buffer[offset] ) == false) { return false; } address = Microsoft.Zelig.AddressMath.Increment( address, 1 ); offset += 1; numBytes -= 1; } while(numBytes >= 2) { uint val; val = (uint)buffer[ offset++ ]; val |= (uint)buffer[ offset++ ] << 8; if(WriteShort( address, (ushort)val ) == false) { return false; } address = Microsoft.Zelig.AddressMath.Increment( address, 2 ); numBytes -= 2; } if(numBytes != 0) { if(WriteByte( address, buffer[offset] ) == false) { return false; } } } return true; } //--// public override unsafe byte ReadByte( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return ptr[0]; } return ErasedValueByte; } public override unsafe ushort ReadShort( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return (ushort)((uint)ptr[0] | (uint)ptr[1] << 8 ); } return ErasedValue; } public override unsafe uint ReadWord( UIntPtr address ) { if(ValidateAddress( address )) { byte* ptr = (byte*)address.ToPointer(); return ((uint)ptr[0] | (uint)ptr[1] << 8 | (uint)ptr[2] << 16 | (uint)ptr[3] << 24 ); } return ErasedValuePair; } public override void Read( UIntPtr address , byte[] buffer , uint offset , uint numBytes ) { while(numBytes != 0) { buffer[offset++] = ReadByte( address ); address = Microsoft.Zelig.AddressMath.Increment( address, 1 ); numBytes--; } } public override void SubstituteFirmware( UIntPtr addressDestination , UIntPtr addressSource , uint numBytes ) { throw new NotImplementedException(); } public override void RebootDevice() { throw new System.NotImplementedException(); } //--// [RT.Inline] static bool ValidateAddress( UIntPtr address ) { if(Zelig.AddressMath.IsLessThan( address, new UIntPtr( DRAMBase ) )) { return false; } if(Zelig.AddressMath.IsGreaterThanOrEqual( address, new UIntPtr( DRAMEnd ) )) { return false; } return true; } [RT.Inline] static bool ValidateAddressPlus1( UIntPtr address ) { if(Zelig.AddressMath.IsLessThanOrEqual( address, new UIntPtr( DRAMBase ) )) { return false; } if(Zelig.AddressMath.IsGreaterThan( address, new UIntPtr( DRAMEnd ) )) { return false; } return true; } [RT.Inline] static bool IsOddAddress( UIntPtr address ) { return Zelig.AddressMath.IsAlignedTo16bits( address ) == false; } } }
30.10687
113
0.393509
[ "MIT" ]
NETMF/llilum
Zelig/Zelig/RunTime/DeviceModels/iMote2/HardwareModel/Storage.cs
7,888
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IApprovalStageRequestBuilder. /// </summary> public partial interface IApprovalStageRequestBuilder : IEntityRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> new IApprovalStageRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> new IApprovalStageRequest Request(IEnumerable<Option> options); } }
34.138889
153
0.566314
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IApprovalStageRequestBuilder.cs
1,229
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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 Castle.Facilities.WcfIntegration { using System.ServiceModel; using Castle.MicroKernel; public interface IWcfChannelExtension : IWcfExtension { void Install(ChannelFactory channelFactory, IKernel kernel, IWcfBurden burden); } }
36.08
82
0.741685
[ "Apache-2.0" ]
castleproject-deprecated/Castle.Facilities.Wcf-READONLY
src/Castle.Facilities.WcfIntegration/IWcfChannelExtension.cs
902
C#
using DataWF.Data; using DataWF.Module.Counterpart; using System.ComponentModel; using System.Runtime.Serialization; namespace DataWF.Module.Flow { [Table("ddocument_customer", "Document", BlockSize = 400)] public class DocumentCustomer : DBItem, IDocumentDetail { public static readonly DBTable<DocumentCustomer> DBTable = GetTable<DocumentCustomer>(); public static readonly DBColumn CustomerKey = DBTable.ParseProperty(nameof(CustomerId)); public static readonly DBColumn AddressKey = DBTable.ParseProperty(nameof(AddressId)); public static readonly DBColumn EMailKey = DBTable.ParseProperty(nameof(EMail)); public static readonly DBColumn PhoneKey = DBTable.ParseProperty(nameof(Phone)); public static readonly DBColumn DocumentKey = DBTable.ParseProperty(nameof(DocumentId)); private Customer customer; private Address address; private Document document; public DocumentCustomer() { } [Browsable(false)] [Column("document_id"), Index("ddocument_customer_document_id")] public virtual long? DocumentId { get => GetValue<long?>(DocumentKey); set => SetValue(value, DocumentKey); } [Reference(nameof(DocumentId))] public Document Document { get => GetReference(DocumentKey, ref document); set => SetReference(document = value, DocumentKey); } [Column("unid", Keys = DBColumnKeys.Primary)] public long? Id { get => GetValue<long?>(Table.PrimaryKey); set => SetValue(value, Table.PrimaryKey); } [Browsable(false)] [Column("customer_id", Keys = DBColumnKeys.View)] public int? CustomerId { get => GetValue<int?>(CustomerKey); set => SetValue(value, CustomerKey); } [Reference(nameof(CustomerId))] public Customer Customer { get => GetReference(CustomerKey, ref customer); set { SetReference(customer = value, CustomerKey); Address = value?.Address; EMail = value?.EMail; Phone = value?.Phone; } } [Browsable(false)] [Column("address_id")] public int? AddressId { get => GetValue<int?>(AddressKey); set => SetValue(value, AddressKey); } [Reference(nameof(AddressId))] public Address Address { get => GetReference(AddressKey, ref address); set => SetReference(address = value, AddressKey); } [Column("email", 1024)] public string EMail { get => GetValue<string>(EMailKey); set => SetValue(value, EMailKey); } [Column("phone", 1024)] public string Phone { get => GetValue<string>(PhoneKey); set => SetValue(value, PhoneKey); } protected override void RaisePropertyChanged(string property) { base.RaisePropertyChanged(property); if (Attached) { document?.OnReferenceChanged(this); } } } }
30.348624
96
0.576481
[ "MIT" ]
alexandrvslv/datawf
DataWF.Module.Flow/Document/DocumentCustomer.cs
3,310
C#
namespace AzurePipelineRunner.BuildDefinitions { public interface IBuildDefinitionReader { Build GetBuild(string buildYamlPath); } }
20.125
48
0.701863
[ "Apache-2.0" ]
fredrikn/AzurePipelineRunner
AzurePipelineRunner/BuildDefinitions/IBuildDefinitionReader.cs
163
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TenancyContract.Entities { public class Thana { [Key] public int ThanaId { get; set; } public string ThanaName { get; set; } public int DistrictId { get; set; } } }
26.25
51
0.669841
[ "MPL-2.0" ]
4L4M1N/Tenancy_Contract
src/Web/Entities/Thana.cs
315
C#
using MinecraftMappings.Internal.Textures.Block; using MinecraftMappings.Minecraft.Bedrock.Textures.Block; namespace MinecraftMappings.Minecraft.Java.Textures.Block { public class OakLog : JavaBlockTexture { public OakLog() : base("Oak Log") { AddVersion("oak_log") .WithDefaultModel<Java.Models.Block.OakLog>() .MapsToBedrockBlock<LogOak>(); } } }
26.9375
61
0.647332
[ "MIT" ]
null511/MinecraftMappings.NET
MinecraftMappings.NET/Minecraft/Java/Textures/Block/OakLog.cs
433
C#
using RequirementsLab.Core.Abstractions; using RequirementsLab.Core.DTO.PoorWords; using RequirementsLab.DAL; using System; using System.Collections.Generic; using System.Text; using System.Linq; using Microsoft.EntityFrameworkCore; using RequirementsLab.Core.Entities; namespace RequirementsLab.Services { public class PoorWordsService : IPoorWordsService { private readonly RequirementsLabContext context; public PoorWordsService(RequirementsLabContext context) { this.context = context; } public PoorWordsResultDTO CheckPoorWords(PoorWordsRequestDTO poorWords) { var taskId = poorWords.taskId; var pwArray = poorWords.poorWords; var requirementIDs = context.RequirementsForPWTask .Where(req => req.TaskId == taskId) .Select(req => req.Id) .ToList(); var poorWordsFromDB = context.PoorWords .Where(pw => requirementIDs.Contains(pw.RequirementId)) .Select(pw => new PoorWordDTO { Text = pw.Text, }) .Distinct() .ToList(); var poorWordsMatched = context.PoorWords .Where(pw => requirementIDs.Contains(pw.RequirementId)) .Where(pw => pwArray.Contains(pw.Text)) .Select(pw => new PoorWordDTO { Text = pw.Text, }) .Distinct() .ToList(); int grade = (int)(((float)poorWordsMatched.Count / poorWordsFromDB.Count) * 100); int notMatchedCount = pwArray.Count - poorWordsMatched.Count; if(pwArray.Count!=0) { grade -= grade / pwArray.Count * notMatchedCount; } else { grade = 0; } string resultTitle; if (grade < 33) { resultTitle = "Незадовільний результат"; } else if(grade >= 33 && grade < 80) { resultTitle = "Добрий результат"; } else { resultTitle = "Відмінний результат"; } return new PoorWordsResultDTO { Grade = grade, NotMatched = notMatchedCount, Title = resultTitle, }; } public RequirementsForPWTaskDTO GetRequirements(int taskId) { var tasks = context.RequirementsForPWTask .Where(requirement => requirement.TaskId == taskId) .Select(requirement => new RequirementForPWTaskDTO { Id = requirement.Id, Title = requirement.Title, }) .ToList(); return new RequirementsForPWTaskDTO { Requirements = tasks }; } } }
29.68932
93
0.508502
[ "MIT" ]
LTania/Tanstep
RequirementsLab.Services/PoorWordsService.cs
3,115
C#
// Copyright (c) 2020 Ubisoft Entertainment // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Sharpmake; namespace Common { public class Common { public static string GetDevEnvString(DevEnv env) { switch (env) { case DevEnv.vs2015: return "2015"; case DevEnv.vs2017: return "2017"; default: return ""; } } public static Target[] GetDefaultTargets() { return new Target[]{ new Target( Platform.anycpu, DevEnv.vs2015, Optimization.Debug | Optimization.Release, OutputType.Dll, Blob.NoBlob, BuildSystem.MSBuild, DotNetFramework.v4_5), new Target( Platform.anycpu, DevEnv.vs2017, Optimization.Debug | Optimization.Release, OutputType.Dll, Blob.NoBlob, BuildSystem.MSBuild, DotNetFramework.v4_6_1) }; } } [Sharpmake.Generate] public class ProjectTemplate : CSharpProject { public ProjectTemplate() { RootPath = @"[project.SharpmakeCsPath]\codebase\"; // This Path will be used to get all SourceFiles in this Folder and all subFolders SourceRootPath = @"[project.RootPath]\[project.Name]"; AddTargets(Common.GetDefaultTargets()); // if set to true, dependencies that the project uses will be copied to the output directory DependenciesCopyLocal = DependenciesCopyLocalTypes.Default; // Set to null if you don't want to use Perforce PerforceRootPath = null; // Files put in this directory will be added to the project as resources (linked) build Action ResourcesPath = RootPath + @"\Resources\"; // Files put in this directory will be added to the project as Content build Action ContentPath = RootPath + @"\Content\"; //Specify if we want the project file to be LowerCase IsFileNameToLower = false; } [Configure()] public virtual void ConfigureAll(Configuration conf, Target target) { //-----------------OutputPath----------------------// // Path where the binaries will be stored conf.TargetPath = @"[conf.ProjectPath]\[project.OutputPathName]\[target.DevEnv]\[target.Framework]\[target.Platform]\[conf.Name]"; // Visual Studio Default: //conf.TargetPath = string.Format(@"[conf.ProjectPath]\{0}", OutputPathName); // Choose between WindowsApplication ConsoleApplication or ClassLibraries conf.Output = Project.Configuration.OutputType.DotNetConsoleApp; // Sets the ProjectFileName for project where ProjectFileName isn't modified by configurations // Visual Studio Default: // public static string DefaultProjectFileName = "[project.Name]"; conf.ProjectFileName = "[project.Name].[target.DevEnv].[target.Framework]"; conf.ReferencesByName.AddRange(new Strings("System", "System.Core", "System.Xml.Linq", "System.Data.DataSetExtensions", "System.Data", "System.Xml")); // Sets where the project file (csproj) will be saved conf.ProjectPath = @"[project.RootPath]\[project.Name]"; //----------------IntermediatePath-----------------// // Usually the obj folder created to link files // Note: Due to a Visual Studio known Bug // The obj folder might still be created, but should be empty at the end of the build, if removed the rebuild project function won't work conf.IntermediatePath = @"[project.SharpmakeCsPath]\..\[project.IntermediatePathName]\[project.Name]\[target.DevEnv]\[target.Framework]\[target.Platform]"; // Visual Studio Default: //public static string IntermediatePath = string.Format(@"[conf.ProjectPath]\{0}", IntermediatePathName); } } [Sharpmake.Generate] public class SolutionTemplate : CSharpSolution { public SolutionTemplate() { AddTargets(Common.GetDefaultTargets()); } [Configure()] public virtual void ConfigureAll(Configuration conf, Target target) { conf.SolutionFileName = string.Format("{0}.{1}.{2}", Name, Common.GetDevEnvString(target.DevEnv), target.Framework.ToVersionString()); conf.SolutionPath = @"[solution.SharpmakeCsPath]\codebase\"; } } }
39.232877
167
0.552898
[ "Apache-2.0" ]
Cheaterdev/Sharpmake
samples/CSharpImports/common.sharpmake.cs
5,728
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : Combatant { private Rigidbody2D myBody; private Animator animator; private NpcGroundDetection groundCheck; void Start() { myBody = GetComponent<Rigidbody2D>(); animator = GetComponent<Animator>(); groundCheck = gameObject.GetComponentInChildren<NpcGroundDetection>(); } private void Update() { HandleGenericAnimation(animator); } protected override void HandleGenericAnimation(Animator animator) { base.HandleGenericAnimation(animator); // If grounded and not in hitstun, leave disabled state. { if (state.currentMovementState == CharacterState.MovementState.Disabled && state.currentCombatState == CharacterState.CombatState.Neutral && groundCheck.grounded) animator.SetBool("Disabled", false); } } }
27.583333
86
0.664653
[ "CC0-1.0" ]
SoloMorris/Combo-System-CGS
ComboSystemSolo/Assets/Scripts/Enemy.cs
995
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace Microsoft.AspNetCore.JsonPatch.Internal; /// <summary> /// This API supports infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class PocoAdapter : IAdapter { public virtual bool TryAdd( object target, string segment, IContractResolver contractResolver, object value, out string errorMessage) { if (!TryGetJsonProperty(target, contractResolver, segment, out var jsonProperty)) { errorMessage = Resources.FormatTargetLocationAtPathSegmentNotFound(segment); return false; } if (!jsonProperty.Writable) { errorMessage = Resources.FormatCannotUpdateProperty(segment); return false; } if (!TryConvertValue(value, jsonProperty.PropertyType, out var convertedValue)) { errorMessage = Resources.FormatInvalidValueForProperty(value); return false; } jsonProperty.ValueProvider.SetValue(target, convertedValue); errorMessage = null; return true; } public virtual bool TryGet( object target, string segment, IContractResolver contractResolver, out object value, out string errorMessage) { if (!TryGetJsonProperty(target, contractResolver, segment, out var jsonProperty)) { errorMessage = Resources.FormatTargetLocationAtPathSegmentNotFound(segment); value = null; return false; } if (!jsonProperty.Readable) { errorMessage = Resources.FormatCannotReadProperty(segment); value = null; return false; } value = jsonProperty.ValueProvider.GetValue(target); errorMessage = null; return true; } public virtual bool TryRemove( object target, string segment, IContractResolver contractResolver, out string errorMessage) { if (!TryGetJsonProperty(target, contractResolver, segment, out var jsonProperty)) { errorMessage = Resources.FormatTargetLocationAtPathSegmentNotFound(segment); return false; } if (!jsonProperty.Writable) { errorMessage = Resources.FormatCannotUpdateProperty(segment); return false; } // Setting the value to "null" will use the default value in case of value types, and // null in case of reference types object value = null; if (jsonProperty.PropertyType.IsValueType && Nullable.GetUnderlyingType(jsonProperty.PropertyType) == null) { value = Activator.CreateInstance(jsonProperty.PropertyType); } jsonProperty.ValueProvider.SetValue(target, value); errorMessage = null; return true; } public virtual bool TryReplace( object target, string segment, IContractResolver contractResolver, object value, out string errorMessage) { if (!TryGetJsonProperty(target, contractResolver, segment, out var jsonProperty)) { errorMessage = Resources.FormatTargetLocationAtPathSegmentNotFound(segment); return false; } if (!jsonProperty.Writable) { errorMessage = Resources.FormatCannotUpdateProperty(segment); return false; } if (!TryConvertValue(value, jsonProperty.PropertyType, out var convertedValue)) { errorMessage = Resources.FormatInvalidValueForProperty(value); return false; } jsonProperty.ValueProvider.SetValue(target, convertedValue); errorMessage = null; return true; } public virtual bool TryTest( object target, string segment, IContractResolver contractResolver, object value, out string errorMessage) { if (!TryGetJsonProperty(target, contractResolver, segment, out var jsonProperty)) { errorMessage = Resources.FormatTargetLocationAtPathSegmentNotFound(segment); return false; } if (!jsonProperty.Readable) { errorMessage = Resources.FormatCannotReadProperty(segment); return false; } if (!TryConvertValue(value, jsonProperty.PropertyType, out var convertedValue)) { errorMessage = Resources.FormatInvalidValueForProperty(value); return false; } var currentValue = jsonProperty.ValueProvider.GetValue(target); if (!JToken.DeepEquals(JsonConvert.SerializeObject(currentValue), JsonConvert.SerializeObject(convertedValue))) { errorMessage = Resources.FormatValueNotEqualToTestValue(currentValue, value, segment); return false; } errorMessage = null; return true; } public virtual bool TryTraverse( object target, string segment, IContractResolver contractResolver, out object value, out string errorMessage) { if (target == null) { value = null; errorMessage = null; return false; } if (TryGetJsonProperty(target, contractResolver, segment, out var jsonProperty)) { value = jsonProperty.ValueProvider.GetValue(target); errorMessage = null; return true; } value = null; errorMessage = Resources.FormatTargetLocationAtPathSegmentNotFound(segment); return false; } protected virtual bool TryGetJsonProperty( object target, IContractResolver contractResolver, string segment, out JsonProperty jsonProperty) { if (contractResolver.ResolveContract(target.GetType()) is JsonObjectContract jsonObjectContract) { var pocoProperty = jsonObjectContract .Properties .FirstOrDefault(p => string.Equals(p.PropertyName, segment, StringComparison.OrdinalIgnoreCase)); if (pocoProperty != null) { jsonProperty = pocoProperty; return true; } } jsonProperty = null; return false; } protected virtual bool TryConvertValue(object value, Type propertyType, out object convertedValue) { var conversionResult = ConversionResultProvider.ConvertTo(value, propertyType); if (!conversionResult.CanBeConverted) { convertedValue = null; return false; } convertedValue = conversionResult.ConvertedInstance; return true; } }
29.845188
119
0.622179
[ "MIT" ]
3ejki/aspnetcore
src/Features/JsonPatch/src/Internal/PocoAdapter.cs
7,133
C#
using System; using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory; using Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Codecs.Lucene3x { /* * 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 FieldInfos = Lucene.Net.Index.FieldInfos; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IOContext = Lucene.Net.Store.IOContext; using SegmentInfo = Lucene.Net.Index.SegmentInfo; /// <summary> /// Lucene3x ReadOnly <see cref="TermVectorsFormat"/> implementation /// <para/> /// @lucene.experimental /// </summary> [Obsolete("(4.0) this is only used to read indexes created before 4.0.")] internal class Lucene3xTermVectorsFormat : TermVectorsFormat { public override TermVectorsReader VectorsReader(Directory directory, SegmentInfo segmentInfo, FieldInfos fieldInfos, IOContext context) { string fileName = IndexFileNames.SegmentFileName(Lucene3xSegmentInfoFormat.GetDocStoreSegment(segmentInfo), "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION); // Unfortunately, for 3.x indices, each segment's // FieldInfos can lie about hasVectors (claim it's true // when really it's false).... so we have to carefully // check if the files really exist before trying to open // them (4.x has fixed this): bool exists; if (Lucene3xSegmentInfoFormat.GetDocStoreOffset(segmentInfo) != -1 && Lucene3xSegmentInfoFormat.GetDocStoreIsCompoundFile(segmentInfo)) { string cfxFileName = IndexFileNames.SegmentFileName(Lucene3xSegmentInfoFormat.GetDocStoreSegment(segmentInfo), "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION); if (segmentInfo.Dir.FileExists(cfxFileName)) { Directory cfsDir = new CompoundFileDirectory(segmentInfo.Dir, cfxFileName, context, false); try { exists = cfsDir.FileExists(fileName); } finally { cfsDir.Dispose(); } } else { exists = false; } } else { exists = directory.FileExists(fileName); } if (!exists) { // 3x's FieldInfos sometimes lies and claims a segment // has vectors when it doesn't: return null; } else { return new Lucene3xTermVectorsReader(directory, segmentInfo, fieldInfos, context); } } public override TermVectorsWriter VectorsWriter(Directory directory, SegmentInfo segmentInfo, IOContext context) { throw UnsupportedOperationException.Create("this codec can only be used for reading"); } } }
43.022472
176
0.619222
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net/Codecs/Lucene3x/Lucene3xTermVectorsFormat.cs
3,829
C#
namespace Passwords { using System; public class Program { private static int n; private static char[] relations; private static int k; private static int[] objects; private static int counter; private static bool zeroTaken; public static void Main() { n = int.Parse(Console.ReadLine()); relations = Console.ReadLine().ToCharArray(); k = int.Parse(Console.ReadLine()); objects = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; int[] array = new int[n]; GenerateVariations(array, 0); counter = 0; } private static void GenerateVariations(int[] array, int prevIndex, int index = 0, int relIndex = -1) { if (index >= array.Length) { counter++; if (counter == k) { Console.WriteLine(string.Join(string.Empty, array)); Environment.Exit(0); } } else { if (relIndex == -1) { if (!zeroTaken) { array[index] = 0; zeroTaken = true; GenerateVariations(array, 9, index + 1, relIndex + 1); zeroTaken = false; } for (int i = 0; i < objects.Length - 1; i++) { array[index] = objects[i]; GenerateVariations(array, i, index + 1, relIndex + 1); } } else { if (relations[relIndex] == '>') { if (array[index - 1] != 0) { array[index] = 0; GenerateVariations(array, 9, index + 1, relIndex + 1); } for (int i = prevIndex + 1; i < objects.Length - 1; i++) { array[index] = objects[i]; GenerateVariations(array, i, index + 1, relIndex + 1); } } else if (relations[relIndex] == '<') { for (int i = 0; i < prevIndex; i++) { array[index] = objects[i]; GenerateVariations(array, i, index + 1, relIndex + 1); } } else { array[index] = array[index - 1]; GenerateVariations(array, prevIndex, index + 1, relIndex + 1); } } } } } }
29.858586
108
0.356225
[ "MIT" ]
iliangogov/Data-Structures-and-Algorithms
Workshop2016/WorkshopDsa/Passwords/Program.cs
2,958
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using NerdBotCommon.Messengers; using NerdBotCommon.Parsers; using Serilog; namespace NerdBotCommon.Plugin { public abstract class PluginBase : IPlugin { protected IBotServices _services; protected ILogger _logger; public PluginBase(IBotServices services) { if (services == null) throw new ArgumentNullException("services"); this._services = services; } #region Properties public IBotServices Services { set { if (value == null) throw new ArgumentNullException("value"); this._services = value; } get { return this._services; } } public ILogger Logger { get { return this._logger; } set { this._logger = value; } } public abstract string Name { get; } public abstract string Description { get; } public abstract string ShortDescription { get; } public abstract string Command { get; } public abstract string HelpCommand { get; } public abstract string HelpDescription { get; } #endregion public abstract void OnLoad(); public abstract void OnUnload(); public abstract Task<bool> OnCommand(Command command, IMessage message, IMessenger messenger); } }
27.473684
103
0.573436
[ "MIT" ]
jpann/nerdbot-core
NerdBotCore/NerdBotCommon/Plugin/PluginBase.cs
1,512
C#
namespace AppInsightsBot { using System.Collections.Generic; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.Bot.Builder.Dialogs; using Newtonsoft.Json; public static class TelemetryExtensions { public static TraceTelemetry CreateTraceTelemetry(this IDialogContext ctx, string message = null, IDictionary<string, string> properties = null) { var t = new TraceTelemetry(message); t.Properties.Add("ConversationData", JsonConvert.SerializeObject(ctx.ConversationData)); t.Properties.Add("PrivateConversationData", JsonConvert.SerializeObject(ctx.PrivateConversationData)); t.Properties.Add("UserData", JsonConvert.SerializeObject(ctx.UserData)); var m = ctx.MakeMessage(); t.Properties.Add("ConversationId", m.Conversation.Id); t.Properties.Add("UserId", m.Recipient.Id); if (properties != null) { foreach (var p in properties) { t.Properties.Add(p); } } return t; } public static EventTelemetry CreateEventTelemetry(this IDialogContext ctx, string message = null, IDictionary<string, string> properties = null) { var t = new EventTelemetry(message); t.Properties.Add("ConversationData", JsonConvert.SerializeObject(ctx.ConversationData)); t.Properties.Add("PrivateConversationData", JsonConvert.SerializeObject(ctx.PrivateConversationData)); t.Properties.Add("UserData", JsonConvert.SerializeObject(ctx.UserData)); var m = ctx.MakeMessage(); t.Properties.Add("ConversationId", m.Conversation.Id); t.Properties.Add("UserId", m.Recipient.Id); if (properties != null) { foreach (var p in properties) { t.Properties.Add(p); } } return t; } public static ExceptionTelemetry CreateExceptionTelemetry(this IDialogContext ctx, System.Exception ex, IDictionary<string, string> properties = null) { var t = new ExceptionTelemetry(ex); t.Properties.Add("ConversationData", JsonConvert.SerializeObject(ctx.ConversationData)); t.Properties.Add("PrivateConversationData", JsonConvert.SerializeObject(ctx.PrivateConversationData)); t.Properties.Add("UserData", JsonConvert.SerializeObject(ctx.UserData)); var m = ctx.MakeMessage(); t.Properties.Add("ConversationId", m.Conversation.Id); t.Properties.Add("UserId", m.Recipient.Id); if (properties != null) { foreach (var p in properties) { t.Properties.Add(p); } } return t; } } }
38.75
158
0.600679
[ "MIT" ]
ArtemKiyashko/telebotexample
CSharp/core-AppInsights/TelemetryExtensions.cs
2,947
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Xenko.Core; namespace Xenko.Assets.SpriteFont { /// <summary> /// Describes a range of consecutive characters that should be included in the font. /// </summary> [DataContract("CharacterRegion")] public class CharacterRegion { /// <summary> /// Initializes a new instance of the <see cref="CharacterRegion"/> class. /// </summary> /// <param name="start">The start.</param> /// <param name="end">The end.</param> /// <exception cref="System.ArgumentException"></exception> public CharacterRegion(char start, char end) : this() { if (start > end) throw new ArgumentException(); Start = start; End = end; } /// <summary> /// Initializes a new instance of the <see cref="CharacterRegion"/> class. /// </summary> public CharacterRegion() { } /// <summary> /// The first character to include in the region. /// </summary> /// <userdoc> /// The first character of the region. /// </userdoc> [DataMember(0)] public char Start; /// <summary> /// The second character to include in the region. /// </summary> /// <userdoc> /// The last character of the region. /// </userdoc> [DataMember(1)] public char End; // Flattens a list of character regions into a combined list of individual characters. public static IEnumerable<char> Flatten(List<CharacterRegion> regions) { if (regions.Any()) { // If we have any regions, flatten them and remove duplicates. return regions.SelectMany(region => region.GetCharacters()).Distinct(); } // If no regions were specified, use the default. return Default.GetCharacters(); } // Default to just the base ASCII character set. public static CharacterRegion Default = new CharacterRegion(' ', '~'); // Enumerates all characters within the region. private IEnumerable<char> GetCharacters() { for (char c = Start; c <= End; c++) { yield return c; } } } }
31.452381
114
0.561317
[ "MIT" ]
Aminator/xenko
sources/engine/Xenko.Assets/SpriteFont/CharacterRegion.cs
2,642
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace JustFood.Models { using System; using System.Collections.Generic; public partial class AccountBalance { public long AccountBalanceID { get; set; } public System.DateTime Dated { get; set; } public double Amount { get; set; } public bool IsBoughtProduct { get; set; } public Nullable<int> AddedQuantity { get; set; } public bool IsExpense { get; set; } public bool IsAddedMoney { get; set; } public Nullable<int> AccountOf { get; set; } public int AddBy { get; set; } public string Note { get; set; } public bool IsVerified { get; set; } public bool IsDailyExpense { get; set; } public bool IsRevenueOfDailySales { get; set; } public long InventoryID { get; set; } public virtual Inventory Inventory { get; set; } public virtual User User { get; set; } public virtual User User1 { get; set; } } }
37.648649
84
0.556353
[ "MIT" ]
aukgit/StoreManament
JustFood/Models/Garbage/AccountBalance.cs
1,393
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; namespace Microsoft.EntityFrameworkCore.Metadata { public class NavigationExtensionsTest { [Fact] public void Can_get_one_to_many_inverses() { var model = BuildModel(); var category = model.FindEntityType(typeof(Product)).GetNavigations().Single(e => e.Name == "Category"); var products = model.FindEntityType(typeof(Category)).GetNavigations().Single(e => e.Name == "Products"); Assert.Same(category, products.FindInverse()); Assert.Same(products, category.FindInverse()); } [Fact] public void Can_get_one_to_one_inverses() { var model = BuildModel(); var category = model.FindEntityType(typeof(Product)).GetNavigations().Single(e => e.Name == "FeaturedProductCategory"); var product = model.FindEntityType(typeof(Category)).GetNavigations().Single(e => e.Name == "FeaturedProduct"); Assert.Same(category, product.FindInverse()); Assert.Same(product, category.FindInverse()); } [Fact] public void Can_get_target_ends() { var model = BuildModel(); var productType = model.FindEntityType(typeof(Product)); var categoryType = model.FindEntityType(typeof(Category)); var category = productType.GetNavigations().Single(e => e.Name == "Category"); var products = categoryType.GetNavigations().Single(e => e.Name == "Products"); Assert.Same(productType, products.GetTargetType()); Assert.Same(categoryType, category.GetTargetType()); } [Fact] public void Returns_null_when_no_inverse() { var products = BuildModel(createCategory: false).FindEntityType(typeof(Category)).GetNavigations() .Single(e => e.Name == "Products"); Assert.Null(products.FindInverse()); var category = BuildModel(createProducts: false).FindEntityType(typeof(Product)).GetNavigations() .Single(e => e.Name == "Category"); Assert.Null(category.FindInverse()); var featuredCategory = BuildModel(createFeaturedProduct: false).FindEntityType(typeof(Product)).GetNavigations() .Single(e => e.Name == "FeaturedProductCategory"); Assert.Null(featuredCategory.FindInverse()); var featuredProduct = BuildModel(createFeaturedProductCategory: false).FindEntityType(typeof(Category)).GetNavigations() .Single(e => e.Name == "FeaturedProduct"); Assert.Null(featuredProduct.FindInverse()); } private class Category { public static readonly PropertyInfo ProductsProperty = typeof(Category).GetProperty(nameof(Products)); public static readonly PropertyInfo FeaturedProductProperty = typeof(Category).GetProperty(nameof(FeaturedProduct)); public int Id { get; set; } public int FeaturedProductId { get; set; } public Product FeaturedProduct { get; set; } public ICollection<Product> Products { get; set; } } private class Product { public static readonly PropertyInfo CategoryProperty = typeof(Product).GetProperty(nameof(Category)); public static readonly PropertyInfo FeaturedProductCategoryProperty = typeof(Product).GetProperty(nameof(FeaturedProductCategory)); public int Id { get; set; } public Category FeaturedProductCategory { get; set; } public int CategoryId { get; set; } public Category Category { get; set; } } private static IModel BuildModel( bool createProducts = true, bool createCategory = true, bool createFeaturedProductCategory = true, bool createFeaturedProduct = true) { var builder = InMemoryTestHelpers.Instance.CreateConventionBuilder(); var model = builder.Model; builder.Entity<Product>( e => { e.Ignore(p => p.Category); e.Ignore(p => p.FeaturedProductCategory); }); builder.Entity<Category>( e => { e.Ignore(c => c.Products); e.Ignore(c => c.FeaturedProduct); }); var categoryType = model.FindEntityType(typeof(Category)); var productType = model.FindEntityType(typeof(Product)); var categoryFk = productType.AddForeignKey( productType.FindProperty("CategoryId"), categoryType.FindPrimaryKey(), categoryType); var featuredProductFk = categoryType.AddForeignKey( categoryType.FindProperty("FeaturedProductId"), productType.FindPrimaryKey(), productType); featuredProductFk.IsUnique = true; if (createProducts) { categoryFk.HasPrincipalToDependent(Category.ProductsProperty); } if (createCategory) { categoryFk.HasDependentToPrincipal(Product.CategoryProperty); } if (createFeaturedProductCategory) { featuredProductFk.HasPrincipalToDependent(Product.FeaturedProductCategoryProperty); } if (createFeaturedProduct) { featuredProductFk.HasDependentToPrincipal(Category.FeaturedProductProperty); } return model; } } }
37.56962
132
0.612028
[ "Apache-2.0" ]
BionStt/EntityFrameworkCore
test/EFCore.Tests/Metadata/NavigationExtensionsTest.cs
5,936
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; using Aop.Api.Domain; namespace Aop.Api.Response { /// <summary> /// KoubeiMerchantKbdeviceDispenserQueryResponse. /// </summary> public class KoubeiMerchantKbdeviceDispenserQueryResponse : AopResponse { /// <summary> /// 取餐柜设备是否可用 /// </summary> [XmlElement("availability")] public bool Availability { get; set; } /// <summary> /// 取餐柜的单元格详情列表 /// </summary> [XmlArray("cell_info_list")] [XmlArrayItem("food_dispenser_cell_info")] public List<FoodDispenserCellInfo> CellInfoList { get; set; } /// <summary> /// 取餐柜的唯一设备ID /// </summary> [XmlElement("device_id")] public string DeviceId { get; set; } } }
26.424242
76
0.579128
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Response/KoubeiMerchantKbdeviceDispenserQueryResponse.cs
928
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using ICSharpCode.SharpDevelop.Dom.Refactoring; using ICSharpCode.SharpDevelop.Gui; namespace ICSharpCode.PackageManagement { public class DocumentLoader : IDocumentLoader { public IRefactoringDocument LoadRefactoringDocument(string fileName) { return LoadRefactoringDocumentView(fileName).RefactoringDocument; } public IRefactoringDocumentView LoadRefactoringDocumentView(string fileName) { if (WorkbenchSingleton.InvokeRequired) { return WorkbenchSingleton.SafeThreadFunction(() => LoadRefactoringDocumentView(fileName)); } else { return new RefactoringDocumentView(fileName); } } } }
30.888889
103
0.790168
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/Misc/PackageManagement/Project/Src/DocumentLoader.cs
836
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; //This Manager is used to manage each game session that a player has. namespace SA { public class SessionManager : MonoBehaviour { // Start is called before the first frame update public static SessionManager singleton; public delegate void OnSceneLoaded(); public OnSceneLoaded onSceneLoaded; private void Awake() { if (singleton == null) { DontDestroyOnLoad(this.gameObject); } else { Destroy(this.gameObject); } } public void LoadGameLevel(OnSceneLoaded callback) { onSceneLoaded = callback; StartCoroutine("scene1"); } public void LoadMenu() { StartCoroutine("menu"); } IEnumerator LoadLevel(string level) { yield return SceneManager.LoadSceneAsync(level, LoadSceneMode.Single); if (onSceneLoaded != null) { onSceneLoaded(); onSceneLoaded = null; } } } }
24.78
82
0.553672
[ "MIT" ]
jody1999/ClimateChangeGame
Assets/Scripts/Manager/SessionManager.cs
1,241
C#
using AniSharp.Types.Connections; using CSGraphQL.GraphQL; using CSGraphQL.GraphQL.Short; namespace AniSharp.Types.Users { //Fix recursion public class Favourites : GraphQlType { [TypeField] public MediaConnection Anime { get; set; } [TypeField] public MediaConnection Manga { get; set; } [TypeField] public CharacterConnection Characters { get; set; } [TypeField] public StaffConnection Staff { get; set; } [TypeField] public StudioConnection Studios { get; set; } } }
30.25
65
0.752066
[ "MIT" ]
MaximumOverflow/AniSharp
AniSharp/Types/Users/Favourites.cs
484
C#
using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Microsoft.Azure.WebJobs.Extensions.SignalRService; using System.Net.Http; using System.Collections.Generic; using Microsoft.Azure.Documents; namespace AuditTrail.Feature.AuditTrail.AzureFunctions.SignalR { public static class GeneralHub { [FunctionName("GeneralHubSubscribe")] public static SignalRConnectionInfo GetSignalRInfo( [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequestMessage req, [SignalRConnectionInfo(HubName = "General")] SignalRConnectionInfo connectionInfo) { return connectionInfo; } // called when cosmos changes [FunctionName("GeneralHubUpdate")] public static async Task SendMessage( [CosmosDBTrigger( databaseName: "audit-trail", collectionName: "audit-records", ConnectionStringSetting = "COSMOS_CONNECTION_STRING", LeaseCollectionName = "leases", CreateLeaseCollectionIfNotExists = true)]IReadOnlyList<Document> documents, [SignalR(HubName = "General")] IAsyncCollector<SignalRMessage> signalRMessages, ILogger log) { log.LogInformation("Cosmos Trigger!!"); await signalRMessages.AddAsync( new SignalRMessage { Target = "GeneralEventUpdate", // the name of this value corresponds with the function called from the client using JavaScript Arguments = new object[] { JsonConvert.SerializeObject(documents) } }); } } }
38.844444
146
0.667048
[ "MIT" ]
robhabraken/sitecore-audit-trail
AuditTrail/AuditTrail.Feature.AuditTrail.AzureFunctions/SignalR/GeneralHub.cs
1,748
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class Enemy : MonoBehaviour { public Transform target; private NavMeshAgent agent; // Start is called before the first frame update void Start() { agent = GetComponent<NavMeshAgent>(); } // Update is called once per frame void Update() { agent.SetDestination(target.position); } }
18.04
52
0.674058
[ "Unlicense" ]
AceofGrades/Cert4Programming
Artificial-Intelligence/FirstPersonShooter/Assets/Scripts/Enemy.cs
453
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("AdoFfTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdoFfTest")] [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("C8E8E0C9-0D7E-4871-B038-44BD19506CB0")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.428571
84
0.750929
[ "MIT" ]
phillipsj/ado-ff-test
AdoFfTest/AdoFfTest/Properties/AssemblyInfo.cs
1,348
C#
/***************************************************************************** Copyright 2020 Haiping Chen. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ namespace Tensorflow.Keras.Datasets { public class KerasDataset { public Mnist mnist { get; } = new Mnist(); } }
37.458333
79
0.599555
[ "Apache-2.0" ]
Liang813/TensorFlow.NET
src/TensorFlowNET.Keras/Datasets/KerasDataset.cs
901
C#
using ChatClient.Commands.NavigationCommands; using ChatClient.Enums; using ChatClient.Interfaces.BaseConfiguration; using ChatClient.Interfaces.Factories; using SharedItems.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace ChatClient.MVVM.ViewModels.ChatMainViewModels { public class MainViewModel : ViewModelBase { private readonly INavigator _navigator; private readonly IViewModelAbstractFactory _viewModelFactory; public MainViewModel(INavigator navigator, IViewModelAbstractFactory viewModelFactory) { _navigator = navigator; _viewModelFactory = viewModelFactory; _navigator.CurrentViewModelChanged += OnCurrentViewModelChanged; UpdateCurrentViewModelCommand = new UpdateCurrentViewModelCommand(_navigator, _viewModelFactory); UpdateCurrentViewModelCommand.Execute(ViewType.Login); } private readonly ICommand UpdateCurrentViewModelCommand; public ViewModelBase CurrentViewModel => _navigator.CurrentViewModel; private void OnCurrentViewModelChanged() { OnPropertyChanged(nameof(CurrentViewModel)); } } }
30.952381
109
0.75
[ "MIT" ]
TheAlexLight/SignalR_Chat
ChatClient/MVVM/ViewModels/ChatMainViewModels/MainViewModel.cs
1,302
C#
///author:huwei ///date:2018.4.17 using TrueSync; using AStarMachine; namespace PathFinding { class GridNode : AStarNode { public IInt2 gridPos; // Tile XY public GridNode() { gridPos.x = 0; gridPos.y = 0; } public override void Reset() { base.Reset(); gridPos.x = 0; gridPos.y = 0; } } }
18.125
56
0.45977
[ "Apache-2.0" ]
weiou063374/path_finding
Assets/PathFinding/GridNode.cs
437
C#
using System; using System.IO.MemoryMappedFiles; using System.Runtime.InteropServices; namespace EventStore.Core.DataStructures.ProbabilisticFilter.MemoryMappedFileBloomFilter { [StructLayout(LayoutKind.Explicit, Size = Size, Pack = 1)] public struct Header { internal const byte CurrentVersion = 1; internal const int Size = 16; [FieldOffset(0)] private byte _version; [FieldOffset(4)] private int _corruptionRebuildCount; [FieldOffset(8)] private long _numBits; public byte Version { get => _version; set => _version = value; } public int CorruptionRebuildCount { get => _corruptionRebuildCount; set => _corruptionRebuildCount = value; } public long NumBits { get => _numBits; set => _numBits = value; } public static Header ReadFrom(MemoryMappedFile mmf) { try { //read the version first using (var headerAccessor = mmf.CreateViewAccessor(0, 1, MemoryMappedFileAccess.Read)) { byte version = headerAccessor.ReadByte(0); if (version != CurrentVersion) { throw new CorruptedFileException($"Unsupported version: {version}"); } } //then the full header var headerBytes = new byte[Size].AsSpan(); using (var headerAccessor = mmf.CreateViewStream(0, Size, MemoryMappedFileAccess.Read)) { int read = headerAccessor.Read(headerBytes); if (read != Size) { throw new CorruptedFileException( $"File header size ({read} bytes) does not match expected header size ({Size} bytes)"); } } return MemoryMarshal.AsRef<Header>(headerBytes); } catch(Exception exc) when (!(exc is CorruptedFileException)) { throw new CorruptedFileException("Failed to read the header"); } } public void WriteTo(MemoryMappedFile mmf) { var span = MemoryMarshal.CreateReadOnlySpan(ref this, 1); var headerBytes = MemoryMarshal.Cast<Header, byte>(span); using var headerAccessor = mmf.CreateViewStream(0, Size, MemoryMappedFileAccess.Write); headerAccessor.Write(headerBytes); headerAccessor.Flush(); } } }
30.909091
94
0.711765
[ "Apache-2.0", "CC0-1.0" ]
EventStore/EventStore
src/EventStore.Core/DataStructures/ProbabilisticFilter/MemoryMappedFileBloomFilter/Header.cs
2,040
C#