commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13 values | lang stringclasses 23 values |
|---|---|---|---|---|---|---|---|---|
5f697740723a99e09ef81b18c0731c8615a6ca24 | Add manyVerticesSample | charlenni/Mapsui,pauldendulk/Mapsui,charlenni/Mapsui | Samples/Mapsui.Samples.Common/Maps/ManyVerticesSample.cs | Samples/Mapsui.Samples.Common/Maps/ManyVerticesSample.cs | using System.Collections.Generic;
using Mapsui.Geometries;
using Mapsui.Layers;
using Mapsui.Providers;
using Mapsui.Styles;
using Mapsui.UI;
using Mapsui.Utilities;
// ReSharper disable UnusedAutoPropertyAccessor.Local
namespace Mapsui.Samples.Common.Maps
{
public class ManyVerticesSample : ISample
{
public string Name => "Many Vertices";
public string Category => "Special";
public void Setup(IMapControl mapControl)
{
mapControl.Map = CreateMap();
}
public static Map CreateMap()
{
var map = new Map();
map.Layers.Add(OpenStreetMap.CreateTileLayer());
map.Layers.Add(CreatePointLayer());
map.Home = n => n.NavigateTo(map.Layers[1].Envelope.Grow(map.Layers[1].Envelope.Width * 0.25));
return map;
}
private static ILayer CreatePointLayer()
{
return new Layer
{
Name = "Points",
IsMapInfoLayer = true,
DataSource = new MemoryProvider(GetFeature())
};
}
private static IFeature GetFeature()
{
var feature = new Feature();
var startPoint = new Point(1623484, 7652571);
var points = new List<Point>();
for (int i = 0; i < 10000; i++)
{
points.Add(new Point(startPoint.X + i, startPoint.Y + i));
}
AddStyles(feature);
feature.Geometry = new LineString(points);
return feature;
}
private static void AddStyles(Feature feature)
{
// route outline style
VectorStyle vsout = new VectorStyle
{
Opacity = 0.5f,
Line = new Pen(Color.White, 10f),
};
VectorStyle vs = new VectorStyle
{
Fill = null,
Outline = null,
Line = { Color = Color.Red, Width = 5f }
};
feature.Styles.Add(vsout);
feature.Styles.Add(vs);
}
}
} | mit | C# | |
cf9a7d1c2494b273e33141f314af027ea73139f7 | Create FileSystemWatch.cs | UnityCommunity/UnityLibrary | Scripts/Helpers/FileSystem/FileSystemWatch.cs | Scripts/Helpers/FileSystem/FileSystemWatch.cs | using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
// watches specified folder changes in the filesystem
// "Listens to the file system change notifications and raises events when a directory, or file in a directory, changes."
// references: http://stackoverflow.com/questions/15017506/using-filesystemwatcher-to-monitor-a-directory and http://www.c-sharpcorner.com/article/monitoring-file-system-using-filesystemwatcher-class-part1/
public class FileSystemWatch : MonoBehaviour
{
string myPath = "c:\\myfolder\\";
FileSystemWatcher watcher;
void Start()
{
InitFileSystemWatcher();
}
private void InitFileSystemWatcher()
{
watcher = new FileSystemWatcher();
watcher.Path = myPath;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
//Handler for Changed Event
watcher.Changed += new FileSystemEventHandler(FileChanged);
//Handler for Created Event
watcher.Created += new FileSystemEventHandler(FileCreated);
//Handler for Deleted Event
watcher.Deleted += new FileSystemEventHandler(FileDeleted);
//Handler for Renamed Event
watcher.Renamed += new RenamedEventHandler(FileRenamed);
watcher.EnableRaisingEvents = true;
}
private void FileChanged(object source, FileSystemEventArgs e)
{
Debug.Log("FileChanged:" + e.FullPath);
}
private void FileCreated(object source, FileSystemEventArgs e)
{
Debug.Log("FileCreated:" + e.FullPath);
}
private void FileDeleted(object source, FileSystemEventArgs e)
{
Debug.Log("FileDeleted:" + e.FullPath);
}
private void FileRenamed(object source, FileSystemEventArgs e)
{
Debug.Log("FileChanged:" + e.FullPath);
}
}
| mit | C# | |
51a925efe135de034b387bd90ccfbdae26c29dff | Add AIWolf.Server.DataConverter to AIWolfServer. | AIWolfSharp/AIWolf_NET | AIWolfServer/DataConverter.cs | AIWolfServer/DataConverter.cs | //
// DataConverter.cs
//
// Copyright (c) 2016 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Linq;
using System.Collections.Generic;
namespace AIWolf.Server
{
#if JHELP
/// <summary>
/// オブジェクトとJSON文字列を相互に変換する
/// </summary>
#else
/// <summary>
/// Converts object into JSON string and vice versa.
/// </summary>
#endif
static class DataConverter
{
static JsonSerializerSettings serializerSetting;
/// <summary>
/// Initializes this class.
/// </summary>
static DataConverter()
{
serializerSetting = new JsonSerializerSettings()
{
// Sort.
ContractResolver = new OrderedContractResolver()
};
// Do not convert enum into integer.
serializerSetting.Converters.Add(new StringEnumConverter());
}
#if JHELP
/// <summary>
/// オブジェクトをJSON文字列に変換する
/// </summary>
/// <param name="obj">変換するオブジェクト</param>
/// <returns>オブジェクトを変換したJSON文字列</returns>
#else
/// <summary>
/// Serializes the given object into the JSON string.
/// </summary>
/// <param name="obj">The object to be serialized.</param>
/// <returns>The JSON string serialized from the given object.</returns>
#endif
public static string Serialize(object obj) => JsonConvert.SerializeObject(obj, serializerSetting);
#if JHELP
/// <summary>
/// JSON文字列をT型のオブジェクトに変換する
/// </summary>
/// <typeparam name="T">返されるオブジェクトの型</typeparam>
/// <param name="json">変換するJSON文字列</param>
/// <returns>JSON文字列を変換したT型のオブジェクト</returns>
#else
/// <summary>
/// Deserializes the given JSON string into the object of type T.
/// </summary>
/// <typeparam name="T">The type of object returned.</typeparam>
/// <param name="json">The JSON string to be deserialized.</param>
/// <returns>The object of type T deserialized from the JSON string.</returns>
#endif
public static T Deserialize<T>(string json) => JsonConvert.DeserializeObject<T>(json, serializerSetting);
class OrderedContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
=> base.CreateProperties(type, memberSerialization).OrderBy(p => p.PropertyName).ToList();
}
}
}
| mit | C# | |
b568d6b627a3de5947e9c436c4aec0ef55cf57d7 | Fix possible infinite loop in ButtonToggleBase. | ryanwang/LeapMotionCoreAssets,Amarcolina/LeapMotionCoreAssets | Assets/LeapMotion/Widgets/Scripts/Button/ButtonToggleBase.cs | Assets/LeapMotion/Widgets/Scripts/Button/ButtonToggleBase.cs | using UnityEngine;
using System.Collections;
namespace LMWidgets
{
public abstract class ButtonToggleBase : ButtonBase, BinaryInteractionHandler<bool>, IDataBoundWidget<ButtonToggleBase, bool> {
protected DataBinderToggle m_dataBinder;
protected bool m_toggleState = true;
public abstract void ButtonTurnsOn();
public abstract void ButtonTurnsOff();
/// <summary>
/// Gets or sets the current state of the toggle button.
/// </summary>
public bool ToggleState {
get { return m_toggleState; }
set {
if ( m_toggleState == value ) { return; }
setButtonState(value);
}
}
protected override void Start() {
if ( m_dataBinder != null ) {
setButtonState(m_dataBinder.GetCurrentData(), true); // Initilize widget value
}
else {
setButtonState(false, true);
}
}
public void SetWidgetValue(bool value) {
if ( State == LeapPhysicsState.Interacting ) { return; } // Don't worry about state changes during interaction.
setButtonState (value);
}
// Stop listening to any previous data binder and start listening to the new one.
public void RegisterDataBinder(LMWidgets.DataBinder<LMWidgets.ButtonToggleBase, bool> dataBinder) {
if (dataBinder == null) {
return;
}
UnregisterDataBinder ();
m_dataBinder = dataBinder as DataBinderToggle;
setButtonState(m_dataBinder.GetCurrentData());
}
// Stop listening to any previous data binder.
public void UnregisterDataBinder() {
m_dataBinder = null;
}
private void setButtonState(bool toggleState, bool force = false) {
if ( toggleState == m_toggleState && !force ) { return; } // Don't do anything if there's no change
m_toggleState = toggleState;
if (m_toggleState == true)
ButtonTurnsOn();
else
ButtonTurnsOff();
}
protected override void buttonReleased()
{
base.FireButtonEnd(m_toggleState);
if ( m_dataBinder != null ) {
setButtonState(m_dataBinder.GetCurrentData()); // Update once we're done interacting
}
}
protected override void buttonPressed()
{
if (m_toggleState == false)
ButtonTurnsOn();
else
ButtonTurnsOff();
ToggleState = !ToggleState;
base.FireButtonStart(m_toggleState);
}
}
}
| using UnityEngine;
using System.Collections;
namespace LMWidgets
{
public abstract class ButtonToggleBase : ButtonBase, BinaryInteractionHandler<bool>, IDataBoundWidget<ButtonToggleBase, bool> {
protected DataBinderToggle m_dataBinder;
protected bool m_toggleState = true;
public abstract void ButtonTurnsOn();
public abstract void ButtonTurnsOff();
/// <summary>
/// Gets or sets the current state of the toggle button.
/// </summary>
/// <remarks>
/// Setting this property will also update any associated data-binder.
/// </remarks>
public bool ToggleState {
get { return m_toggleState; }
set {
setButtonState(value);
if ( m_dataBinder != null ) { m_dataBinder.SetCurrentData(m_toggleState); } // Update externally linked data
}
}
protected override void Start() {
if ( m_dataBinder != null ) {
setButtonState(m_dataBinder.GetCurrentData(), true); // Initilize widget value
}
else {
setButtonState(false, true);
}
}
public void SetWidgetValue(bool value) {
if ( State == LeapPhysicsState.Interacting ) { return; } // Don't worry about state changes during interaction.
setButtonState (value);
}
// Stop listening to any previous data binder and start listening to the new one.
public void RegisterDataBinder(LMWidgets.DataBinder<LMWidgets.ButtonToggleBase, bool> dataBinder) {
if (dataBinder == null) {
return;
}
UnregisterDataBinder ();
m_dataBinder = dataBinder as DataBinderToggle;
setButtonState(m_dataBinder.GetCurrentData());
}
// Stop listening to any previous data binder.
public void UnregisterDataBinder() {
m_dataBinder = null;
}
private void setButtonState(bool toggleState, bool force = false) {
if ( toggleState == m_toggleState && !force ) { return; } // Don't do anything if there's no change
m_toggleState = toggleState;
if (m_toggleState == true)
ButtonTurnsOn();
else
ButtonTurnsOff();
}
protected override void buttonReleased()
{
base.FireButtonEnd(m_toggleState);
if ( m_dataBinder != null ) {
setButtonState(m_dataBinder.GetCurrentData()); // Update once we're done interacting
}
}
protected override void buttonPressed()
{
if (m_toggleState == false)
ButtonTurnsOn();
else
ButtonTurnsOff();
ToggleState = !ToggleState;
base.FireButtonStart(m_toggleState);
}
}
}
| apache-2.0 | C# |
557a566d6ab785d8813a1053fadf11c23b88b33d | Update ArkAccountTopList.cs | sharkdev-j/ark-net,kristjank/ark-net | ark-net/Model/Account/ArkAccountTopList.cs | ark-net/Model/Account/ArkAccountTopList.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ArkAccountTopList.cs" company="Ark">
// MIT License
// //
// // Copyright (c) 2017 Kristjan Košič
// //
// // Permission is hereby granted, free of charge, to any person obtaining a copy
// // of this software and associated documentation files (the "Software"), to deal
// // in the Software without restriction, including without limitation the rights
// // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// // copies of the Software, and to permit persons to whom the Software is
// // furnished to do so, subject to the following conditions:
// //
// // The above copyright notice and this permission notice shall be included in all
// // copies or substantial portions of the Software.
// //
// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// // SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Collections.Generic;
using ArkNet.Model.BaseModels;
namespace ArkNet.Model.Account
{
/// <summary>
/// Extends the <see cref="ArkResponseBase"/> type for the Ark Account Top List response model.
/// </summary>
///
// note: terminology might have been 'ArkTopAcccountList'.
public class ArkAccountTopList : ArkResponseBase
{
/// <summary>
/// The list of requested account tops.
/// </summary>
///
/// <value>Gets/sets the value as a <see cref="List"/> of type <see cref="ArkAccountTop"/>.</value>
///
public List<ArkAccountTop> Accounts { get; set; }
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ArkAccountTopList.cs" company="Ark Labs">
// MIT License
// //
// // Copyright (c) 2017 Kristjan Košič
// //
// // Permission is hereby granted, free of charge, to any person obtaining a copy
// // of this software and associated documentation files (the "Software"), to deal
// // in the Software without restriction, including without limitation the rights
// // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// // copies of the Software, and to permit persons to whom the Software is
// // furnished to do so, subject to the following conditions:
// //
// // The above copyright notice and this permission notice shall be included in all
// // copies or substantial portions of the Software.
// //
// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// // SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Collections.Generic;
using ArkNet.Model.BaseModels;
namespace ArkNet.Model.Account
{
/// <summary>
/// Extends the <see cref="ArkResponseBase"/> type for the Ark Account Top List response model.
/// </summary>
///
// note: terminology might have been 'ArkTopAcccountList'.
public class ArkAccountTopList : ArkResponseBase
{
/// <summary>
/// The list of requested account tops.
/// </summary>
///
/// <value>Gets/sets the value as a <see cref="List"/> of type <see cref="ArkAccountTop"/>.</value>
///
public List<ArkAccountTop> Accounts { get; set; }
}
}
| mit | C# |
4df95c4e35010556e43b4fc57ade34cc2825a88b | fix version number | OpenRA/tao,mono/tao,mono/tao,OpenRA/tao | Framework/Projects/Tao.Sdl/AssemblyInfo.cs | Framework/Projects/Tao.Sdl/AssemblyInfo.cs | #region License
/*
MIT License
Copyright 2003-2005 Tao Framework Team
http://www.taoframework.com
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion License
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyCompany("Tao Framework -- http://www.taoframework.com")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Retail")]
#endif
[assembly: AssemblyCopyright("Copyright 2003-2005 Tao Framework Team. All rights reserved.")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDefaultAlias("Tao.Sdl")]
[assembly: AssemblyDelaySign(false)]
#if WIN32
[assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Windows)")]
#elif LINUX
[assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Linux)")]
#endif
[assembly: AssemblyFileVersion("1.2.7.1")]
[assembly: AssemblyInformationalVersion("1.2.7.1")]
#if STRONG
[assembly: AssemblyKeyFile(@"..\..\Solutions\Tao.Sdl\Solution Items\Tao.Sdl.snk")]
#else
[assembly: AssemblyKeyFile("")]
#endif
[assembly: AssemblyKeyName("")]
#if DEBUG
[assembly: AssemblyProduct("Tao.Sdl.dll *** Debug Build ***")]
#else
[assembly: AssemblyProduct("Tao.Sdl.dll")]
#endif
#if WIN32
[assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Windows)")]
#elif LINUX
[assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Linux)")]
#endif
[assembly: AssemblyTrademark("Tao Framework -- http://www.taoframework.com")]
[assembly: AssemblyVersion("1.2.7.1")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]
| #region License
/*
MIT License
Copyright 2003-2005 Tao Framework Team
http://www.taoframework.com
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion License
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyCompany("Tao Framework -- http://www.taoframework.com")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Retail")]
#endif
[assembly: AssemblyCopyright("Copyright 2003-2005 Tao Framework Team. All rights reserved.")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDefaultAlias("Tao.Sdl")]
[assembly: AssemblyDelaySign(false)]
#if WIN32
[assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Windows)")]
#elif LINUX
[assembly: AssemblyDescription("Tao Framework SDL Binding For .NET (Linux)")]
#endif
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0.0")]
#if STRONG
[assembly: AssemblyKeyFile(@"..\..\Solutions\Tao.Sdl\Solution Items\Tao.Sdl.snk")]
#else
[assembly: AssemblyKeyFile("")]
#endif
[assembly: AssemblyKeyName("")]
#if DEBUG
[assembly: AssemblyProduct("Tao.Sdl.dll *** Debug Build ***")]
#else
[assembly: AssemblyProduct("Tao.Sdl.dll")]
#endif
#if WIN32
[assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Windows)")]
#elif LINUX
[assembly: AssemblyTitle("Tao Framework SDL Binding For .NET (Linux)")]
#endif
[assembly: AssemblyTrademark("Tao Framework -- http://www.taoframework.com")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.SkipVerification)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]
| mit | C# |
be7f1f8dc16ffa52a7df4c231c82cd366e41839e | Create BotControlScript.cs | MesoamericaAppsHackatonPanama2013/SimulacionDesastres | BotControlScript.cs | BotControlScript.cs | using UnityEngine;
using System.Collections;
// Require these components when using this script
[RequireComponent(typeof (Animator))]
public class BotControlScript : MonoBehaviour
{
[System.NonSerialized]
public float lookWeight; // the amount to transition when using head look
public float animSpeed = 1.5f; // a public setting for overall animator animation speed
public float lookSmoother = 3f; // a smoothing setting for camera motion
private Animator anim; // a reference to the animator on the character
private AnimatorStateInfo currentBaseState; // a reference to the current state of the animator, used for base layer
private AnimatorStateInfo layer2CurrentState; // a reference to the current state of the animator, used for layer 2
static int idleState = Animator.StringToHash("Base Layer.Idle");
static int locoState = Animator.StringToHash("Base Layer.Locomotion"); // these integers are references to our animator's states
static int jumpState = Animator.StringToHash("Base Layer.Jump"); // and are used to check state for various actions to occur
static int jumpDownState = Animator.StringToHash("Base Layer.JumpDown"); // within our FixedUpdate() function below
static int fallState = Animator.StringToHash("Base Layer.Fall");
static int rollState = Animator.StringToHash("Base Layer.Roll");
static int waveState = Animator.StringToHash("Layer2.Wave");
void Start ()
{
// initialising reference variables
anim = GetComponent<Animator>();
if(anim.layerCount ==2)
anim.SetLayerWeight(1, 1);
}
void FixedUpdate ()
{
float h = Input.GetAxis("Horizontal"); // setup h variable as our horizontal input axis
float v = Input.GetAxis("Vertical"); // setup v variables as our vertical input axis
anim.SetFloat("Speed", v); // set our animator's float parameter 'Speed' equal to the vertical input axis
anim.SetFloat("Direction", h); // set our animator's float parameter 'Direction' equal to the horizontal input axis
anim.speed = animSpeed; // set the speed of our animator to the public variable 'animSpeed'
anim.SetLookAtWeight(lookWeight); // set the Look At Weight - amount to use look at IK vs using the head's animation
currentBaseState = anim.GetCurrentAnimatorStateInfo(0); // set our currentState variable to the current state of the Base Layer (0) of animation
if(anim.layerCount ==2)
layer2CurrentState = anim.GetCurrentAnimatorStateInfo(1); // set our layer2CurrentState variable to the current state of the second Layer (1) of animation
// IDLE
// check if we are at idle, if so, let us Wave!
if (currentBaseState.nameHash == idleState)
{
if(Input.GetButtonUp("Jump"))
{
anim.SetBool("Wave", true);
}
}
// if we enter the waving state, reset the bool to let us wave again in future
if(layer2CurrentState.nameHash == waveState)
{
anim.SetBool("Wave", false);
}
}
}
| mit | C# | |
b58084621e6757c2ccdb88fb0a42cdcab0faabf7 | Add unspecific IgnoreAttribute | rapidcore/rapidcore,rapidcore/rapidcore | src/core/main/IgnoreAttribute.cs | src/core/main/IgnoreAttribute.cs | using System;
namespace RapidCore
{
/// <summary>
/// Just a generic "ignore" something attribute
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public class IgnoreAttribute : Attribute
{
}
} | mit | C# | |
d6981634e41926c801d00d4be426754e894b048e | implement ClickJacking Protection Module - This module checks to see if protection against click jacking attacks is disabled for any paths. If the appSettings section of web.config file contains an etry CMSXFrameOptionsExclude, that means that the protection is disabled for the paths specified in the result . https://docs.kentico.com/display/K9/Clickjacking | ChristopherJennings/KInspector,Kentico/KInspector,JosefDvorak/KInspector,ChristopherJennings/KInspector,JosefDvorak/KInspector,ChristopherJennings/KInspector,JosefDvorak/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,Kentico/KInspector,Kentico/KInspector | KInspector.Modules/Modules/Security/ClickJackingModule.cs | KInspector.Modules/Modules/Security/ClickJackingModule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kentico.KInspector.Modules.Modules.Security
{
class ClickJackingModule
{
}
}
| mit | C# | |
95fd7c97c9d64fc611a09c55779dda596976a527 | Add in actual GitDescribeTest file | wrozmiarek/msbuildtasks,smallkid/msbuildtasks,arekbee/msbuildtasks,AArnott/msbuildtasks,jricke/msbuildtasks,loresoft/msbuildtasks,stimpy77/msbuildtasks | Source/MSBuild.Community.Tasks.Tests/Git/GitDescribeTest.cs | Source/MSBuild.Community.Tasks.Tests/Git/GitDescribeTest.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using MSBuild.Community.Tasks.Git;
using NUnit.Framework;
namespace MSBuild.Community.Tasks.Tests.Git
{
[TestFixture]
public class GitDescribeTest
{
[Test]
public void GitDescribeExecute()
{
var task = new GitDescribe();
task.BuildEngine = new MockBuild();
task.ToolPath = @"C:\Program Files (x86)\Git\bin";
string prjRootPath = TaskUtility.GetProjectRootDirectory(true);
task.LocalPath = Path.Combine(prjRootPath, @"Source");
bool result = task.Execute();
Assert.IsTrue(result, "Execute Failed");
Assert.AreNotEqual(task.CommitCount, -1); // -1 designates a soft error. Only should occur in soft error mode
Assert.IsFalse(string.IsNullOrEmpty(task.CommitHash), "Invalid Revision Number");
}
}
}
| bsd-2-clause | C# | |
4e7128d951fa844649cef35b791620e91432cde7 | Add GitHub build server | laedit/vika | src/NVika/BuildServers/GitHub.cs | src/NVika/BuildServers/GitHub.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.ComponentModel.Composition;
using System.Text;
using NVika.Abstractions;
using NVika.Parsers;
namespace NVika.BuildServers
{
internal sealed class GitHub : BuildServerBase
{
private readonly IEnvironment _environment;
[ImportingConstructor]
internal GitHub(IEnvironment environment)
{
_environment = environment;
}
public override string Name => nameof(GitHub);
public override bool CanApplyToCurrentContext() => !string.IsNullOrEmpty(_environment.GetEnvironmentVariable("GITHUB_ACTIONS"));
public override void WriteMessage(Issue issue)
{
var outputString = new StringBuilder();
switch (issue.Severity)
{
case IssueSeverity.Error:
outputString.Append("::error ");
break;
case IssueSeverity.Warning:
outputString.Append("::warning");
break;
}
if (issue.FilePath != null)
{
var file = issue.Project != null
? issue.FilePath.Replace(issue.Project + @"\", string.Empty)
: issue.FilePath;
outputString.Append($"file={file},");
}
if (issue.Offset != null)
outputString.Append($"col={issue.Offset.Start},");
outputString.Append($"line={issue.Line}::{issue.Message}");
Console.WriteLine(outputString.ToString());
}
}
}
| apache-2.0 | C# | |
8453b4a79ac85fd338f23f1941005ac0ad788ae1 | Add AssemblyInfo for ColorPicker.csproj | AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia | src/Avalonia.Controls.ColorPicker/Properties/AssemblyInfo.cs | src/Avalonia.Controls.ColorPicker/Properties/AssemblyInfo.cs | using System.Runtime.CompilerServices;
using Avalonia.Metadata;
[assembly: InternalsVisibleTo("Avalonia.DesignerSupport, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c1bba1142285fe0419326fb25866ba62c47e6c2b5c1ab0c95b46413fad375471232cb81706932e1cef38781b9ebd39d5100401bacb651c6c5bbf59e571e81b3bc08d2a622004e08b1a6ece82a7e0b9857525c86d2b95fab4bc3dce148558d7f3ae61aa3a234086902aeface87d9dfdd32b9d2fe3c6dd4055b5ab4b104998bd87")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls.Collections")]
[assembly: XmlnsDefinition("https://github.com/avaloniaui", "Avalonia.Controls.Primitives")]
| mit | C# | |
615bc2c75002eb6ad84d74fda89f24b7299698d8 | Add back-/forward compatibility tests | ZEISS-PiWeb/PiWeb-Api | src/Api.Rest.Dtos.Tests/Compatibility/CompatibilityTests.cs | src/Api.Rest.Dtos.Tests/Compatibility/CompatibilityTests.cs | #region copyright
/* * * * * * * * * * * * * * * * * * * * * * * * * */
/* Carl Zeiss Industrielle Messtechnik GmbH */
/* Softwaresystem PiWeb */
/* (c) Carl Zeiss 2022 */
/* * * * * * * * * * * * * * * * * * * * * * * * * */
#endregion
namespace Zeiss.PiWeb.Api.Rest.Dtos.Tests.Compatibility;
#region usings
using System;
using System.Collections;
using NUnit.Framework;
using Zeiss.PiWeb.Api.Rest.Dtos.Data;
#endregion
[TestFixture]
public class CompatibilityTests
{
#region members
private static readonly AttributeDefinitionDto AttributeDefinition = new()
{
Key = 13,
Description = "Test",
Length = 43,
QueryEfficient = false,
Type = AttributeTypeDto.AlphaNumeric
};
private static readonly CatalogAttributeDefinitionDto CatalogAttributeDefinition = new()
{
Key = 13,
Description = "Test",
QueryEfficient = false,
Catalog = new Guid( "11D4115C-41A7-4D47-A353-AF5DF61503EA" )
};
private static object[] TestCases =
{
new object[] { AttributeDefinition, (AttributeDefinitionDto value) => Tuple.Create( value.Key, value.Description, value.Length, value.QueryEfficient, value.Type ) },
new object[] { CatalogAttributeDefinition, (CatalogAttributeDefinitionDto value ) => Tuple.Create( value.Key, value.Description, value.QueryEfficient, value.Catalog ) },
};
#endregion
#region methods
[TestCaseSource( nameof( TestCases ) )]
public void Backward_Compatible<T>( T value, Func<T, IStructuralEquatable> createEquatable )
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject( value );
var deserializedValue = System.Text.Json.JsonSerializer.Deserialize<T>( json );
var expected = createEquatable( value );
var actual = createEquatable( deserializedValue );
Assert.AreEqual( expected, actual, $"{typeof( T ).Name}" );
}
[TestCaseSource( nameof( TestCases ) )]
public void Forward_Compatible<T>( T value, Func<T, IStructuralEquatable> createEquatable )
{
var json = System.Text.Json.JsonSerializer.Serialize( value );
var deserializedValue = Newtonsoft.Json.JsonConvert.DeserializeObject<T>( json );
var expected = createEquatable( value );
var actual = createEquatable( deserializedValue );
Assert.AreEqual( expected, actual, $"{typeof( T ).Name}" );
}
#endregion
} | bsd-3-clause | C# | |
4d30419249bd5a1802dcd7dd3025c3afde9cc9b7 | add NoProxyHttpClientHandler.cs | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | src/WeihanLi.Common/NoProxyHttpClientHandler.cs | src/WeihanLi.Common/NoProxyHttpClientHandler.cs | using System.Net.Http;
namespace WeihanLi.Common
{
public class NoProxyHttpClientHandler : HttpClientHandler
{
public NoProxyHttpClientHandler()
{
Proxy = null;
UseProxy = false;
}
}
}
| mit | C# | |
ec96963f45c4686f3ed8cc7ea52b786e0bf3cec2 | Create WarCardGame.cs | cwesnow/Net_Fiddle | 2017Aug/WarCardGame.cs | 2017Aug/WarCardGame.cs | using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("A Game of War");
War.Start();
}
}
public class War {
public static void Start(){
Deck deck1 = new Deck();
Deck deck2 = new Deck();
deck1.Shuffle();
deck2.Shuffle();
int x = 0;
while(true){
x++;
Console.WriteLine("Round: {0,-3}", x);
flip(deck1,deck2);
if(deck1.isNull()) {
if( deck1.hasReserve() ) { deck1.Shuffle(); } else { break; }
}
if(deck2.isNull()) {
if( deck2.hasReserve() ) { deck2.Shuffle(); } else { break; }
}
}
Console.WriteLine("End of Game! {0} Wins!", deck2.isNull() ? "Player 1" : "Player 2");
}
// Round of Play - Each Player Draws a Card, Evaluates Win/Lose/War response
static void flip(Deck deck1, Deck deck2) {
List<Card> played = new List<Card>();
Card card1 = deck1.Draw();
played.Add(card1);
Card card2 = deck2.Draw();
played.Add(card2);
int WinLoseDraw = checkCards(card1, card2);
while(WinLoseDraw == 0 && (!deck1.isNull() || !deck2.isNull())) {
// Nested Ternary (conditional) ? true : false statements
Console.WriteLine("{0,-5} vs {1,-5} {2,-5}",
card1, card2, "This means WAR!");
card1 = deck1.Draw();
played.Add(card1);
card2 = deck2.Draw();
played.Add(card2);
card1 = deck1.Draw();
played.Add(card1);
card2 = deck2.Draw();
played.Add(card2);
WinLoseDraw = checkCards(card1, card2);
}
// Nested Ternary (conditional) ? true : false statements
Console.WriteLine("{0,-5} vs {1,-5} {2,-5}",
card1, card2, WinLoseDraw == 1 ? "Win" : "Lose");
if(WinLoseDraw == 1) deck1.won(played); else deck2.won(played);
}
static int checkCards(Card c1, Card c2){
// Check for Nulls
if( c1 == null && c2 == null) return 0;
if (c1 == null || c2 == null) return (c1 != null) ? 1 : -1;
// Equality check
if( c1.worth == c2.worth ) return 0;
return c1.worth > c2.worth ? 1 : -1;
}
}
public class Deck {
static Random rng = new Random();
List<Card> deck = new List<Card>(); // Current
List<Card> reserve = new List<Card>(); // Winnings
Char[] faces = {'D', 'H', 'S', 'C'};
int[] values = { 2,3,4,5,6,7,8,9,10,11,12,13,14};
// Constructor - Generates a classic 52 card deck
public Deck(){
foreach(Char face in faces) {
foreach(int val in values) {
deck.Add(new Card(face,val));
}
}
}
public bool isNull() { return deck.Count == 0 ? true : false; }
public bool hasReserve() { return reserve.Count == 0 ? true : false; }
// Shuffles list of cards
public void Shuffle() {
deck.AddRange(reserve);
reserve.RemoveRange(0, reserve.Count);
for(int x = deck.Count-1; x > 0; x--) {
int index = rng.Next(x+1); // Random #
Card card = deck[index]; // Temp Value
deck[index] = deck[x]; // Swap 1
deck[x] = card; // Swap 2
}
}
// Returns a card, after removing one from deck. Returns null if no cards left
public Card Draw() {
if( deck.Count < 1 ) return null;
Card card = deck[0];
deck.RemoveAt(0);
return card;
}
public Card Draw2() {
Draw(); // Face Down Card
return Draw();
}
public void won(List<Card> winnings) {
reserve.AddRange(winnings);
}
}
public class Card {
public int worth;
public char face;
public Card(char face, int worth) {
this.face = face;
this.worth = worth;
}
public override string ToString(){
return String.Format("{0}:{1}", face, worth);
}
}
| mit | C# | |
ee64d5356b0655f3512ed01962a99acd30662d1a | Add FileFinder to test suite to enable compilation | Zeugma440/atldotnet | ATL.test/FileFinder.cs | ATL.test/FileFinder.cs | using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ATL.test
{
[TestClass]
public class FileFinder
{
[TestMethod]
public void FF_RecursiveExplore()
{
//String dirName = "E:/Music/Classique";
//String dirName = "E:/Music/Films & TV";
//String dirName = "E:/Music/René";
//String dirName = "E:/Music/Divers";
//String dirName = "E:/Music/Anime";
//String dirName = "E:/Music/VGM";
String dirName = "E:/temp/id3v2";
String filter = "*.mp3";
DirectoryInfo dirInfo = new DirectoryInfo(dirName);
foreach (FileInfo f in dirInfo.EnumerateFiles(filter,SearchOption.AllDirectories))
{
Track t = new Track(f.FullName);
System.Console.WriteLine(f.FullName);
}
}
[TestMethod]
public void FF_ReadOneFile()
{
Track t = new Track("E:/temp/id3v2/01 - Opening_unsynch.mp3");
}
}
}
| mit | C# | |
8e6bb8ddb60f1a39358eb7b477d47b02a4e8f0f1 | Create Problem112.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem112.cs | Problems/Problem112.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler.Problems
{
class Problem112
{
private bool IsBouncy(int number)
{
if (number < 100) { return false; }
int a, b;
bool increasing = true;
bool decreasing = true;
do
{
a = number % 10;
b = (number / 10) % 10;
increasing &= (a >= b);
decreasing &= (a <= b);
number /= 10;
} while (number >= 10);
return !(increasing || decreasing);
}
private bool IsBouncy2(int number)
{
if (number < 100) { return false; }
string numberS = number.ToString();
bool increasing = true;
bool decreasing = true;
bool allEqual = true;
for (int i = 0; i < numberS.Length - 1; i++)
{
increasing &= int.Parse(numberS[i].ToString()) <= int.Parse(numberS[i + 1].ToString());
decreasing &= int.Parse(numberS[i].ToString()) >= int.Parse(numberS[i + 1].ToString());
allEqual &= int.Parse(numberS[i].ToString()) == int.Parse(numberS[i + 1].ToString());
}
return !(increasing || decreasing || allEqual);
}
public void Run()
{
double target = 0.99;
double count = 0;
double rate = 0;
int i;
for (i = 100; rate < target; )
{
if (IsBouncy2(i))
{
count++;
//Console.WriteLine(i.ToString() + " @ " + rate.ToString());
}
rate = (count / (i)); // Zero counts as Number
if (rate == target)
{
break;
}
i++;
}
Console.WriteLine(i.ToString() + " @ " + rate.ToString());
}
}
}
| mit | C# | |
dd69d142b3df64f166a9a064098eebac70628b0f | Create Problem357.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem357.cs | Problems/Problem357.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
namespace ProjectEuler.Problems
{
class Problem357
{
private static Sieve s;
private static bool SumDivIsPrime(long num)
{
// divisor d of n, d+n/d is prime
long top = (long)Math.Sqrt(num);
// d = 1
if (!s.prime[num + 1])
{
// 1 + num/1 = num+1 (Must be prime)
return false;
}
for (long d = 2; d <= top; d++)
{
if (num % d == 0)
{
if (!s.prime[d + num / d])
{
return false;
}
}
}
return true;
}
private static bool SumDivIsPrimeB(long num)
{
// divisor d of n, d+n/d is prime
long top = (long) Math.Sqrt(num);
// d = 1
if (!Sieve.isPrime(num + 1))
{
// 1 + num/1 = num+1 (Must be prime)
return false;
}
for (long d = 2; d <= top; d++)
{
if (num % d == 0)
{
if (!Sieve.isPrime(d + num/d)) {
return false;
}
}
}
return true;
}
public static void Run()
{
BigInteger sum = 0; // 1 + 1/1 = 2 (prime)
long count = 0;
bool printNext = false;
long upper = 100000000;
s = new Sieve(upper+1);
long period = upper / 100;
for (long n = 1; n <= upper; n++)
{
if (n % period == 0)
{
printNext = true;
}
if (SumDivIsPrime(n))
{
sum += n;
count++;
if (printNext)
{
printNext = false;
Console.WriteLine("({0}) {1} = {2}", count, n, sum);
}
}
}
using (StreamWriter str_out = new StreamWriter("C:/data/p357.txt", true))
{
str_out.WriteLine("({0})<={1} : {2}", count, upper, sum);
}
Console.WriteLine("TOTAL({0}) = {1}", count, sum);
Console.ReadLine();
}
}
}
| mit | C# | |
4ed46c8dc0687fd7eac9fc6b2c66e78256a4a3ea | define IResourceService | json-api-dotnet/JsonApiDotNetCore,Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core | src/JsonApiDotNetCore/Services/IResourceService.cs | src/JsonApiDotNetCore/Services/IResourceService.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using JsonApiDotNetCore.Models;
namespace JsonApiDotNetCore.Services
{
public interface IResourceService<T> : IResourceService<T, int>
where T : class, IIdentifiable<int>
{ }
public interface IResourceService<T, TId>
where T : class, IIdentifiable<TId>
{
Task<IEnumerable<T>> GetAsync();
Task<T> GetAsync(TId id);
Task<object> GetRelationshipsAsync(TId id, string relationshipName);
Task<object> GetRelationshipAsync(TId id, string relationshipName);
Task<T> CreateAsync(T entity);
Task<T> UpdateAsync(TId id, T entity);
Task UpdateRelationshipsAsync(TId id, string relationshipName, List<DocumentData> relationships);
Task<bool> DeleteAsync(TId id);
}
}
| mit | C# | |
3fac25db1c85bc3112b43332af3af10e411ad63d | Add DatabaseBuilder.cs | Ackara/Daterpillar | src/Tests.Daterpillar/Utilities/DatabaseBuilder.cs | src/Tests.Daterpillar/Utilities/DatabaseBuilder.cs | using Gigobyte.Daterpillar.Transformation;
using System.Data;
namespace Tests.Daterpillar.Utilities
{
public static class DatabaseBuilder
{
public static bool TryCreateDatabase(IDbConnection connection, Schema schema)
{
throw new System.NotImplementedException();
}
}
} | mit | C# | |
2d8ef6f541da7d0213e4f7416bdb0e539c259721 | Add interface for CDU access | c0nnex/SPAD.neXt,c0nnex/SPAD.neXt | SPAD.Interfaces/Gauges/ICDUScreen.cs | SPAD.Interfaces/Gauges/ICDUScreen.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SPAD.neXt.Interfaces.Gauges
{
/// <summary>
/// CDU cell color
/// </summary>
public enum CDU_COLOR
{
WHITE = 0,
CYAN = 1,
GREEN = 2,
MAGENTA = 3,
AMBER = 4,
RED = 5,
}
/// <summary>
/// CDU cell flags
/// </summary>
[Flags]
public enum CDU_FLAG
{
/// <summary>
/// small font, including that used for line headers
/// </summary>
SMALL_FONT = 0x01,
/// <summary>
/// character background is highlighted in reverse video
/// </summary>
REVERSE = 0x02,
/// <summary>
/// dimmed character color indicating inop/unused entries
/// </summary>
UNUSED = 0x04,
}
public enum CDU_NUMBER
{
Left = 0,
Captain = 0,
Right = 1,
FirstOfficer = 1,
Center = 2,
}
/// <summary>
/// A single CDU cell
/// </summary>
public interface CDU_Cell
{
/// <summary>
/// Cell Character
/// (hex A1 / dec 161) is a left arrow
/// (hex A2 / dec 162) is a right arrow
/// </summary>
char Symbol { get; }
/// <summary>
/// Cell color <see cref="CDU_COLOR"/>
/// </summary>
CDU_COLOR Color { get; }
/// <summary>
/// Cell Flags <see cref="CDU_FLAG"/>
/// </summary>
CDU_FLAG Flags { get; }
}
/// <summary>
/// Interface to read CDU content (if supported by aircraft)
/// </summary>
public interface ICDUScreen
{
/// <summary>
/// Powerstatus of CDU
/// </summary>
bool Powered { get; }
CDU_NUMBER CDUNumber { get; }
/// <summary>
/// Get content of a CDU row
/// </summary>
/// <param name="rowNumber">Row number ( 0 - 13 )</param>
/// <param name="startOffset">Starting offset ( 0 - 23 )</param>
/// <param name="endOffset">End offset ( 0 - 23 ) , -1 = all remaining characters</param>
/// <returns>Content of CDU row</returns>
string GetRow(int rowNumber, int startOffset = 0, int endOffset = -1);
/// <summary>
/// Get content of a CDU column
/// </summary>
/// <param name="colNumber">Column number ( 0 - 23 )</param>
/// <returns>Content of CDU column of all rows</returns>
string GetCol(int colNumber);
/// <summary>
/// Get a single CDU cell value
/// </summary>
/// <param name="rowNumber">Row number ( 0 - 13 )</param>
/// <param name="colNumber">Column number ( 0 - 23 )</param>
/// <returns><see cref="CDU_Cell"/> with cell content</returns>
CDU_Cell GetCell(int rowNumber, int colNumber);
}
}
| mit | C# | |
bfd908fc4752c7e5ec0e5c646d05d48487da2b26 | add Upgrade_20221006_DraftJS | signumsoftware/framework,signumsoftware/framework | Signum.Upgrade/Upgrades/Upgrade_20221006_DraftJS.cs | Signum.Upgrade/Upgrades/Upgrade_20221006_DraftJS.cs | using Signum.Utilities;
using System.Collections.Generic;
namespace Signum.Upgrade.Upgrades;
class Upgrade_20221006_DraftJS : CodeUpgradeBase
{
public override string Description => "Adds draftjs as a dependency for email templates";
public override void Execute(UpgradeContext uctx)
{
uctx.ForeachCodeFile("package.json", file =>
{
file.InsertAfterLastLine(a => a.Contains("@fortawesome"), "\"@types/draft-js\": \"0.11.9\"");
file.InsertBeforeFirstLine(a => a.Contains("\"history\""), "\"draft-js\": \"0.11.7\"");
file.InsertBeforeFirstLine(a => a.Contains("\"history\""), "\"draftjs-to-html\": \"0.9.1\"");
file.InsertAfterFirstLine(a => a.Contains("\"history\""), "\"html-to-draftjs\": \"1.5.0\"");
});
}
}
| mit | C# | |
861d2651d1dbe458710db9ad7fc132e68f597bf8 | Update Path2DPathEffect.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.ViewModels/Style/PathEffects/Path2DPathEffect.cs | src/Draw2D.ViewModels/Style/PathEffects/Path2DPathEffect.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Runtime.Serialization;
using Spatial;
namespace Draw2D.ViewModels.Style.PathEffects
{
[DataContract(IsReference = true)]
public class Path2DPathEffect : ViewModelBase, IPathEffect
{
private Matrix _matrix;
private string _path;
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public Matrix Matrix
{
get => _matrix;
set => Update(ref _matrix, value);
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public string Path
{
get => _path;
set => Update(ref _path, value);
}
public Path2DPathEffect()
{
}
public Path2DPathEffect(Matrix matrix, string path)
{
this.Matrix = matrix;
this.Path = path;
}
public static IPathEffect MakeTile()
{
var matrix = Matrix.MakeFrom(Matrix2.Scale(30, 30));
var path = "M-15 -15L15 -15L15 15L-15 15L-15 -15Z";
return new Path2DPathEffect(matrix, path) { Title = "2DPathTile" };
}
public object Copy(Dictionary<object, object> shared)
{
return new Path2DPathEffect()
{
Title = this.Title,
Matrix = (Matrix)this.Matrix.Copy(shared),
Path = this.Path
};
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Draw2D.ViewModels.Style.PathEffects
{
[DataContract(IsReference = true)]
public class Path2DPathEffect : ViewModelBase, IPathEffect
{
private Matrix _matrix;
private string _path;
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public Matrix Matrix
{
get => _matrix;
set => Update(ref _matrix, value);
}
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public string Path
{
get => _path;
set => Update(ref _path, value);
}
public Path2DPathEffect()
{
}
public Path2DPathEffect(Matrix matrix, string path)
{
this.Matrix = matrix;
this.Path = path;
}
public static IPathEffect MakeTile()
{
// TODO:
var matrix = Matrix.MakeIdentity();
matrix.ScaleX = 30;
matrix.ScaleY = 30;
var path = "M-15 -15L15 -15L15 15L-15 15L-15 -15Z";
return new Path2DPathEffect(matrix, path) { Title = "2DPathTile" };
}
public object Copy(Dictionary<object, object> shared)
{
return new Path2DPathEffect()
{
Title = this.Title,
Matrix = (Matrix)this.Matrix.Copy(shared),
Path = this.Path
};
}
}
}
| mit | C# |
6a68c7e88b33a3591455c38e342e1f6114374450 | Add Controller for the xml sequential Operate | Andy-Sun/Unity3d-Sequential | scripts/Controller.cs | scripts/Controller.cs | /*
* Author: AndySun
* Date: 2015-07-20
* Description: 控制XML存储操作的顺序执行。
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Controller : MonoBehaviour
{
/// <summary>
/// 所有操作的列表
/// </summary>
List<OperItem> list = new List<OperItem>();
static OperItem currentItem;//当前操作项
static int id = 0;//操作项编号
void Start()
{
list = XMLRW.ReadXML("OrderConfig.xml");
currentItem = list[id];
}
void Update()
{
if (id < list.Count)
{
switch (currentItem.type)
{
case EOperType.Trans:
if (Vector3.Distance(currentItem.trans.position, currentItem.param) > currentItem.precision)
{
currentItem.trans.position = Vector3.Lerp(currentItem.trans.position, currentItem.param, currentItem.speed);
}
else
NextStep();
break;
case EOperType.Rot:
if (Vector3.Distance(currentItem.trans.localEulerAngles, currentItem.param) > currentItem.precision)
{
currentItem.trans.localEulerAngles = Vector3.Lerp(currentItem.trans.localEulerAngles, currentItem.param, currentItem.speed);
}
else
NextStep();
break;
case EOperType.SetParent:
currentItem.trans.SetParent(currentItem.parent);
NextStep();
break;
default:
break;
}
}
}
/// <summary>
/// 执行下一步操作
/// </summary>
void NextStep()
{
++id;
if (id != list.Count)
{
currentItem = list[id];
}
}
}
| mit | C# | |
70eb2103e7765e0efd703e7a1ad3a350a83cd99d | Create SwitchObject.cs | xxmon/unity | SwitchObject.cs | SwitchObject.cs | using UnityEngine;
using System.Collections;
public class SwitchObject : MonoBehaviour
{
public bool on = false;
public GameObject objectOn;
public GameObject objectOff;
// Use this for initialization
void Start ()
{
updateObjects ();
}
// Update is called once per frame
void Update ()
{
}
void updateObjects ()
{
if (objectOn == null || objectOff == null) {
return;
}
if (on) {
objectOn.SetActive (true);
objectOff.SetActive (false);
} else {
objectOn.SetActive (false);
objectOff.SetActive (true);
}
}
void switchObjects ()
{
on = !on;
updateObjects ();
}
void switchOn ()
{
on = true;
updateObjects ();
}
void switchOff ()
{
on = false;
updateObjects ();
}
void OnValidate ()
{
updateObjects ();
}
}
| mit | C# | |
526dcf111f937e6337dd06ac8e48080183ad8f8b | add markdownValidatorContext data model (#2477) | superyyrrzz/docfx,superyyrrzz/docfx,dotnet/docfx,superyyrrzz/docfx,dotnet/docfx,dotnet/docfx | src/Microsoft.DocAsCode.Plugins/IMarkdownValidatorContext.cs | src/Microsoft.DocAsCode.Plugins/IMarkdownValidatorContext.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Plugins
{
public interface IMarkdownValidatorContext
{
string GlobalRulesFilePath { get; }
string CustomRulesFilePath { get; }
}
}
| mit | C# | |
92428e230fd993188b84747755ef50333c26ddbe | Add texture cropping test case | ZLima12/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework | osu.Framework.Tests/Visual/Sprites/TestSceneTextureCropping.cs | osu.Framework.Tests/Visual/Sprites/TestSceneTextureCropping.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Framework.Testing;
using osuTK;
namespace osu.Framework.Tests.Visual.Sprites
{
public class TestSceneTextureCropping : GridTestScene
{
public TestSceneTextureCropping()
: base(3, 3)
{
}
protected override void LoadComplete()
{
base.LoadComplete();
for (int i = 0; i < Rows; ++i)
{
for (int j = 0; j < Cols; ++j)
{
RectangleF cropRectangle = new RectangleF(i / 3f, j / 3f, 1 / 3f, 1 / 3f);
Cell(i, j).AddRange(new Drawable[]
{
new SpriteText
{
Text = $"{cropRectangle}",
Font = new FontUsage(size: 14),
},
new Container
{
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Masking = true,
Children = new Drawable[]
{
new Sprite
{
RelativeSizeAxes = Axes.Both,
Texture = texture.Crop(cropRectangle, relativeSizeAxes: Axes.Both),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
}
}
});
}
}
}
private Texture texture;
[BackgroundDependencyLoader]
private void load(TextureStore store)
{
texture = store.Get(@"sample-texture");
}
}
}
| mit | C# | |
b68995af20a2da7f68f450524bdd5274f9249020 | Create Frag.cs | alchemz/ARL_Training | recursive/Frag.cs | recursive/Frag.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Frag : MonoBehaviour {
public Mesh mesh;
public Material material;
private int depth;
public int maxDepth;
public float childScale;
// Use this for initialization
void Start () {
gameObject.AddComponent<MeshFilter> ().mesh = mesh;
gameObject.AddComponent<MeshRenderer> ().material = material;
GetComponent<MeshRenderer>().material.color =
Color.Lerp(Color.white, Color.yellow, (float)depth / maxDepth);
if (depth < maxDepth) {
StartCoroutine (createChildren ());
}
}
private IEnumerator createChildren(){
yield return new WaitForSeconds(0.5f);
new GameObject ("Child").AddComponent<Frag> ().initialize (this, Vector3.up, Quaternion.identity);
yield return new WaitForSeconds(0.5f);
new GameObject ("Child").AddComponent<Frag> ().initialize (this, Vector3.down, Quaternion.Euler(0f,0f,90f));
yield return new WaitForSeconds(0.5f);
new GameObject ("Child").AddComponent<Frag> ().initialize (this, Vector3.left,Quaternion.Euler(0f,0f,-90f));
}
private void initialize(Frag parent, Vector3 direction, Quaternion orientation){
mesh = parent.mesh;
material = parent.material;
depth = parent.depth + 1;
maxDepth = parent.maxDepth;
transform.parent = parent.transform;
childScale = parent.childScale;
transform.localScale = Vector3.one * childScale;
transform.localPosition = direction * (0.5f + 0.5f * childScale);
transform.localRotation = orientation;
}
// Update is called once per frame
void Update () {
}
}
| mit | C# | |
17dbec8975a701d028425c0b9ac4cc8cc39702ac | Add missing test file from last commit | stephentoub/MidiSharp | MidiSharp.Tests/SequenceTests.cs | MidiSharp.Tests/SequenceTests.cs | //-----------------------------------------------------------------------
// <copyright file="SequenceTests.cs.cs" company="Stephen Toub">
// Copyright (c) Stephen Toub. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MidiSharp.Events.Meta;
using MidiSharp.Events.Voice.Note;
using System.IO;
using System.Linq;
namespace MidiSharp.Tests
{
[TestClass]
public sealed class SequenceTests
{
[TestMethod]
public void RoundtripEvents()
{
MidiSequence seq1 = CreateScaleSequence();
string tmpPath = Path.GetTempFileName();
using (var s = File.OpenWrite(tmpPath)) {
seq1.Save(s);
}
MidiSequence seq2;
using (var s = File.OpenRead(tmpPath)) {
seq2 = MidiSequence.Open(s);
}
AssertAreEqual(seq1, seq2);
File.Delete(tmpPath);
}
[TestMethod]
public void CloneEvents()
{
MidiSequence seq1 = CreateScaleSequence();
MidiSequence seq2 = new MidiSequence(seq1);
Assert.AreNotSame(seq1, seq2);
AssertAreEqual(seq1, seq2);
}
[TestMethod]
public void Transpose()
{
for (int steps = -7; steps <= 7; steps++) {
MidiSequence seq1 = CreateScaleSequence();
MidiSequence seq2 = new MidiSequence(seq1);
seq2.Transpose(steps);
var onEvents1 = seq1.SelectMany(t => t.Events).OfType<OnNoteVoiceMidiEvent>().ToArray();
var offEvents1 = seq1.SelectMany(t => t.Events).OfType<OffNoteVoiceMidiEvent>().ToArray();
var onEvents2 = seq2.SelectMany(t => t.Events).OfType<OnNoteVoiceMidiEvent>().ToArray();
var offEvents2 = seq2.SelectMany(t => t.Events).OfType<OffNoteVoiceMidiEvent>().ToArray();
Assert.AreEqual(onEvents1.Length, onEvents2.Length);
Assert.AreEqual(offEvents1.Length, offEvents2.Length);
Assert.AreEqual(onEvents1.Length, offEvents1.Length);
for (int i = 0; i < onEvents1.Length; i++) {
Assert.AreEqual(onEvents1[i].Note + steps, onEvents2[i].Note);
Assert.AreEqual(offEvents1[i].Note + steps, offEvents2[i].Note);
}
}
}
static MidiSequence CreateScaleSequence()
{
var sequence = new MidiSequence();
var events = sequence.AddTrack().Events;
string[] notes = new[] { "C5", "D5", "E5", "F5", "G5", "A5", "B5", "C6", "C6", "B5", "A5", "G5", "F5", "E5", "D5", "C5" };
events.AddRange(notes.SelectMany(note => NoteVoiceMidiEvent.Complete(100, 0, note, 127, 100)));
events.Add(new EndOfTrackMetaMidiEvent(notes.Length * 100));
return sequence;
}
static void AssertAreEqual(MidiSequence sequence1, MidiSequence sequence2)
{
Assert.AreEqual(sequence1.Format, sequence2.Format);
Assert.AreEqual(sequence1.Division, sequence2.Division);
Assert.AreEqual(sequence1.DivisionType, sequence2.DivisionType);
Assert.AreEqual(sequence1.TrackCount, sequence2.TrackCount);
for (int i = 0; i < sequence1.TrackCount; i++) {
AssertAreEqual(sequence1[i], sequence2[i]);
}
}
static void AssertAreEqual(MidiTrack track1, MidiTrack track2)
{
Assert.AreEqual(track1.Events.Count, track2.Events.Count);
for (int j = 0; j < track1.Events.Count; j++) {
Assert.AreEqual(track1.Events[j].ToString(), track2.Events[j].ToString());
}
}
}
} | mit | C# | |
e1eda89ea69234164ae055d1f129626d8fc970f7 | Implement OnlineContainer | ppy/osu,2yangk23/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,peppy/osu,peppy/osu-new,EVAST9919/osu,EVAST9919/osu,smoogipooo/osu,johnneijzen/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu | osu.Game/Online/OnlineContainer.cs | osu.Game/Online/OnlineContainer.cs | using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API;
using osu.Game.Online.Placeholders;
namespace osu.Game.Online
{
/// <summary>
/// A <see cref="Container"/> for dislaying online content who require a local user to be logged in.
/// Shows its children only when the local user is logged in and supports displaying a placeholder if not.
/// </summary>
public class OnlineViewContainer : Container, IOnlineComponent
{
private readonly Container content;
private readonly Container placeholderContainer;
private readonly Placeholder placeholder;
private const int transform_time = 300;
protected override Container<Drawable> Content => content;
public OnlineViewContainer(string placeholder_message)
{
InternalChildren = new Drawable[]
{
content = new Container
{
RelativeSizeAxes = Axes.Both,
},
placeholderContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
Child = placeholder = new LoginPlaceholder()
},
};
}
public void APIStateChanged(IAPIProvider api, APIState state)
{
switch (state)
{
case APIState.Offline:
case APIState.Connecting:
Schedule(() =>updatePlaceholderVisibility(true));
break;
default:
Schedule(() => updatePlaceholderVisibility(false));
break;
}
}
private void updatePlaceholderVisibility(bool show_placeholder)
{
if (show_placeholder)
{
content.FadeOut(transform_time / 2, Easing.OutQuint);
placeholder.ScaleTo(0.8f).Then().ScaleTo(1, 3 * transform_time, Easing.OutQuint);
placeholderContainer.FadeInFromZero(2 * transform_time, Easing.OutQuint);
}
else
{
placeholderContainer.FadeOut(transform_time / 2, Easing.OutQuint);
content.FadeIn(transform_time, Easing.OutQuint);
}
}
[BackgroundDependencyLoader]
private void load(IAPIProvider api)
{
api.Register(this);
}
}
}
| mit | C# | |
cdb41ec0a370de4f3d9eccd254d3274235845031 | Put the Convert.ToDouble, which we need to make things generic in the Plot helpers... | gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT | LINQToTTree/LINQToTTreeLib/TypeHandlers/TypeHandlerConvert.cs | LINQToTTree/LINQToTTreeLib/TypeHandlers/TypeHandlerConvert.cs | using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq.Expressions;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Expressions;
namespace LINQToTTreeLib.TypeHandlers
{
/// <summary>
/// The Convert.ToDouble is sometimes used in our code. Deal with it.
/// cleanly here.
/// Convert.ToDouble (value) for example.
/// </summary>
[Export(typeof(ITypeHandler))]
class TypeHandlerConvert : ITypeHandler
{
public bool CanHandle(Type t)
{
return t == typeof(Convert);
}
/// <summary>
/// There is never a constant reference, so don't let it go!
/// </summary>
/// <param name="expr"></param>
/// <param name="codeEnv"></param>
/// <param name="context"></param>
/// <param name="container"></param>
/// <returns></returns>
public IValue ProcessConstantReference(System.Linq.Expressions.ConstantExpression expr, IGeneratedCode codeEnv, ICodeContext context, System.ComponentModel.Composition.Hosting.CompositionContainer container)
{
throw new NotImplementedException();
}
/// <summary>
/// Deal with the various method calls to convert.
/// </summary>
/// <param name="expr"></param>
/// <param name="result"></param>
/// <param name="gc"></param>
/// <param name="context"></param>
/// <param name="container"></param>
/// <returns></returns>
public System.Linq.Expressions.Expression ProcessMethodCall(MethodCallExpression expr, out IValue result, IGeneratedCode gc, ICodeContext context, CompositionContainer container)
{
if (expr.Method.Name == "ToDouble")
return ProcessToDouble(expr, out result, gc, context, container);
///
/// We don't know how to deal with this particular convert!
///
throw new NotImplementedException("Can't translate the call Convert." + expr.Method.Name);
}
/// <summary>
/// Convert something to a double. We don't actually do anything as long as this is an expression that we
/// can naturally convert (int, float, etc.).
///
/// We are expecting an expressio nthat is ToDouble(Convert()), so if we can't see the convert, then we bail.
/// </summary>
/// <param name="expr"></param>
/// <param name="result"></param>
/// <param name="gc"></param>
/// <param name="context"></param>
/// <param name="container"></param>
/// <returns></returns>
private Expression ProcessToDouble(MethodCallExpression expr, out IValue result, IGeneratedCode gc, ICodeContext context, CompositionContainer container)
{
var srcExpr = expr.Arguments[0];
if (srcExpr.NodeType != ExpressionType.Convert)
throw new NotImplementedException("Expecting a Convert expression inside the call to Convert.ToDouble");
var cvtExpr = srcExpr as UnaryExpression;
result = ExpressionToCPP.GetExpression(cvtExpr.Operand, gc, context, container);
if (
result.Type != typeof(int)
&& result.Type != typeof(double)
&& result.Type != typeof(float)
)
{
throw new NotImplementedException("Do not know how to convert '" + srcExpr.Type.Name + "' to a double!");
}
return expr;
}
}
}
| lgpl-2.1 | C# | |
35d68d7c0bd3ab1272ae22f65dd5264f2e7bf5b9 | Add a proof-of-concept test | EamonNerbonne/ExpressionToCode | ExpressionToCodeTest/TopLevelProgramTest.cs | ExpressionToCodeTest/TopLevelProgramTest.cs | using System;
using TopLevelProgramExample;
using Xunit;
namespace ExpressionToCodeTest
{
public class TopLevelProgramTest
{
[Fact]
public void CanRunTopLevelProgram()
{
var topLevelProgram = (Action<string[]>)Delegate.CreateDelegate(typeof(Action<string[]>), typeof(TopLevelProgramMarker).Assembly.EntryPoint);
topLevelProgram(new []{"test"});
}
}
}
| apache-2.0 | C# | |
cb629b83b98bdfe74dbb2ad9f620887578efb2c2 | Create IsItHalloween.cs | SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming | Kattis-Solutions/IsItHalloween.cs | Kattis-Solutions/IsItHalloween.cs | using System;
namespace Is_It_Halloween
{
class Program
{
static void Main(string[] args)
{
string s = Console.ReadLine();
if(s.Equals("OCT 31") || s.Equals("DEC 25"))
{
Console.WriteLine("yup");
}
else
{
Console.WriteLine("nope");
}
}
}
}
| mit | C# | |
1fccba152cb4c44ed631c137e08d924d49184176 | Create Palindrome-Checker.cs | DeanCabral/Code-Snippets | Palindrome-Checker.cs | Palindrome-Checker.cs | class Palindrome
{
static void Main(string[] args)
{
GetUserInput();
}
static void GetUserInput()
{
string input = "";
string output = "";
Console.Write("Enter a word: ");
input = Console.ReadLine();
output = Palindrome.IsPalindrome(input) ? "This word is a Palindrome. True." : "This word is not a Palindrome. False.";
Console.WriteLine(output);
Console.WriteLine();
GetUserInput();
}
static bool IsPalindrome(string word)
{
List<char> characters = new List<char>();
int count = 0;
foreach (char c in word)
{
characters.Add(c);
}
for (int i = 0; i < characters.Count; i++)
{
if (characters[i] == characters[(characters.Count - 1) - i]) count++;
}
return word.Length == count;
}
}
| mit | C# | |
9feb6003a052367de5175f0b5831a48d2e7a9108 | Implement get solider query | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Queries/GetSoldier.cs | Battery-Commander.Web/Queries/GetSoldier.cs | using BatteryCommander.Web.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Queries
{
public class GetSoldier : IRequest<Soldier>
{
public int Id { get; }
public GetSoldier(int id)
{
Id = id;
}
private class Handler : IRequestHandler<GetSoldier, Soldier>
{
private readonly Database db;
public Handler(Database db)
{
this.db = db;
}
public async Task<Soldier> Handle(GetSoldier query, CancellationToken cancellationToken)
{
var soldier =
await db
.Soldiers
.Include(s => s.Supervisor)
.Include(s => s.SSDSnapshots)
.Include(s => s.ABCPs)
.Include(s => s.ACFTs)
.Include(s => s.APFTs)
.Include(s => s.Unit)
.Where(s => s.Id == query.Id)
.SingleOrDefaultAsync(cancellationToken);
return soldier;
}
}
}
} | mit | C# | |
2bf968511290f0af037c3d607c7baad764928704 | Add comment for OSX specific FileSystem test | iamjasonp/corefx,krk/corefx,BrennanConroy/corefx,ravimeda/corefx,the-dwyer/corefx,twsouthwick/corefx,Chrisboh/corefx,cydhaselton/corefx,fgreinacher/corefx,ViktorHofer/corefx,krytarowski/corefx,krk/corefx,nchikanov/corefx,pallavit/corefx,tijoytom/corefx,lggomez/corefx,parjong/corefx,billwert/corefx,nbarbettini/corefx,DnlHarvey/corefx,stone-li/corefx,khdang/corefx,jlin177/corefx,alphonsekurian/corefx,SGuyGe/corefx,manu-silicon/corefx,MaggieTsang/corefx,adamralph/corefx,seanshpark/corefx,jlin177/corefx,parjong/corefx,elijah6/corefx,krytarowski/corefx,nbarbettini/corefx,mazong1123/corefx,elijah6/corefx,ellismg/corefx,iamjasonp/corefx,DnlHarvey/corefx,khdang/corefx,Priya91/corefx-1,cydhaselton/corefx,billwert/corefx,wtgodbe/corefx,alphonsekurian/corefx,MaggieTsang/corefx,Chrisboh/corefx,shimingsg/corefx,tijoytom/corefx,the-dwyer/corefx,rjxby/corefx,jhendrixMSFT/corefx,iamjasonp/corefx,cydhaselton/corefx,Ermiar/corefx,rahku/corefx,zhenlan/corefx,tijoytom/corefx,Petermarcu/corefx,pallavit/corefx,dsplaisted/corefx,khdang/corefx,zhenlan/corefx,jlin177/corefx,shimingsg/corefx,DnlHarvey/corefx,dhoehna/corefx,YoupHulsebos/corefx,shimingsg/corefx,Ermiar/corefx,krk/corefx,MaggieTsang/corefx,yizhang82/corefx,dsplaisted/corefx,axelheer/corefx,mazong1123/corefx,jhendrixMSFT/corefx,lggomez/corefx,Petermarcu/corefx,shmao/corefx,rahku/corefx,pallavit/corefx,tijoytom/corefx,Petermarcu/corefx,twsouthwick/corefx,manu-silicon/corefx,nbarbettini/corefx,axelheer/corefx,gkhanna79/corefx,Petermarcu/corefx,yizhang82/corefx,Jiayili1/corefx,MaggieTsang/corefx,ravimeda/corefx,shimingsg/corefx,ravimeda/corefx,dotnet-bot/corefx,ravimeda/corefx,marksmeltzer/corefx,YoupHulsebos/corefx,Petermarcu/corefx,the-dwyer/corefx,cartermp/corefx,JosephTremoulet/corefx,ellismg/corefx,lggomez/corefx,zhenlan/corefx,seanshpark/corefx,jhendrixMSFT/corefx,rahku/corefx,seanshpark/corefx,stone-li/corefx,rubo/corefx,dotnet-bot/corefx,alphonsekurian/corefx,the-dwyer/corefx,parjong/corefx,lggomez/corefx,nbarbettini/corefx,Ermiar/corefx,billwert/corefx,fgreinacher/corefx,Ermiar/corefx,zhenlan/corefx,shimingsg/corefx,manu-silicon/corefx,manu-silicon/corefx,pallavit/corefx,wtgodbe/corefx,lggomez/corefx,alexperovich/corefx,Jiayili1/corefx,nchikanov/corefx,weltkante/corefx,jlin177/corefx,mazong1123/corefx,mazong1123/corefx,lggomez/corefx,weltkante/corefx,rjxby/corefx,shahid-pk/corefx,ViktorHofer/corefx,ravimeda/corefx,marksmeltzer/corefx,weltkante/corefx,gkhanna79/corefx,cydhaselton/corefx,SGuyGe/corefx,ellismg/corefx,DnlHarvey/corefx,yizhang82/corefx,Petermarcu/corefx,elijah6/corefx,Priya91/corefx-1,shmao/corefx,khdang/corefx,stone-li/corefx,ptoonen/corefx,cydhaselton/corefx,mmitche/corefx,Priya91/corefx-1,twsouthwick/corefx,jlin177/corefx,dhoehna/corefx,MaggieTsang/corefx,shmao/corefx,khdang/corefx,JosephTremoulet/corefx,jlin177/corefx,ericstj/corefx,JosephTremoulet/corefx,ViktorHofer/corefx,seanshpark/corefx,alexperovich/corefx,Jiayili1/corefx,dhoehna/corefx,axelheer/corefx,dotnet-bot/corefx,elijah6/corefx,jhendrixMSFT/corefx,rjxby/corefx,marksmeltzer/corefx,zhenlan/corefx,cartermp/corefx,ellismg/corefx,parjong/corefx,ericstj/corefx,tstringer/corefx,ericstj/corefx,mmitche/corefx,shahid-pk/corefx,shmao/corefx,richlander/corefx,axelheer/corefx,Ermiar/corefx,Jiayili1/corefx,YoupHulsebos/corefx,alexperovich/corefx,gkhanna79/corefx,Chrisboh/corefx,YoupHulsebos/corefx,SGuyGe/corefx,nchikanov/corefx,rubo/corefx,dhoehna/corefx,axelheer/corefx,ellismg/corefx,cartermp/corefx,twsouthwick/corefx,mazong1123/corefx,weltkante/corefx,the-dwyer/corefx,nchikanov/corefx,cartermp/corefx,seanshpark/corefx,DnlHarvey/corefx,MaggieTsang/corefx,richlander/corefx,manu-silicon/corefx,tstringer/corefx,stone-li/corefx,marksmeltzer/corefx,manu-silicon/corefx,ericstj/corefx,alexperovich/corefx,weltkante/corefx,BrennanConroy/corefx,rubo/corefx,twsouthwick/corefx,elijah6/corefx,ravimeda/corefx,gkhanna79/corefx,pallavit/corefx,cydhaselton/corefx,rjxby/corefx,YoupHulsebos/corefx,dotnet-bot/corefx,gkhanna79/corefx,Jiayili1/corefx,jhendrixMSFT/corefx,iamjasonp/corefx,ericstj/corefx,pallavit/corefx,mmitche/corefx,stone-li/corefx,SGuyGe/corefx,dotnet-bot/corefx,krk/corefx,stephenmichaelf/corefx,marksmeltzer/corefx,ellismg/corefx,twsouthwick/corefx,ViktorHofer/corefx,dsplaisted/corefx,tijoytom/corefx,rubo/corefx,tstringer/corefx,alexperovich/corefx,Ermiar/corefx,rjxby/corefx,twsouthwick/corefx,Chrisboh/corefx,krk/corefx,JosephTremoulet/corefx,Jiayili1/corefx,YoupHulsebos/corefx,billwert/corefx,ravimeda/corefx,stephenmichaelf/corefx,nchikanov/corefx,parjong/corefx,cydhaselton/corefx,DnlHarvey/corefx,yizhang82/corefx,nbarbettini/corefx,ericstj/corefx,alphonsekurian/corefx,rjxby/corefx,richlander/corefx,DnlHarvey/corefx,rubo/corefx,tijoytom/corefx,nbarbettini/corefx,JosephTremoulet/corefx,wtgodbe/corefx,mmitche/corefx,krytarowski/corefx,richlander/corefx,ViktorHofer/corefx,stephenmichaelf/corefx,shmao/corefx,parjong/corefx,elijah6/corefx,ericstj/corefx,billwert/corefx,billwert/corefx,wtgodbe/corefx,richlander/corefx,Priya91/corefx-1,alexperovich/corefx,nchikanov/corefx,YoupHulsebos/corefx,nbarbettini/corefx,yizhang82/corefx,shahid-pk/corefx,mazong1123/corefx,Jiayili1/corefx,marksmeltzer/corefx,dotnet-bot/corefx,fgreinacher/corefx,yizhang82/corefx,alexperovich/corefx,krytarowski/corefx,krk/corefx,tstringer/corefx,richlander/corefx,alphonsekurian/corefx,rjxby/corefx,zhenlan/corefx,khdang/corefx,Priya91/corefx-1,ptoonen/corefx,alphonsekurian/corefx,wtgodbe/corefx,mazong1123/corefx,jhendrixMSFT/corefx,JosephTremoulet/corefx,alphonsekurian/corefx,billwert/corefx,Chrisboh/corefx,krk/corefx,elijah6/corefx,iamjasonp/corefx,stone-li/corefx,tijoytom/corefx,dhoehna/corefx,stone-li/corefx,Petermarcu/corefx,dhoehna/corefx,tstringer/corefx,MaggieTsang/corefx,shahid-pk/corefx,marksmeltzer/corefx,BrennanConroy/corefx,rahku/corefx,shmao/corefx,mmitche/corefx,cartermp/corefx,tstringer/corefx,stephenmichaelf/corefx,yizhang82/corefx,nchikanov/corefx,gkhanna79/corefx,ptoonen/corefx,weltkante/corefx,ptoonen/corefx,shimingsg/corefx,weltkante/corefx,fgreinacher/corefx,ViktorHofer/corefx,the-dwyer/corefx,krytarowski/corefx,lggomez/corefx,rahku/corefx,Chrisboh/corefx,dhoehna/corefx,the-dwyer/corefx,JosephTremoulet/corefx,zhenlan/corefx,iamjasonp/corefx,stephenmichaelf/corefx,adamralph/corefx,shimingsg/corefx,seanshpark/corefx,richlander/corefx,parjong/corefx,cartermp/corefx,wtgodbe/corefx,dotnet-bot/corefx,shmao/corefx,krytarowski/corefx,jhendrixMSFT/corefx,ViktorHofer/corefx,adamralph/corefx,mmitche/corefx,rahku/corefx,manu-silicon/corefx,seanshpark/corefx,ptoonen/corefx,gkhanna79/corefx,SGuyGe/corefx,stephenmichaelf/corefx,ptoonen/corefx,Priya91/corefx-1,ptoonen/corefx,jlin177/corefx,krytarowski/corefx,Ermiar/corefx,axelheer/corefx,shahid-pk/corefx,SGuyGe/corefx,stephenmichaelf/corefx,iamjasonp/corefx,rahku/corefx,wtgodbe/corefx,mmitche/corefx,shahid-pk/corefx | src/System.IO.FileSystem/tests/Directory/SetCurrentDirectory.cs | src/System.IO.FileSystem/tests/Directory/SetCurrentDirectory.cs | // 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.Diagnostics;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public sealed class Directory_SetCurrentDirectory : RemoteExecutorTestBase
{
[Fact]
public void Null_Path_Throws_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => Directory.SetCurrentDirectory(null));
}
[Fact]
public void Empty_Path_Throws_ArgumentException()
{
Assert.Throws<ArgumentException>(() => Directory.SetCurrentDirectory(string.Empty));
}
[Fact]
public void SetToNonExistentDirectory_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() => Directory.SetCurrentDirectory(GetTestFilePath()));
}
[Fact]
public void SetToValidOtherDirectory()
{
RemoteInvoke(() =>
{
Directory.SetCurrentDirectory(TestDirectory);
// On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current
// directory to a symlinked path will result in GetCurrentDirectory returning the absolute
// path that followed the symlink.
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
}
return SuccessExitCode;
}).Dispose();
}
}
}
| // 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.Diagnostics;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public sealed class Directory_SetCurrentDirectory : RemoteExecutorTestBase
{
[Fact]
public void Null_Path_Throws_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => Directory.SetCurrentDirectory(null));
}
[Fact]
public void Empty_Path_Throws_ArgumentException()
{
Assert.Throws<ArgumentException>(() => Directory.SetCurrentDirectory(string.Empty));
}
[Fact]
public void SetToNonExistentDirectory_ThrowsDirectoryNotFoundException()
{
Assert.Throws<DirectoryNotFoundException>(() => Directory.SetCurrentDirectory(GetTestFilePath()));
}
[Fact]
public void SetToValidOtherDirectory()
{
RemoteInvoke(() =>
{
Directory.SetCurrentDirectory(TestDirectory);
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
}
return SuccessExitCode;
}).Dispose();
}
}
}
| mit | C# |
6eb2be5818c4a36d5c62d04ebbe472145fe47ca8 | Create empty.cs | suppayami/unity2d-tmx | empty.cs | empty.cs | //empty
| mit | C# | |
374c3e3e8dafa28f7f81342782feeac8a675df20 | Add unit tests for the SqlServerStorageEngine class | openchain/openchain | test/Openchain.SqlServer.Tests/SqlServerStorageEngineTests.cs | test/Openchain.SqlServer.Tests/SqlServerStorageEngineTests.cs | // Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace Openchain.Sqlite.Tests
{
public class SqlServerStorageEngineTests : BaseStorageEngineTests
{
private readonly int instanceId;
public SqlServerStorageEngineTests()
{
Random rnd = new Random();
this.instanceId = rnd.Next(0, int.MaxValue);
this.Store = CreateNewEngine();
}
protected override IStorageEngine CreateNewEngine()
{
SqlServerStorageEngine engine = new SqlServerStorageEngine("Data Source=.;Initial Catalog=Openchain;Integrated Security=True", this.instanceId, TimeSpan.FromSeconds(10));
engine.OpenConnection().Wait();
return engine;
}
}
}
| apache-2.0 | C# | |
703c8584c0d7f7fb3eaff6df74ebd1d5c5aa366c | Add Viewmodel base class | Zalodu/Schedutalk,Zalodu/Schedutalk | Schedutalk/Schedutalk/Schedutalk/ViewModel/VMBase.cs | Schedutalk/Schedutalk/Schedutalk/ViewModel/VMBase.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Schedutalk.ViewModel
{
abstract class VMBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
}
}
| mit | C# | |
b76d4f955bb55a8da29106a31471e3744006cfd8 | Change console URL for 1 code sample | teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets | lookups/lookup-get-basic-example-1/lookup-get-basic-example-1.cs | lookups/lookup-get-basic-example-1/lookup-get-basic-example-1.cs | // Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio.Lookups;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/console
const string accountSid = "{{ account_sid }}";
const string authToken = "{{ auth_token }}";
var lookupsClient = new LookupsClient(accountSid, authToken);
// Look up a phone number in E.164 format
var phoneNumber = lookupsClient.GetPhoneNumber("+15108675309", true);
Console.WriteLine(phoneNumber.Carrier.Type);
Console.WriteLine(phoneNumber.Carrier.Name);
}
} | // Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio.Lookups;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "{{ account_sid }}";
const string authToken = "{{ auth_token }}";
var lookupsClient = new LookupsClient(accountSid, authToken);
// Look up a phone number in E.164 format
var phoneNumber = lookupsClient.GetPhoneNumber("+15108675309", true);
Console.WriteLine(phoneNumber.Carrier.Type);
Console.WriteLine(phoneNumber.Carrier.Name);
}
} | mit | C# |
32fb8085fde0628907d8765d5f3c961dbf1c8043 | Create GroupIdToGroupConverter.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D/Converters/GroupIdToGroupConverter.cs | src/Draw2D/Converters/GroupIdToGroupConverter.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using Draw2D.ViewModels.Containers;
namespace Draw2D.Converters
{
public class GroupIdToGroupConverter : IMultiValueConverter
{
public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture)
{
if (values?.Count == 2 && values[0] is string groupId && values[1] is IGroupLibrary groupLibrary)
{
return groupLibrary.Get(groupId);
}
return AvaloniaProperty.UnsetValue;
}
}
}
| mit | C# | |
17fc74cf8c620cf4745b03d5f4cea0592c194803 | Create SolutionAssemblyInfo.cs | csuffyy/Orc.FilterBuilder | src/SolutionAssemblyInfo.cs | src/SolutionAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# | |
c621ae324a980c6b85b0373ffa685752282f5a18 | Add files via upload | AlexWan/OsEngine | project/OsEngine/bin/Debug/Custom/Indicators/Scripts/Volume.cs | project/OsEngine/bin/Debug/Custom/Indicators/Scripts/Volume.cs | using System.Collections.Generic;
using System.Drawing;
using OsEngine.Entity;
using OsEngine.Indicators;
namespace CustomIndicators.Scripts
{
public class Volume : Aindicator
{
private IndicatorDataSeries _series;
public override void OnStateChange(IndicatorState state)
{
if (state == IndicatorState.Configure)
{
_series = CreateSeries("Volume", Color.DodgerBlue, IndicatorChartPaintType.Column, true);
}
else if (state == IndicatorState.Dispose)
{
_series = null;
}
}
public override void OnProcess(List<Candle> candles, int index)
{
_series.Values[index] = candles[index].Volume;
}
}
} | apache-2.0 | C# | |
27562c6ff9a4751fcc5cabfdef41eb0fea21dcd0 | Create Problem32.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem32.cs | Problems/Problem32.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler.Problems
{
class Problem32
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
private int NumberInArray(int start, int end)
{
int result = 0;
for (int i = start; i <= end; i++)
{
result += numbers[i] * (int) Math.Pow(10, (end - i));
}
return result;
}
public string Run()
{
List<int> res = new List<int>();
List<int[]> resFull = new List<int[]>();
do
{
for (int i = 0; i < (numbers.Length*2/3) +1; i++)
{
for (int j = i + 1; j <= (numbers.Length*2/3) +1; j++)
{
int a = NumberInArray(0, i);
int b = NumberInArray(i+1, j);
int c = NumberInArray(j+1, numbers.Length - 1);
if (a * b == c)
{
if (!res.Contains(c))
{
res.Add(c);
}
resFull.Add(new int[] {a, b, c});
}
}
}
}
while (Permutation.NextPermutation(numbers));
int sum = 0;
foreach (int r in res)
{
sum += r;
}
return sum.ToString() ;
}
}
}
| mit | C# | |
037de866fbf20cfca954912e2fe1a823c9affeb7 | Create Palindrome.cs | michaeljwebb/Algorithm-Practice | Other/Palindrome.cs | Other/Palindrome.cs | //Check to see if given string is a palindrome. Return true or false.
//Not completed
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
string testString = "racecar";
Palindrome(testString);
}
public static string Palindrome(string s){
Dictionary<int,int> _pCount = new Dictionary<int,int>();
int isOdd = 0;
char[] cArray = s.ToCharArray();
for(int i = 0; i < cArray.Length; i++){
if(!_pCount.ContainsKey(cArray[i])){
_pCount.Add(cArray[i], 1);
}
else{
int tempCount = _pCount[cArray[i]];
tempCount++;
if(tempCount % 1 == 0){
isOdd++;
}
if(isOdd > 1){
Console.WriteLine(isOdd + " false");
}
else if(isOdd <= 1){
Console.WriteLine(isOdd + " true");
}
}
}
return isOdd.ToString();
}
}
| mit | C# | |
bd356e8c3ddfc99c4079226f9aba656c183a73b5 | fix HostIdFixer for v5 | eclaus/docs.particular.net,pashute/docs.particular.net,pedroreys/docs.particular.net,WojcikMike/docs.particular.net,yuxuac/docs.particular.net | Snippets/Snippets_5/HostIdentifier/HostIdFixer.cs | Snippets/Snippets_5/HostIdentifier/HostIdFixer.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using NServiceBus;
using NServiceBus.Config;
using NServiceBus.Hosting;
using NServiceBus.Settings;
using NServiceBus.Unicast;
#pragma warning disable 618
#region HostIdFixer
public class HostIdFixer : IWantToRunWhenConfigurationIsComplete
{
public HostIdFixer(UnicastBus bus, ReadOnlySettings settings)
{
Guid hostId = CreateGuid(Environment.MachineName, settings.EndpointName());
string location = Assembly.GetExecutingAssembly().Location;
Dictionary<string, string> properties = new Dictionary<string, string>
{
{"Location",location}
};
bus.HostInformation = new HostInformation(hostId, Environment.MachineName, properties);
}
static Guid CreateGuid(params string[] data)
{
using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
{
byte[] inputBytes = Encoding.Default.GetBytes(String.Concat(data));
byte[] hashBytes = provider.ComputeHash(inputBytes);
return new Guid(hashBytes);
}
}
public void Run(Configure config)
{
}
}
#endregion
| using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using NServiceBus;
using NServiceBus.Hosting;
using NServiceBus.Settings;
using NServiceBus.Unicast;
#pragma warning disable 618
#region HostIdFixer
public class HostIdFixer : IWantToRunWhenBusStartsAndStops
{
UnicastBus bus;
ReadOnlySettings settings;
public HostIdFixer(UnicastBus bus, ReadOnlySettings settings)
{
this.bus = bus;
this.settings = settings;
}
public void Start()
{
Guid hostId = CreateGuid(Environment.MachineName, settings.EndpointName());
string location = Assembly.GetExecutingAssembly().Location;
Dictionary<string, string> properties = new Dictionary<string, string>
{
{"Location",location}
};
bus.HostInformation = new HostInformation(hostId, Environment.MachineName, properties);
}
static Guid CreateGuid(params string[] data)
{
using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
{
byte[] inputBytes = Encoding.Default.GetBytes(String.Concat(data));
byte[] hashBytes = provider.ComputeHash(inputBytes);
return new Guid(hashBytes);
}
}
public void Stop()
{
}
}
#endregion
| apache-2.0 | C# |
98aa0bc6b0127530624e99f3530ad06afd0c20c6 | Create ComputationAssembly.cs | HelloKitty/DistributedComputationEngine | TerminalClient/Compilation/ComputationAssembly.cs | TerminalClient/Compilation/ComputationAssembly.cs | //
| mit | C# | |
30e07ddf6f4ffb80a608ed817b35b611ddcc8a77 | Disable threading on test | cetusfinance/qwack,cetusfinance/qwack,cetusfinance/qwack,cetusfinance/qwack | PnLAttributionFacts.cs | PnLAttributionFacts.cs | using System;
using System.Collections.Generic;
using System.Text;
using Qwack.Core.Instruments;
using Qwack.Core.Instruments.Funding;
using Qwack.Core.Models;
using Xunit;
using Qwack.Models.Tests;
using Qwack.Core.Curves;
using Qwack.Core.Basic;
using Qwack.Dates;
using System.Linq;
using Qwack.Models.Models;
namespace Qwack.Models.Tests.PnLAttribution
{
public class PnLAttributionFacts
{
private (IAssetFxModel startModel, IAssetFxModel endModel, Portfolio portfolio) GenerateTestData()
{
Utils.Parallel.ParallelUtils.Instance.MultiThreaded = false;
var usd = TestProviderHelper.CurrencyProvider.GetCurrency("USD");
var zar = TestProviderHelper.CurrencyProvider.GetCurrency("ZAR");
var nyc = TestProviderHelper.CalendarProvider.Collection["NYC"];
var originDate = DateTime.Parse("2019-04-25");
var ins = new FxForward
{
TradeId = "TestA",
DeliveryDate = originDate.AddDays(30),
DomesticCCY = zar,
ForeignCCY = usd,
DomesticQuantity = 1e6,
Strike = 14,
ForeignDiscountCurve = "DISCO-USD"
};
var pf = new Portfolio { Instruments = new List<IInstrument> { ins } };
var discoUsd = new FlatIrCurve(0.02, usd, "DISCO-USD");
var discoZar = new FlatIrCurve(0.05, zar, "DISCO-ZAR");
var fxpairs = new List<FxPair>
{
new FxPair {Domestic = usd, Foreign =zar,SettlementCalendar=nyc,SpotLag=2.Bd() },
new FxPair {Domestic = zar, Foreign =usd,SettlementCalendar=nyc,SpotLag=2.Bd() },
};
var fxMatrix = new FxMatrix(TestProviderHelper.CurrencyProvider);
fxMatrix.Init(zar, originDate, new Dictionary<Currency, double> { { usd, 14.0 } }, fxpairs, new Dictionary<Currency, string> { { usd, "DISCO-USD" }, { zar, "DISCO-ZAR" } });
var fModel = new FundingModel(originDate, new[] { discoUsd, discoZar }, TestProviderHelper.CurrencyProvider, TestProviderHelper.CalendarProvider);
fModel.SetupFx(fxMatrix);
var startModel = new AssetFxModel(originDate, fModel);
var endFModel = fModel.DeepClone();
endFModel.FxMatrix.SpotRates[usd] = 15;
var endModel = startModel.Clone(endFModel);
return (startModel, endModel, pf);
}
[Fact]
public void BasicPnLAttributionFacts()
{
var (startModel, endModel, portfolio) = GenerateTestData();
var zar = TestProviderHelper.CurrencyProvider.GetCurrency("ZAR");
var result = Models.PnLAttribution.BasicAttribution(portfolio, startModel, endModel, zar, TestProviderHelper.CurrencyProvider);
var sum = result.GetAllRows().Sum(x => x.Value);
var expected = portfolio.PV(endModel, zar).GetAllRows().Sum(x => x.Value)
- portfolio.PV(startModel, zar).GetAllRows().Sum(x => x.Value);
Assert.Equal(expected, sum, 10);
}
[Fact]
public void ExplainPnLAttributionFacts()
{
var (startModel, endModel, portfolio) = GenerateTestData();
var zar = TestProviderHelper.CurrencyProvider.GetCurrency("ZAR");
var result = Models.PnLAttribution.ExplainAttributionInLineGreeks(portfolio, startModel, endModel, zar, TestProviderHelper.CurrencyProvider);
var sum = result.GetAllRows().Sum(x => x.Value);
var expected = portfolio.PV(endModel, zar).GetAllRows().Sum(x => x.Value)
- portfolio.PV(startModel, zar).GetAllRows().Sum(x => x.Value);
Assert.Equal(expected, sum, 10);
}
}
}
| mit | C# | |
d6eac9c730cd88fc912c2b6943212e1b97d5bc85 | Create Problem125.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem125.cs | Problems/Problem125.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler.Problems
{
class Problem125
{
private bool Palindrome(int number)
{
bool is_palindrome = true;
string numberStr = number.ToString();
for (int i = 0; i < numberStr.Length / 2; i++)
{
is_palindrome &= numberStr[i] == numberStr[numberStr.Length - 1 - i];
if (!is_palindrome)
{
break;
}
}
return is_palindrome;
}
private bool SumOfSquares(int number)
{
var upper = Math.Sqrt(number);
for (int i = (int) upper; i > 1; i--)
{
int sum = i * i;
int j = i;
do
{
j--;
sum += (j * j);
if (sum == number)
{
return true;
}
else if (sum > number)
{
break;
}
}
while (j >= 1);
}
return false;
// 100K @ 40ms
}
public void Run()
{
DateTime start = DateTime.Now;
int count = 0;
long sum = 0;
for (int n = 2; n < 100000000; n++)
{
if(Palindrome(n)) {
if (SumOfSquares(n))
{
count++;
sum += n;
}
}
}
Console.WriteLine(count);
Console.WriteLine(sum);
Console.Write((DateTime.Now - start).TotalMilliseconds);
Console.WriteLine(" ms");
Console.ReadLine();
}
}
}
| mit | C# | |
93a7c123405e801bf2096518763185bb3c7c01d8 | Add order item delete support | peasy/Samples,peasy/Samples,peasy/Samples | Orders.com.Web.MVC/Views/OrderItems/Delete.cshtml | Orders.com.Web.MVC/Views/OrderItems/Delete.cshtml | @model Orders.com.Web.MVC.ViewModels.OrderItemViewModel
@{
ViewBag.Title = "Delete";
}
<h2>Delete Item</h2>
<h3>Are you sure you want to delete this?</h3>
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-1">Category</label>
<div class="col-md-10">
@Html.DisplayFor(model => model.AssociatedCategory.Name)
</div>
</div>
<div class="form-group">
<label class="control-label col-md-1">Product</label>
<div class="col-md-10">
@Html.DisplayFor(model => model.AssociatedProduct.Name)
</div>
</div>
<div class="form-group">
<label class="control-label col-md-1">Price</label>
<div class="col-md-10">
@Html.DisplayFor(model => model.Price)
</div>
</div>
<div class="form-group">
<label class="control-label col-md-1">Quantity</label>
<div class="col-md-10">
@Html.DisplayFor(model => model.Quantity)
</div>
</div>
<div class="form-group">
<label class="control-label col-md-1">Amount</label>
<div class="col-md-10">
@Html.DisplayFor(model => model.Amount)
</div>
</div>
<div class="form-group">
<label class="control-label col-md-1">Status</label>
<div class="col-md-10">
@Html.DisplayFor(model => model.Status)
</div>
</div>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Edit", "Orders", new { id = Model.OrderID }, null)
</div>
}
</div>
| mit | C# | |
4315a433712aef6904d206db7a5f8df253264c39 | Add Server-Timing generation in | MiniProfiler/dotnet,MiniProfiler/dotnet | src/MiniProfiler.Shared/MiniProfiler.ServerTiming.cs | src/MiniProfiler.Shared/MiniProfiler.ServerTiming.cs | using System.Collections.Generic;
using System.Text;
namespace StackExchange.Profiling
{
public partial class MiniProfiler
{
/// <summary>
/// Gets the Server-Timing header for this profiler, summarizing where time was spent for the browser.
/// Example output: sql=0.009; "sql", redis=0.005; "redis", aspnet=0.020; "ASP.NET"
/// </summary>
/// <returns>A string, the value to put in a Server-Timing header.</returns>
public string GetServerTimingHeader()
{
var total = DurationMilliseconds;
var summary = new Dictionary<string, decimal>();
foreach (var t in GetTimingHierarchy())
{
if (t.CustomTimings == null)
{
continue;
}
foreach (var ct in t.CustomTimings)
{
if (ct.Value?.Count > 0)
{
decimal ctTotal = 0;
for (var i = 0; i < ct.Value.Count; i++)
{
ctTotal += ct.Value[i]?.DurationMilliseconds ?? 0;
}
summary[ct.Key] = (summary.TryGetValue(ct.Key, out decimal cur) ? cur : 0) + ctTotal;
}
}
}
var sb = new StringBuilder();
foreach (var category in summary)
{
sb.Append(category.Key).Append('=').Append(category.Value / 1000)
.Append("; \"").Append(category.Key).Append("\",");
total -= category.Value;
}
sb.Append("aspnet=").Append(total <= 0 ? 0 : total / 1000).Append("; \"ASP.NET\"");
// Server-Timing: sql=0.009; "sql", redis=0.005; "redis", aspnet=0.020; "ASP.NET"
return sb.ToString();
}
}
}
| mit | C# | |
534300d3c22cf5cbf52cf048edd42151224a5f5b | Create IProtocol.cs | poostwoud/discovery | src/Library/Protocol/IProtocol.cs | src/Library/Protocol/IProtocol.cs | using System;
using System.Xml;
namespace Discovery.Library.Protocol
{
public interface IProtocol
{
void Append();
void Partial();
IProtocolResponse Read(Uri uri, string userName = "", string password = "");
void Remove();
void Replace();
}
}
| mit | C# | |
12fb472141a22e89129a448f7d73cd21b1e92d68 | Create Class1.cs | rus100/gomoku | Class1.cs | Class1.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace gomoku
{
class Class1
{
static public bool pc;
static public bool znak;
static public int time;
static public int kolvohod;
static public string imya;
static public bool time1;
static public bool kolvohod1;
}
}
| unlicense | C# | |
9d87c69a71c110d7a1522933dcc70921edd6c0c6 | Add missing file | christophwille/wpaghapp | Source/WpaGhApp/Views/Main/OrgsListView.xaml.cs | Source/WpaGhApp/Views/Main/OrgsListView.xaml.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace WpaGhApp.Views.Main
{
public sealed partial class OrgsListView : UserControl
{
public OrgsListView()
{
this.InitializeComponent();
}
}
}
| mit | C# | |
aaeaceea734caae77baca156126152b7e53eda90 | Create a class that acts as a configuration node for cache providers | nohros/must,nohros/must,nohros/must | src/base/common/configuration/common/provider/CacheProviderNode.cs | src/base/common/configuration/common/provider/CacheProviderNode.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Configuration;
using Nohros.Resources;
namespace Nohros.Configuration
{
/// <summary>
/// Contains configuration informations for cache providers.
/// </summary>
public class CacheProviderNode : ProviderNode
{
/// <summary>
/// Initializes a new instance of the <see cref="CacheProviderNode"/> class by using the specified
/// provider name and type.
/// </summary>
/// <param name="name">The name of the provider.</param>
/// <param name="type">The assembly-qualified name of the provider type.</param>
public CacheProviderNode(string name, string type) : base(name, type) { }
/// <summary>
/// Parses a XML node that contains information about the provider.
/// </summary>
/// <param name="node">The XML node to parse.</param>
/// <param name="config">A <see cref="NohrosConfiguration"/> object containing the provider configuration
/// informations.</param>
/// <exception cref="System.Configuration.ConfigurationErrorsException">The <paramref name="node"/> is not a
/// valid representation of a messenger provider.</exception>
public override void Parse(XmlNode node, NohrosConfiguration config) {
InternalParse(node, config);
}
}
}
| mit | C# | |
c09f59128ec199697980181b33c06e55a05910f8 | Create Problem206.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problem206.cs | Problem206.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace ProjectEuler.Problems
{
class Problem206
{
// Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,
// where each “_” is a single digit.
BigInteger lowerSq = 1020304050607080900;
BigInteger upperSq = 1929394959697989990;
private bool Match(ulong val)
{
val = val * val;
string valS = val.ToString();
if (valS.Length != 19)
{
return false;
}
return valS[0] == '1'
&& valS[2] == '2'
&& valS[4] == '3'
&& valS[6] == '4'
&& valS[8] == '5'
&& valS[10] == '6'
&& valS[12] == '7'
&& valS[14] == '8'
&& valS[16] == '9'
&& valS[18] == '0';
}
public void Run() {
ulong lower = 1010101010;
ulong upper = 1389026624;
for (ulong i = lower; i < upper; i++)
{
if (Match(i))
{
Console.WriteLine(i);
return;
}
}
Console.WriteLine("Not found");
}
}
}
| mit | C# | |
781bdce0eb3ce884817725f2b6d7082a80c32e64 | Add IServiceManifest | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Mvc/IServiceManifest.cs | src/Microsoft.AspNet.Mvc/IServiceManifest.cs | // Copyright (c) Microsoft Open Technologies, Inc. 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.Collections.Generic;
namespace Microsoft.Framework.DependencyInjection.ServiceLookup
{
#if ASPNET50 || ASPNETCORE50
[Microsoft.Framework.Runtime.AssemblyNeutral]
#endif
public interface IServiceManifest
{
IEnumerable<Type> Services { get; }
}
}
| apache-2.0 | C# | |
7644344d0f7d87a842a1721d5d49f008e4da1153 | add SnowflakeId unit tests | ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP | test/DotNetCore.CAP.Test/SnowflakeIdTest.cs | test/DotNetCore.CAP.Test/SnowflakeIdTest.cs | using System.Linq;
using System.Threading.Tasks;
using DotNetCore.CAP.Infrastructure;
using Xunit;
namespace DotNetCore.CAP.Test
{
public class SnowflakeIdTest
{
[Fact]
public void NextIdTest()
{
var result = SnowflakeId.Default().NextId();
Assert.IsType<long>(result);
Assert.True(result > 0);
Assert.True(result.ToString().Length == long.MaxValue.ToString().Length);
}
[Fact]
public void ConcurrentNextIdTest()
{
var array = new long[1000];
Parallel.For(0, 1000, i =>
{
var id = SnowflakeId.Default().NextId();
array[i] = id;
});
Assert.True(array.Distinct().Count() == 1000);
}
}
}
| mit | C# | |
f0317d0ef0ff732288cc4ceff378e6a81066bc28 | add a mixed memory/persisted storage context | ArsenShnurkov/BitSharp | BitSharp.Storage.Esent/MixedStorageContext.cs | BitSharp.Storage.Esent/MixedStorageContext.cs | using BitSharp.Common;
using BitSharp.Common.ExtensionMethods;
using BitSharp.Data;
using BitSharp.Storage.Esent;
using Microsoft.Isam.Esent.Collections.Generic;
using Microsoft.Isam.Esent.Interop;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BitSharp.Storage.Esent
{
public class MixedStorageContext : IStorageContext
{
private readonly EsentStorageContext esentStorageContext;
private readonly MemoryStorageContext memoryStorageContext;
private readonly BlockHeaderStorage _blockHeaderStorage;
private readonly ChainedBlockStorage _chainedBlockStorage;
private readonly MemoryStorage<UInt256, IImmutableList<UInt256>> _blockTxHashesStorage;
private readonly MemoryStorage<UInt256, BitSharp.Data.Transaction> _transactionStorage;
private readonly BlockRollbackStorage _blockRollbackStorage;
private readonly InvalidBlockStorage _invalidBlockStorage;
public MixedStorageContext(string baseDirectory, long cacheSizeMaxBytes)
{
this.esentStorageContext = new EsentStorageContext(baseDirectory, cacheSizeMaxBytes);
this.memoryStorageContext = new MemoryStorageContext();
this._blockHeaderStorage = this.esentStorageContext.BlockHeaderStorage;
this._chainedBlockStorage = this.esentStorageContext.ChainedBlockStorage;
this._blockTxHashesStorage = this.memoryStorageContext.BlockTxHashesStorage;
this._transactionStorage = this.memoryStorageContext.TransactionStorage;
this._blockRollbackStorage = this.esentStorageContext.BlockRollbackStorage;
this._invalidBlockStorage = this.esentStorageContext.InvalidBlockStorage;
}
public BlockHeaderStorage BlockHeaderStorage { get { return this._blockHeaderStorage; } }
public ChainedBlockStorage ChainedBlockStorage { get { return this._chainedBlockStorage; } }
public MemoryStorage<UInt256, IImmutableList<UInt256>> BlockTxHashesStorage { get { return this._blockTxHashesStorage; } }
public MemoryStorage<UInt256, BitSharp.Data.Transaction> Transactionstorage { get { return this._transactionStorage; } }
public BlockRollbackStorage BlockRollbackStorage { get { return this._blockRollbackStorage; } }
public IBoundedStorage<UInt256, string> InvalidBlockStorage { get { return this._invalidBlockStorage; } }
internal string BaseDirectory { get { return this.esentStorageContext.BaseDirectory; } }
IBoundedStorage<UInt256, BlockHeader> IStorageContext.BlockHeaderStorage { get { return this._blockHeaderStorage; } }
IBoundedStorage<UInt256, ChainedBlock> IStorageContext.ChainedBlockStorage { get { return this._chainedBlockStorage; } }
IBoundedStorage<UInt256, IImmutableList<UInt256>> IStorageContext.BlockTxHashesStorage { get { return this._blockTxHashesStorage; } }
IUnboundedStorage<UInt256, BitSharp.Data.Transaction> IStorageContext.TransactionStorage { get { return this._transactionStorage; } }
IBoundedStorage<UInt256, IImmutableList<KeyValuePair<UInt256, UInt256>>> IStorageContext.BlockRollbackStorage { get { return this._blockRollbackStorage; } }
IBoundedStorage<UInt256, string> IStorageContext.InvalidBlockStorage { get { return this._invalidBlockStorage; } }
//public IEnumerable<ChainedBlock> SelectMaxTotalWorkBlocks()
//{
// return this.ChainedBlockStorage.SelectMaxTotalWorkBlocks();
//}
public IUtxoBuilderStorage ToUtxoBuilder(IUtxoStorage utxo)
{
//return new MemoryUtxoBuilderStorage(utxo);
return new UtxoBuilderStorage(utxo);
}
public void Dispose()
{
new IDisposable[]
{
this.esentStorageContext
}.DisposeList();
}
}
}
| unlicense | C# | |
eb20c4d0ef4da3bcc84140f820dc4b8fb8263f38 | add debug | PFC-acl-amg/GamaPFC,PFC-acl-amg/GamaPFC,PFC-acl-amg/GamaPFC | GamaPFC/Gama.Common/Debug/Debug.cs | GamaPFC/Gama.Common/Debug/Debug.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gama.Common.Debug
{
public static class Debug
{
public static bool DEBUG = true;
private static System.Diagnostics.Stopwatch _Stopwatch;
public static void StartStopWatch()
{
if (DEBUG)
_Stopwatch = System.Diagnostics.Stopwatch.StartNew();
}
public static void StopWatch(string source)
{
if (DEBUG)
{
_Stopwatch.Stop();
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Console.WriteLine($">>>>>>>>>>>>>>{source}: {_Stopwatch.ElapsedMilliseconds / 1000.0} segundos");
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
}
}
}
}
| mit | C# | |
bbd7d7b4284eb282eb35621c50845883fcea8181 | Add JObjectExtensions | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Utilities/JObjectExtensions.cs | source/Nuke.Common/Utilities/JObjectExtensions.cs | // Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Newtonsoft.Json.Linq;
namespace Nuke.Common.Utilities
{
public static class JsonExtensions
{
[CanBeNull]
public static T GetPropertyValueOrNull<T>(this JObject jobject, string name)
{
var property = jobject.Property(name);
return property != null
? property.Value.Value<T>()
: default;
}
public static T GetPropertyValue<T>(this JObject jobject, string name)
{
return jobject.GetPropertyValueOrNull<T>(name).NotNull(name);
}
public static JObject GetPropertyValue(this JObject jobject, string name)
{
return jobject.GetPropertyValue<JObject>(name);
}
public static string GetPropertyStringValue(this JObject jobject, string name)
{
return jobject.GetPropertyValue<string>(name);
}
public static JEnumerable<T> GetChildren<T>(this JObject jobject, string name)
where T : JToken
{
return jobject.GetPropertyValue<JArray>(name).Children<T>();
}
public static JEnumerable<JObject> GetChildren(this JObject jobject, string name)
{
return jobject.GetChildren<JObject>(name);
}
}
}
| mit | C# | |
b37e075fec5ecc9186e60df6f0384b73b91ffb4d | Add missing file. | SergeyTeplyakov/ErrorProne.NET | src/ErrorProne.NET/ErrorProne.NET.Test/OtherRules/ReadOnlyAttributeAnalyzerTests.cs | src/ErrorProne.NET/ErrorProne.NET.Test/OtherRules/ReadOnlyAttributeAnalyzerTests.cs | using System.Collections.Generic;
using ErrorProne.NET.Common;
using ErrorProne.NET.Rules.OtherRules;
using NUnit.Framework;
using RoslynNunitTestRunner;
namespace ErrorProne.NET.Test.OtherRules
{
[TestFixture]
public class ReadOnlyAttributeAnalyzerTests : CSharpAnalyzerTestFixture<ReadOnlyAttributeAnalyzer>
{
[TestCaseSource(nameof(ShouldWarnIfInvalidTestCases))]
public void ShouldWarnIfInvalid(string code)
{
HasDiagnostic(code, RuleIds.ReadonlyAttributeNotOnCustomStructs);
}
public static IEnumerable<string> ShouldWarnIfInvalidTestCases()
{
// Can't use attribute on primitives
yield return @"
class Foo
{
[ErrorProne.NET.Annotations.ReadOnlyAttribute]
public int [|_m|];
}";
// Can't use attribute on nullable primitives
yield return @"
class Foo
{
[ErrorProne.NET.Annotations.ReadOnlyAttribute]
public int? [|_m|];
}";
// Can't use attribute on reference types
yield return @"
class Foo
{
[ErrorProne.NET.Annotations.ReadOnlyAttribute]
public string [|_m|];
}";
// Can't use attribute on enums
yield return @"
enum CustomEnum {}
class Foo
{
[ErrorProne.NET.Annotations.ReadOnlyAttribute]
public CustomEnum [|_m|];
}";
// Can't use with readonly attribute
yield return @"
struct CustomStruct {}
class Foo
{
[ErrorProne.NET.Annotations.ReadOnlyAttribute]
public readonly CustomStruct [|_m|];
}";
}
[TestCaseSource(nameof(ShouldNotWarnTestCases))]
public void ShouldNotWarnIfValid(string code)
{
NoDiagnostic(code, RuleIds.ReadonlyAttributeNotOnCustomStructs);
}
public static IEnumerable<string> ShouldNotWarnTestCases()
{
// Can't use attribute on enums
yield return @"
struct CustomStruct {}
class Foo
{
[ErrorProne.NET.Annotations.ReadOnlyAttribute]
public CustomStruct _m;
}";
}
}
} | mit | C# | |
0f68bbd23c79a2c0c324db901a19f2653fd993ea | Add Isle of Man | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date/PublicHolidays/IsleOfManProvider.cs | Src/Nager.Date/PublicHolidays/IsleOfManProvider.cs | using Nager.Date.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class IsleOfManProvider : CatholicBaseProvider
{
public override IEnumerable<PublicHoliday> Get(int year)
{
//Isle of Man
//https://en.wikipedia.org/wiki/Public_holidays_in_the_Isle_of_Man
var countryCode = CountryCode.IM;
var easterSunday = base.EasterSunday(year);
var firstMondayInMay = DateSystem.FindDay(year, 5, DayOfWeek.Monday, 1);
var lastMondayInMay = DateSystem.FindLastDay(year, 5, DayOfWeek.Monday);
var secondFridayInJune = DateSystem.FindDay(year, 6, DayOfWeek.Friday, 2);
var lastMondayInAugust = DateSystem.FindLastDay(year, 8, DayOfWeek.Monday);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "New Year's Day", "New Year's Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Good Friday", "Good Friday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(1), "Easter Monday", "Easter Monday", countryCode));
items.Add(new PublicHoliday(firstMondayInMay, "Labour Day", "Labour Day", countryCode));
items.Add(new PublicHoliday(lastMondayInMay, "Spring Bank Holiday", "Spring Bank Holiday", countryCode));
items.Add(new PublicHoliday(secondFridayInJune, "Senior Race Day", "Senior Race Day", countryCode));
items.Add(new PublicHoliday(year, 7, 5, "Tynwald Day", "Tynwald Day", countryCode));
items.Add(new PublicHoliday(lastMondayInAugust, "Late Summer Bank Holiday", "Late Summer Bank Holiday", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "Christmas Day", "Christmas Day", countryCode));
items.Add(new PublicHoliday(year, 12, 26, "Boxing Day", "St. Stephen's Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| mit | C# | |
551f5cd5417b1147edca0bf3417974c14b275c4f | add NamespaceList.cs | KennyCtrip/venus | Source/Venus/Utility/NamespaceList.cs | Source/Venus/Utility/NamespaceList.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Venus.Utility
{
internal class NamespaceList
{
private Dictionary<string, NamespaceList> index = new Dictionary<string, NamespaceList>();
private int level;
private NamespaceList(int level)
{
this.level = level;
}
public static NamespaceList Create()
{
return new NamespaceList(1);
}
public int Count
{
get
{
return index.Count;
}
}
public void Add(string[] ns)
{
if (ns == null)
throw new ArgumentNullException("ns");
if (ns.Length >= level)
{
var key = ns[level - 1].Trim();
if (!index.ContainsKey(key))
{
if (ns.Length == level)
{
index.Add(key, null);
}
else
{
var list = new NamespaceList(level + 1);
list.Add(ns);
index.Add(key, list);
}
}
}
}
public bool Include(string[] ns)
{
if (ns == null)
throw new ArgumentNullException("ns");
if (ns.Length >= level)
{
var key = ns[level - 1].Trim();
if (index.ContainsKey(key))
{
var list = index[key];
if (list == null)
return true;
return list.Include(ns);
}
}
return false;
}
}
}
| apache-2.0 | C# | |
ee0b8df19e543e987281b689f6ec383e08f19b7b | Create OpeningMicrosoftExcel97-2003Files.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Files/Handling/OpeningMicrosoftExcel97-2003Files.cs | Examples/CSharp/Files/Handling/OpeningMicrosoftExcel97-2003Files.cs | using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Files.Handling
{
public class OpeningMicrosoftExcel97-2003Files
{
public static void Main(string[] args)
{
//Exstart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Get the Excel file into stream
FileStream stream = new FileStream(dataDir + "Book_Excel97_2003.xls", FileMode.Open);
//Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions1 = new LoadOptions(LoadFormat.Excel97To2003);
//Create a Workbook object and opening the file from the stream
Workbook wbExcel97 = new Workbook(stream, loadOptions1);
Console.WriteLine("Microsoft Excel 97 - 2003 workbook opened successfully!");
}
}
}
| mit | C# | |
5fa85f0eccd73f551d8c04c549c4523029490889 | Switch request tab over to use fluent api | codevlabs/Glimpse,dudzon/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,flcdrg/Glimpse,flcdrg/Glimpse,sorenhl/Glimpse,SusanaL/Glimpse,gabrielweyer/Glimpse,elkingtonmcb/Glimpse,dudzon/Glimpse,Glimpse/Glimpse,sorenhl/Glimpse,flcdrg/Glimpse,paynecrl97/Glimpse,codevlabs/Glimpse,elkingtonmcb/Glimpse,rho24/Glimpse,rho24/Glimpse,Glimpse/Glimpse,gabrielweyer/Glimpse,dudzon/Glimpse,paynecrl97/Glimpse,elkingtonmcb/Glimpse,SusanaL/Glimpse,paynecrl97/Glimpse,SusanaL/Glimpse,codevlabs/Glimpse,rho24/Glimpse,Glimpse/Glimpse | source/Glimpse.AspNet/SerializationConverter/RequestModelConverter.cs | source/Glimpse.AspNet/SerializationConverter/RequestModelConverter.cs | using System.Collections.Generic;
using Glimpse.AspNet.Extensions;
using Glimpse.AspNet.Model;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Plugin.Assist;
namespace Glimpse.AspNet.SerializationConverter
{
public class RequestModelConverter : SerializationConverter<RequestModel>
{
public override object Convert(RequestModel request)
{
var root = new TabObject();
root.AddRow().Key("Cookies").Value(request.Cookies.ToTable());
root.AddRow().Key("Query String").Value(request.QueryString.ToTable());
root.AddRow().Key("Url").Value(request.Url.ToString());
root.AddRow().Key("Url Referrer").Value(request.UrlReferrer.OrNull());
root.AddRow().Key("App Relative Current Execution File Path").Value(request.AppRelativeCurrentExecutionFilePath);
root.AddRow().Key("Application Path").Value(request.ApplicationPath);
root.AddRow().Key("Current Execution File Path").Value(request.CurrentExecutionFilePath);
root.AddRow().Key("Current UI Culture").Value(request.CurrentUiCulture);
root.AddRow().Key("File Path").Value(request.FilePath);
root.AddRow().Key("Path").Value(request.Path);
root.AddRow().Key("Path Info").Value(request.PathInfo);
root.AddRow().Key("Physical Application Path").Value(request.PhysicalApplicationPath);
root.AddRow().Key("Physical Path").Value(request.PhysicalPath);
root.AddRow().Key("Raw Url").Value(request.RawUrl);
root.AddRow().Key("User Agent").Value(request.UserAgent);
root.AddRow().Key("User Host Address").Value(request.UserHostAddress);
root.AddRow().Key("User Host Name").Value(request.UserHostName);
return root.Build();
}
}
} | using System.Collections.Generic;
using Glimpse.AspNet.Extensions;
using Glimpse.AspNet.Model;
using Glimpse.Core.Extensibility;
namespace Glimpse.AspNet.SerializationConverter
{
public class RequestModelConverter : SerializationConverter<RequestModel>
{
public override object Convert(RequestModel request)
{
return new Dictionary<string, object>
{
// TODO: Leverage Kristoffer Ahl's fluent interface for transformation into a table and formatting
{ "Cookies", request.Cookies.ToTable() },
// TODO: Leverage Kristoffer Ahl's fluent interface for transformation into a table and formatting
{ "Query String", request.QueryString.ToTable() },
{ "Url", request.Url.ToString() },
{ "Url Referrer", request.UrlReferrer.OrNull() },
{ "App Relative Current Execution File Path", request.AppRelativeCurrentExecutionFilePath },
{ "Application Path", request.ApplicationPath },
{ "Current Execution File Path", request.CurrentExecutionFilePath },
{ "Current UI Culture", request.CurrentUiCulture },
{ "File Path", request.FilePath },
{ "Path", request.Path },
{ "Path Info", request.PathInfo },
{ "Physical Application Path", request.PhysicalApplicationPath },
{ "Physical Path", request.PhysicalPath },
{ "Raw Url", request.RawUrl },
{ "User Agent", request.UserAgent },
{ "User Host Address", request.UserHostAddress },
{ "User Host Name", request.UserHostName },
};
}
}
} | apache-2.0 | C# |
841b71ca13004634abd2d195e4f68ee80f243d34 | Document IHasLifetime | EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,Tom94/osu-framework,paparony03/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,default0/osu-framework,RedNesto/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,paparony03/osu-framework,naoey/osu-framework,default0/osu-framework,RedNesto/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,naoey/osu-framework,ppy/osu-framework | osu.Framework/Lists/IHasLifetime.cs | osu.Framework/Lists/IHasLifetime.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Timing;
namespace osu.Framework.Lists
{
public interface IHasLifetime
{
/// <summary>
/// Updates the current time to the provided time.
/// </summary>
void UpdateTime(FrameTimeInfo time);
/// <summary>
/// Whether this life-timed object is currently loaded.
/// </summary>
bool IsLoaded { get; }
/// <summary>
/// The beginning of this object's lifetime.
/// </summary>
double LifetimeStart { get; }
/// <summary>
/// The end of this object's lifetime.
/// </summary>
double LifetimeEnd { get; }
/// <summary>
/// Whether this life-timed object is currently alive. Alive-status depends on
/// <see cref="LifetimeStart"/>, <see cref="LifetimeEnd"/> and the current time.
/// </summary>
bool IsAlive { get; }
/// <summary>
/// Whether this life-timed object should be removed from a <see cref="LifetimeList{T}"/>
/// if <see cref="IsAlive"/> is false.
/// </summary>
bool RemoveWhenNotAlive { get; }
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Timing;
namespace osu.Framework.Lists
{
public interface IHasLifetime
{
double LifetimeStart { get; }
double LifetimeEnd { get; }
bool IsAlive { get; }
void UpdateTime(FrameTimeInfo time);
bool IsLoaded { get; }
bool RemoveWhenNotAlive { get; }
}
}
| mit | C# |
f0e719396b4113c29e7683fe8e1dd204b1e3c23b | Disable parallelization for OmniSharp.DotNet.Tests (increase stability) | DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn | tests/OmniSharp.DotNet.Tests/AssemblyInfo.cs | tests/OmniSharp.DotNet.Tests/AssemblyInfo.cs | [assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)] | mit | C# | |
b9450b149b2c2b3d83209a1ed5fbfb39c02e738a | Test for Live | icarus-consulting/Yaapii.Atoms | tests/Yaapii.Atoms.Tests/Scalar/LiveTests.cs | tests/Yaapii.Atoms.Tests/Scalar/LiveTests.cs | using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Yaapii.Atoms.Scalar.Tests
{
public sealed class LiveTests
{
[Fact]
public void ReloadsFunc()
{
var counts = 0;
var live = new Live<bool>(() =>
{
++counts;
return true;
});
live.Value();
live.Value();
Assert.Equal(2, counts);
}
}
}
| mit | C# | |
3b7469786e04f49480d337e55194a204aee6bfd0 | Add a more specific GenericListModel to reduce the amount of code | Xeeynamo/KingdomHearts | OpenKh.Tools.Common/Models/MyGenericListModel.cs | OpenKh.Tools.Common/Models/MyGenericListModel.cs | using System.Collections;
using System.Collections.Generic;
using Xe.Tools.Wpf.Models;
namespace OpenKh.Tools.Common.Models
{
public class MyGenericListModel<T> : GenericListModel<T>, IEnumerable<T>
{
public MyGenericListModel(IEnumerable<T> list) : base(list)
{
}
public IEnumerator<T> GetEnumerator() => Items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => Items.GetEnumerator();
protected override T OnNewItem() => throw new System.NotImplementedException();
}
}
| mit | C# | |
e7d7c0f2b5f83387f7ea3d4473cee623670fd3ef | Add build config info for ArtifactDependencies | borismod/FluentTc,GibbOne/FluentTc,QualiSystems/FluentTc | FluentTc/Domain/SourceBuildType.cs | FluentTc/Domain/SourceBuildType.cs | namespace FluentTc.Domain
{
public class SourceBuildType
{
public override string ToString()
{
return "source-buildType";
}
public string Id { get; set; }
public string Name { get; set; }
public string ProjectName { get; set; }
public string ProjectId { get; set; }
}
} | apache-2.0 | C# | |
a6db73a0d185fa9f221e54c785dcfc6e99544dc6 | Create Process.cs | webjug/vol | Process.cs | Process.cs | using System;
namespace Process
{
class MyClass()
{
}
}
| unlicense | C# | |
b13991c57ee41e04dd28a9e1fca98f00fd3d0d26 | Create scratch.cs | ariugwu/sharpbox,ariugwu/sharpbox,ariugwu/sharpbox,ariugwu/sharpbox | sharpbox.Io/scratch.cs | sharpbox.Io/scratch.cs | public class Client
{
/// <summary>
/// Used to read the contents of a file using the IFilters present on the machine.
/// </summary>
private TextReader _reader;
public Client() { }
#region CRUD
public Byte[] GetByFilename(string path)
{
return System.IO.File.ReadAllBytes(path);
}
public void Save(string path, Stream input)
{
using (Stream file = System.IO.File.Create(path))
{
CopyStream(input, file);
}
}
public void Delete(string path)
{
System.IO.File.Delete(path);
}
#endregion
#region Helper(s)
public String ReadFileContents(string path)
{
try
{
TextReader reader = new FilterReader(path);
using (reader)
{
var text = reader.ReadToEnd();
return text;
}
}
catch (Exception ex)
{
throw;
}
}
public string[] ReadFileLines(string path)
{
return System.IO.File.ReadAllLines(path);
}
/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
private void CopyStream(Stream input, Stream output)
{
var buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
/// <summary>
/// Not a perfect solution to the "Is File locked?" aka "Don't return me until the write operatin is finished"...but there is no perfect solution @SEE: http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use/937558#937558
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
#endregion
}
| mit | C# | |
6ecc40a99d9cc3152a8be6a278f795b0cc10a009 | Create DebugHUD.cs | slek120/Unity-Framerate-HUD | DebugHUD.cs | DebugHUD.cs | using UnityEngine;
using System.Collections;
public class DebugHUD : MonoBehaviour
{
public static DebugHUD debugHUD;
public bool debugOn = true;
public float updateInterval = 0.5f;
private int frames = 0;
private float duration = 0;
// Singleton
void Awake ()
{
if (debugHUD == null) {
DontDestroyOnLoad (gameObject);
debugHUD = this;
} else if (debugHUD != this) {
Destroy (gameObject);
}
if (!Debug.isDebugBuild)
debugOn = false;
if (guiText) {
guiText.fontSize = (int)(Screen.width * 0.05f);
if (debugOn)
StartCoroutine (UpdateFPS ());
else
guiText.enabled = false;
} else {
Debug.LogWarning ("Please attach GUIText component to game object");
}
}
void Update ()
{
++frames;
duration += Time.deltaTime;
}
// Display FPS data
IEnumerator UpdateFPS ()
{
float fps = 0;
string format;
// Cache reference to components
GUIText FPStext = guiText;
Material material = FPStext.material;
while (true) {
duration = 0;
frames = 0;
yield return new WaitForSeconds (updateInterval);
// Only do division once
duration = 1 / duration;
// Only update if FPS changes
if (fps - (frames * duration) < 0.01 && fps - (frames * duration) > -0.01) {
continue;
}
fps = frames * duration;
format = System.String.Format ("{0:F2} FPS", fps);
FPStext.text = format;
if (fps < 30)
material.color = Color.yellow;
else if (fps < 10)
material.color = Color.red;
else
material.color = Color.green;
}
}
}
| mit | C# | |
1057cf8bcd4e323e0394e65932887ddb15f83273 | Create AnomalousCancellation.cs | burnsba/scratch,burnsba/scratch,burnsba/scratch | Math/AnomalousCancellation.cs | Math/AnomalousCancellation.cs | // 2017-11-09
//
// This works more or less, but the defintion is ambiguous.
// Are uncancelled duplicates allowed?
// Limit this to only one digit, or more?
// This only considers a single digit that may occur more than once. That means
// - There is no way to consider multiple cancellations at the same time.
// For instance, can't cancel the 2 and 3 in xxx2xx3xx / x23xxxxxx at the same time
// - In the same way, two digit or more numbers can't be cancelled. For instance,
// can't cancel the 23 in x23 / 23x
// http://mathworld.wolfram.com/AnomalousCancellation.html
int min = 100;
int max = 1000;
int totalCount = 0;
for (int num = min; num <= max; num++)
{
for (int den = min; den < num; den++)
{
if (num == den)
{
continue;
}
var numDigits = num.ToString().Select(x => x.ToString());
var denDigits = den.ToString().Select(x => x.ToString());
var distinct = numDigits.Distinct();
foreach (var digit in distinct)
{
// If digit is zero
if (digit == "0")
{
continue;
}
// If there's nothing to cancel.
if (!denDigits.Contains(digit))
{
continue;
}
// If there are not equal number of the digit to cancel.
var numCancelCount = numDigits.Where(x => x == digit).Count();
var denCancelCount = denDigits.Where(x => x == digit).Count();
if (numCancelCount != denCancelCount /* || numCancelCount != 1*/)
{
continue;
}
//// If this is dividing by 10.
//if (digit == "0" && numDigits.Last() == "0" && denDigits.Last() == "0")
//{
// continue;
//}
//
var newNumComb = numDigits.Select((x,i) => Tuple.Create(x,i)).Where(x => x.Item1 != digit);
var newDenComb = denDigits.Select((x,i) => Tuple.Create(x,i)).Where(x => x.Item1 != digit);
var newNumDigits = newNumComb.Select(x => x.Item1);
var newDenDigits = newDenComb.Select(x => x.Item1);
var newNumIndeces = newNumComb.Select(x => x.Item2);
var newDenIndeces = newDenComb.Select(x => x.Item2);
// If the indeces for the cancelled digits are the same in the numerator and denominator.
//if (newNumIndeces.SequenceEqual(newDenIndeces))
//{
// continue;
//}
//var newNumDigits = numDigits.Where(x => x != digit);
//var newDenDigits = denDigits.Where(x => x != digit);
// If everything got cancelled in the numerator or denominator.
if (newNumDigits.Count() == 0 || newDenDigits.Count() == 0)
{
continue;
}
//// If there are still overlapping digits that have not been cancelled.
//if (newNumDigits.Intersect(newDenDigits).Any())
//{
// continue;
//}
var newNum = int.Parse(String.Join(String.Empty, newNumDigits));
var newDen = int.Parse(String.Join(String.Empty, newDenDigits));
// If it got simplified to zero.
if (newNum == 0 || newDen == 0)
{
continue;
}
var lhs = num * newDen;
var rhs = newNum * den;
if (lhs == rhs)
{
totalCount++;
Console.WriteLine($"Cancel {digit}: {num} / {den} == {newNum} / {newDen}");
}
}
}
}
Console.WriteLine($"TotalCount: {totalCount}");
| apache-2.0 | C# | |
7b54f10a2e83e3752f4a27ca709e1ca73075108a | Add Game view model | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/ChessVariantsTraining/ViewModels/Game.cs | src/ChessVariantsTraining/ViewModels/Game.cs | namespace ChessVariantsTraining.ViewModels
{
public class Game
{
public string White
{
get;
private set;
}
public string Black
{
get;
private set;
}
public string WhiteUrl
{
get;
private set;
}
public string BlackUrl
{
get;
private set;
}
public string Variant
{
get;
private set;
}
public string TimeControl
{
get;
private set;
}
public Game(string white, string black, string whiteUrl, string blackUrl, string variant, string timeControl)
{
White = white;
Black = black;
WhiteUrl = whiteUrl;
BlackUrl = blackUrl;
Variant = variant;
TimeControl = timeControl;
}
}
}
| agpl-3.0 | C# | |
095a2cb3452dc918960039c5934e68f2363a6981 | add build.cake build file | CiBuildOrg/WebApi-Boilerplate,CiBuildOrg/WebApi-Boilerplate,CiBuildOrg/WebApi-Boilerplate | build.cake | build.cake | #tool nuget:?package=NUnit.ConsoleRunner&version=3.6.0
#tool "nuget:?package=ReportUnit"
#tool "docfx.console"
#addin "Cake.DocFx"
#addin "SharpZipLib"
#addin "Cake.FileHelpers"
#addin "Cake.Compression"
#addin "MagicChunks"
//#addin "nuget:?package=Cake.StyleCop&version=1.1.3"
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument<string>("target", "Default");
var configuration = Argument<string>("configuration", "Release"); // by default will compile release
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var solutions = GetFiles("./**/*.sln");
var solutionFile = solutions.First();
var solutionPaths = solutions.Select(solution => solution.GetDirectory());
var testResultFolder = MakeAbsolute(Directory(Argument("testResultsPath", "./test-results")));
var buildResultFolder = MakeAbsolute(Directory(Argument("buildResultsPath","./build-results")));
var testResultsFilePath = testResultFolder + "/TestResult.xml";
var testOutputFile = File(testResultsFilePath);
var publishDirectory = MakeAbsolute(Directory(Argument("publishFolder", "./publish")));
var buildResultsFilePath = buildResultFolder + "/build.log";
var buildResultsOutputFile = File(buildResultsFilePath);
var publishProjectDirectory = MakeAbsolute(Directory("./src/App"));
var publishProjectPath = publishProjectDirectory + "/App.sln";
var publishProjectFile = File(publishProjectPath);
///////////////////////////////////////////////////////////////////////////////
// SETUP / TEARDOWN
///////////////////////////////////////////////////////////////////////////////
Setup(() =>
{
// Executed BEFORE the first task.
if (!DirectoryExists(testResultFolder))
{
CreateDirectory(testResultFolder);
}
if (!DirectoryExists(publishDirectory))
{
CreateDirectory(publishDirectory);
}
if (!DirectoryExists(buildResultFolder))
{
CreateDirectory(buildResultFolder);
}
Information("Running tasks...");
});
Teardown(() =>
{
// Executed AFTER the last task.
Information("Finished running tasks.");
});
///////////////////////////////////////////////////////////////////////////////
// TASK DEFINITIONS
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Description("Cleans all directories that are used during the build process.")
.Does(() =>
{
CleanDirectory(testResultFolder);
CleanDirectory(publishDirectory);
// Clean solution directories.
foreach(var path in solutionPaths)
{
Information("Cleaning {0}", path);
CleanDirectories(path + "/**/bin/" + configuration);
CleanDirectories(path + "/**/obj/" + configuration);
}
});
Task("Restore")
.Description("Restores all the NuGet packages that are used by the specified solution.")
.Does(() =>
{
// Restore all NuGet packages.
foreach(var solution in solutions)
{
Information("Restoring {0}...", solution);
NuGetRestore(solution);
}
});
//Task("StyleCop")
// .Does(() =>
// {
// StyleCopAnalyse(settings => settings
// .WithSolution(solutionFile)
// .WithSettings(File("./Settings.StyleCop"))
// .ToResultFile(buildResultFolder + File("StyleCopViolations.xml")));
// });
// Build the DocFX documentation site
Task("Documentation")
.Does(() =>
{
DocFxMetadata("./doc/docfx.json");
DocFxBuild("./doc/docfx.json");
CreateDirectory("artifacts");
// Archive the generated site
ZipCompress("./doc/_site", "./artifacts/site.zip");
});
Task("Build")
.Description("Builds all the different parts of the project.")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
//.IsDependentOn("StyleCop")
.Does(() =>
{
// Build all solutions.
foreach(var solution in solutions)
{
Information("Building {0}", solution);
MSBuild(solution, settings =>
settings.SetPlatformTarget(PlatformTarget.MSIL)
.WithProperty("TreatWarningsAsErrors","true")
.WithTarget("Build")
.SetConfiguration(configuration)
.AddFileLogger(
new MSBuildFileLogger {
Verbosity = Verbosity.Normal,
LogFile = buildResultsOutputFile
}));
}
CleanDirectories("./**/obj");
});
Task("Publish")
.IsDependentOn("Build")
.Does(() =>
{
EnsureDirectoryExists(publishDirectory);
// copy all things into the publish folder
});
Task("Run-Unit-Tests")
.IsDependentOn("Build")
.Does(() =>
{
EnsureDirectoryExists(testResultFolder);
NUnit3("./src/**/bin/" + configuration + "/*.Tests.dll", new NUnit3Settings {
Results = testOutputFile,
Verbose = true,
Workers = 30
});
});
Task("Generate-Unit-Test-Report")
.IsDependentOn("Run-Unit-Tests")
.Does(() =>
{
ReportUnit(testResultFolder, testResultFolder, new ReportUnitSettings());
});
///////////////////////////////////////////////////////////////////////////////
// TARGETS
///////////////////////////////////////////////////////////////////////////////
Task("Default")
.Description("This is the default task which will be ran if no specific target is passed in.")
.IsDependentOn("Generate-Unit-Test-Report");
///////////////////////////////////////////////////////////////////////////////
// EXECUTION
///////////////////////////////////////////////////////////////////////////////
RunTarget(target); | mit | C# | |
e0f7f56512d249bdf639e43e200350286e880bed | refactor out a mechanism to iterate through commits and patches | ZanyGnu/GitRepoStats | RepoStats/CommitIterator.cs | RepoStats/CommitIterator.cs | using LibGit2Sharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RepoStats
{
public class CommitIterator
{
List<CommitAnalysis> commitAnalysis;
List<PatchAnalysis> patchAnalysis;
string repoRoot;
public CommitIterator(string repoRoot, List<CommitAnalysis> commitAnalysis, List<PatchAnalysis> patchAnalysis)
{
this.commitAnalysis = commitAnalysis;
this.patchAnalysis = patchAnalysis;
this.repoRoot = repoRoot;
}
void RunThroughCommits()
{
using (var repo = new Repository(repoRoot))
{
foreach (Commit c in repo.Commits)
{
ExecuteCommitAnalysis(c, commitAnalysis, patchAnalysis);
if (c.Parents.Count() == 0)
{
continue;
}
// TODO: need to handle multiple parents.
Patch changes = repo.Diff.Compare<Patch>(c.Tree, c.Parents.First().Tree);
ExecutePatchAnalysis(patchAnalysis, c, changes);
}
}
}
private static void ExecuteCommitAnalysis(Commit c, List<CommitAnalysis> commitAnalysis, List<PatchAnalysis> patchAnalysis)
{
foreach (CommitAnalysis ca in commitAnalysis)
{
ca.Visit(c);
}
foreach (PatchAnalysis pa in patchAnalysis)
{
pa.Visit(c);
}
}
private static void ExecutePatchAnalysis(List<PatchAnalysis> patchAnalysis, Commit c, Patch changes)
{
foreach (PatchEntryChanges patchEntryChanges in changes)
{
foreach (PatchAnalysis pa in patchAnalysis)
{
pa.Visit(c, patchEntryChanges);
}
}
}
public interface CommitAnalysis
{
void Visit(Commit c);
}
public interface PatchAnalysis : CommitAnalysis
{
void Visit(Commit commit, PatchEntryChanges patch);
}
public class FileInfoAnalysis : PatchAnalysis
{
public void Visit(Commit c)
{
}
public void Visit(Commit commit, PatchEntryChanges patch)
{
}
}
}
}
| mit | C# | |
edc6e8ebe0129125f34c14ca52f76e8f7de5a034 | add unit test | CatLib/Framework,yb199478/catlib | CatLib.VS/CatLib.Tests/Translation/SelectorTests.cs | CatLib.VS/CatLib.Tests/Translation/SelectorTests.cs | /*
* This file is part of the CatLib package.
*
* (c) Yu Bin <support@catlib.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Document: http://catlib.io/
*/
using CatLib.API.Translation;
using CatLib.Translation;
#if UNITY_EDITOR || NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Category = Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute;
#endif
namespace CatLib.Tests.Translation
{
[TestClass]
public class SelectorTests
{
[TestMethod]
public void TestBaseSelect()
{
var selector = new Selector();
Assert.AreEqual("hello this is test", selector.Choose("hello this is test", 10, Language.Chinese));
}
}
}
| unknown | C# | |
7cef859253fe855d3948cb97c56d578a8a57aa13 | Add sample code file that calls both supported and unsupported library code with respect to flow summaries. | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | csharp/ql/test/query-tests/Telemetry/LibraryUsage/ExternalLibraryUsage.cs | csharp/ql/test/query-tests/Telemetry/LibraryUsage/ExternalLibraryUsage.cs | using System;
using System.Collections.Generic;
public class LibraryUsage
{
public void M1()
{
var l = new List<object>(); // Uninteresting parameterless constructor
var o = new object(); // Uninteresting parameterless constructor
l.Add(o); // Has flow summary
l.Add(o); // Has flow summary
}
public void M2()
{
var d0 = new DateTime(); // Uninteresting parameterless constructor
var next0 = d0.AddYears(30); // Has no flow summary
var d1 = new DateTime(2000, 1, 1); // Interesting constructor
var next1 = next0.AddDays(3); // Has no flow summary
var next2 = next1.AddYears(5); // Has no flow summary
}
public void M3()
{
var guid1 = Guid.Parse("{12345678-1234-1234-1234-123456789012}"); // Has no flow summary
}
}
| mit | C# | |
0c114acc473aeabaf99633c71aed71f5df87a926 | upgrade version to 2.0.1 | tangxuehua/equeue,tangxuehua/equeue,geffzhang/equeue,tangxuehua/equeue,Aaron-Liu/equeue,geffzhang/equeue,Aaron-Liu/equeue | src/EQueue/Properties/AssemblyInfo.cs | src/EQueue/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EQueue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.1")]
[assembly: AssemblyFileVersion("2.0.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EQueue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0")]
[assembly: AssemblyFileVersion("2.0.0")]
| mit | C# |
ce969ed7371a731728276608569facee41d4b928 | add helper extension to normalize strings | Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore | test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/StringExtensions.cs | test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/StringExtensions.cs | using System.Text.RegularExpressions;
namespace JsonApiDotNetCoreExampleTests.Helpers.Extensions
{
public static class StringExtensions
{
public static string Normalize(this string input)
{
return Regex.Replace(input, @"\s+", string.Empty)
.ToUpper()
.Replace('"', '\'');
}
}
} | mit | C# | |
56bd3d8a82230fd626fad39c23a40a3fd0729e1a | Add realtime multiplayer test scene | peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu | osu.Game.Tests/Visual/RealtimeMultiplayer/TestSceneRealtimeMultiplayer.cs | osu.Game.Tests/Visual/RealtimeMultiplayer/TestSceneRealtimeMultiplayer.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Screens.Multi.Components;
namespace osu.Game.Tests.Visual.RealtimeMultiplayer
{
public class TestSceneRealtimeMultiplayer : RealtimeMultiplayerTestScene
{
public TestSceneRealtimeMultiplayer()
{
var multi = new TestRealtimeMultiplayer();
AddStep("show", () => LoadScreen(multi));
AddUntilStep("wait for loaded", () => multi.IsLoaded);
}
private class TestRealtimeMultiplayer : Screens.Multi.RealtimeMultiplayer.RealtimeMultiplayer
{
protected override RoomManager CreateRoomManager() => new TestRealtimeRoomManager();
}
}
}
| mit | C# | |
cb7341ca44ec8043ded2ada238f4e9f421ab26f9 | add pagination class. | dreign/ComBoost,dreign/ComBoost | Wodsoft.ComBoost/ComponentModel/Pagination.cs | Wodsoft.ComBoost/ComponentModel/Pagination.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.ComponentModel
{
public class Pagination : IPagination
{
public Pagination()
{
PageSizeOption = EntityViewModel.DefaultPageSizeOption;
}
public Pagination(int page, int count, int size)
: this()
{
CurrentPage = page;
CurrentSize = size;
TotalPage = (int)Math.Ceiling(count / (double)size);
}
public Pagination(int page, int count)
: this(page, count, EntityViewModel.DefaultPageSize) { }
public int[] PageSizeOption { get; set; }
public int TotalPage { get; set; }
public int CurrentPage { get; set; }
public int CurrentSize { get; set; }
}
}
| mit | C# | |
ef6bde3459aaf1e8dbbbfb35ab85c75083d2d4d9 | Add stub for IndexResponse | InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET | IntegrationEngine.Core.Tests/StubIndexResponse.cs | IntegrationEngine.Core.Tests/StubIndexResponse.cs | using Elasticsearch.Net;
using Nest;
using System;
namespace IntegrationEngine.Core.Tests
{
public class StubIndexResponse : IIndexResponse
{
public StubIndexResponse()
{
}
#region IIndexResponse implementation
public string Id {
get {
throw new NotImplementedException();
}
}
public string Index {
get {
throw new NotImplementedException();
}
}
public string Type {
get {
throw new NotImplementedException();
}
}
public string Version {
get {
throw new NotImplementedException();
}
}
public bool Created {
get {
throw new NotImplementedException();
}
}
#endregion
#region IResponse implementation
public bool IsValid {
get {
throw new NotImplementedException();
}
}
public IElasticsearchResponse ConnectionStatus {
get {
throw new NotImplementedException();
}
}
public ElasticInferrer Infer {
get {
throw new NotImplementedException();
}
}
public ElasticsearchServerError ServerError {
get {
throw new NotImplementedException();
}
}
#endregion
#region IResponseWithRequestInformation implementation
public IElasticsearchResponse RequestInformation {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
#endregion
}
}
| mit | C# | |
4780ee9eb1af0b588a4cd407f4730a2a4bfcd788 | Create RobotsProblem.cs | gvaduha/homebrew,gvaduha/homebrew,gvaduha/homebrew,gvaduha/homebrew,gvaduha/homebrew,gvaduha/homebrew | CSharp/RobotsProblem.cs | CSharp/RobotsProblem.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace RobotsProblem
{
enum Containment
{
Robot,
Parachute
}
class Robot
{
int step;
IDictionary<int,Containment> v;
int pos;
bool moving;
public Robot(IDictionary<int, Containment> v, int pos)
{
this.v = v;
this.pos = pos;
this.step = 1;
this.moving = true;
}
public IEnumerable<int> run()
{
if (moving)
{
Containment c;
if (v.ContainsKey(pos + step))
{
v[pos + step] = Containment.Robot;
moving = false;
yield break;
}
if (v.TryGetValue(pos, out c) && c == Containment.Robot)
{
yield return 88;
}
step++;
yield break;
}
}
}
class RobotsProblem
{
static void Main(string[] args)
{
// if pos1==pos2 return boom;
var v = new Dictionary<int, Containment>(2) { {2, Containment.Parachute}, {7, Containment.Parachute} };
Robot r1 = new Robot(v,2);
Robot r2 = new Robot(v,7);
for (;;)
{
r1.run().Any();
if (r2.run().Any()) break;
}
Console.WriteLine("BOOM!");
//Console.WriteLine(String.Join("",v));
}
}
}
| mit | C# | |
70f0c0a68ff230d91e98d5e6d6090c08de7e3084 | Add IntanceScanner for TypeScanner | CosmosProgramme/Cosmos.Core | Standard/src/Cosmos.Extensions/InstanceScanner.cs | Standard/src/Cosmos.Extensions/InstanceScanner.cs | using System;
using System.Collections.Generic;
namespace Cosmos
{
public abstract class InstanceScanner<TClass> : TypeScanner
{
protected InstanceScanner() : base() { }
protected InstanceScanner(string scannerName) : base(scannerName) { }
protected InstanceScanner(Type baseType) : base(baseType) { }
protected InstanceScanner(string scannerName, Type baseType) : base(scannerName, baseType) { }
public virtual IEnumerable<TClass> ScanAndReturnInstances()
{
foreach (var type in Scan())
{
yield return type.CreateInstance<TClass>();
}
}
}
} | mit | C# | |
f071de2ac92b83701498e606441441721771db4a | fix port-baud remember. add single application allawed | khaikin/GymMgr | GymMgr/SingleInstCode.cs | GymMgr/SingleInstCode.cs | using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace SingleInstanceCode
{
static public class SingleInstanceClass
{
// Add "global\" in front of the EventName, then only one instance is allowed on the
// whole system, including other users. But the application can not be brought
// into view, of course.
private static String SingleAppComEventName = null;
private static BackgroundWorker singleAppComThread = null;
private static EventWaitHandle threadComEvent = null;
private static CleanupCode cleanupCode = null;
private class CleanupCode
{
~CleanupCode()
{
SingleInstanceClass.Cleanup();
}
}
/// <summary>
/// Cleanup the sources that were allocated in CheckForOtherApp().
/// </summary>
static private void Cleanup()
{
// stop the thread.
if (singleAppComThread != null)
singleAppComThread.CancelAsync();
// cloe the event so another instance can start again.
if (threadComEvent != null)
threadComEvent.Close();
}
/// <summary>
///
/// </summary>
/// <param name="uniqueName"></param>
/// <returns>True is another instance is already running. False otherwise</returns>
static public Boolean CheckForOtherApp(String uniqueName)
{
SingleAppComEventName = uniqueName;
try
{
// another instance is already running
threadComEvent = EventWaitHandle.OpenExisting(SingleAppComEventName);
threadComEvent.Set(); // signal the other instance.
threadComEvent.Close();
return true; // return immediatly.
}
catch { /* don't care about errors */ }
// Create the Event handle
threadComEvent = new EventWaitHandle(false, EventResetMode.AutoReset, SingleAppComEventName);
// make sure the resources are cleaned up afterwards.
cleanupCode = new CleanupCode();
CreateInterAppComThread();
return false;
}
/// <summary>
///
/// </summary>
static private void CreateInterAppComThread()
{
singleAppComThread = new BackgroundWorker();
singleAppComThread.WorkerReportsProgress = false;
singleAppComThread.WorkerSupportsCancellation = true;
singleAppComThread.DoWork += new DoWorkEventHandler(singleAppComThread_DoWork);
singleAppComThread.RunWorkerAsync();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static private void singleAppComThread_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
WaitHandle[] waitHandles = new WaitHandle[] { threadComEvent };
while (!worker.CancellationPending)
{
// check every second for a signal.
if (WaitHandle.WaitAny(waitHandles, 1000) == 0)
{
// The user tried to start another instance. We can't allow that,
// so bring the other instance back into view and enable that one.
// That form is created in another thread, so we need some thread sync magic.
if (Application.OpenForms.Count > 0)
{
Form mainForm = Application.OpenForms[0];
mainForm.Invoke(new SetFormVisableDelegate(ThreadFormVisable), mainForm);
}
}
}
}
// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// When this method is called using a Invoke then this runs in the thread
/// that created to form, which is nice.
/// </summary>
/// <param name="frm"></param>
private delegate void SetFormVisableDelegate(Form frm);
static private void ThreadFormVisable(Form frm)
{
if (frm != null)
{
// display the form and bring to foreground.
frm.Visible = true;
frm.WindowState = FormWindowState.Maximized;
frm.Show();
SetForegroundWindow(frm.Handle);
}
}
}
}
| unlicense | C# | |
9ebde329048c8cf62549df625b9dc28f3c8afd76 | Test HttpResults behaviour | ZocDoc/ServiceStack,nataren/NServiceKit,meebey/ServiceStack,nataren/NServiceKit,timba/NServiceKit,timba/NServiceKit,meebey/ServiceStack,timba/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,NServiceKit/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack | tests/ServiceStack.WebHost.IntegrationTests/Services/HttpResultsService.cs | tests/ServiceStack.WebHost.IntegrationTests/Services/HttpResultsService.cs | using System;
using System.Net;
using System.Runtime.Serialization;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.ServiceModel;
namespace ServiceStack.WebHost.IntegrationTests.Services
{
[RestService("/httpresults")]
[DataContract]
public class HttpResults
{
[DataMember]
public string Name { get; set; }
}
[DataContract]
public class HttpResultsResponse
: IHasResponseStatus
{
public HttpResultsResponse()
{
this.ResponseStatus = new ResponseStatus();
}
[DataMember]
public string Result { get; set; }
[DataMember]
public ResponseStatus ResponseStatus { get; set; }
}
public class HttpResultsService
: ServiceBase<HttpResults>
{
protected override object Run(HttpResults request)
{
if (request.Name == "Error")
throw new HttpError(HttpStatusCode.NotFound, "Error NotFound");
return new HttpResult(HttpStatusCode.NotFound, "Returned NotFound");
}
}
} | bsd-3-clause | C# | |
c4584cd02c95edacfccec49c97f65d0cd34b9979 | Create teacherCreateViewModel | Programazing/Open-School-Library,Programazing/Open-School-Library | src/Open-School-Library/Models/TeacherViewModels/TeacherCreateViewModel.cs | src/Open-School-Library/Models/TeacherViewModels/TeacherCreateViewModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.TeacherViewModels
{
public class TeacherCreateViewModel
{
}
}
| mit | C# | |
302b06088fbd98248b35dd7d2bebec05cc6dfcca | Create sortedBitSearch.cs | michaeljwebb/Algorithm-Practice | Other/sortedBitSearch.cs | Other/sortedBitSearch.cs | //Given an array of sorted 0s and 1s, count how many 1st exist
//Space complexity: O(1)
//Time complexity: O(log(N)) where N is the number of digits
//Example: [0,0,0,0,0,1,1,1] -> 3
| mit | C# | |
4458377bf394588cc80aa70234451f63f4398086 | Fix for LOG4NET-154. Added StackTracePatternConverter that outputs the methods called before the log message. | freedomvoice/log4net,freedomvoice/log4net,twcclegg/log4net,freedomvoice/log4net,twcclegg/log4net,twcclegg/log4net,freedomvoice/log4net,twcclegg/log4net | src/Layout/Pattern/StackTracePatternConverter.cs | src/Layout/Pattern/StackTracePatternConverter.cs | #region Apache License
//
// 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.
//
#endregion
using System;
using System.Globalization;
using System.Text;
using System.IO;
using System.Diagnostics;
using log4net.Util;
using log4net.Core;
namespace log4net.Layout.Pattern
{
/// <summary>
/// Write the caller stack frames to the output
/// </summary>
/// <remarks>
/// <para>
/// Writes the <see cref="LocationInfo.StackFrames"/> to the output writer, using format:
/// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1
/// </para>
/// </remarks>
/// <author>Michael Cromwell</author>
internal sealed class StackTracePatternConverter : PatternLayoutConverter, IOptionHandler
{
private int m_stackFrameLevel = 1;
/// <summary>
/// Initialize the converter
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
public void ActivateOptions()
{
if (Option == null)
return;
string optStr = Option.Trim();
if (!string.IsNullOrEmpty(optStr))
{
int stackLevelVal;
if (SystemInfo.TryParse(optStr, out stackLevelVal))
{
if (stackLevelVal <= 0)
{
LogLog.Error(declaringType, "StackTracePatternConverter: StackeFrameLevel option (" + optStr + ") isn't a positive integer.");
}
else
{
m_stackFrameLevel = stackLevelVal;
}
}
else
{
LogLog.Error(declaringType, "StackTracePatternConverter: StackFrameLevel option \"" + optStr + "\" not a decimal integer.");
}
}
}
/// <summary>
/// Write the strack frames to the output
/// </summary>
/// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param>
/// <param name="loggingEvent">the event being logged</param>
/// <remarks>
/// <para>
/// Writes the <see cref="LocationInfo.StackFrames"/> to the output writer.
/// </para>
/// </remarks>
override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
StackFrame[] stackframes = loggingEvent.LocationInformation.StackFrames;
if ((stackframes == null) || (stackframes.Length <= 0))
{
LogLog.Error(declaringType, "loggingEvent.LocationInformation.StackFrames was null or empty.");
return;
}
int stackFrameIndex = m_stackFrameLevel - 1;
while (stackFrameIndex >= 0)
{
if (stackFrameIndex > stackframes.Length)
{
stackFrameIndex--;
continue;
}
StackFrame stackFrame = stackframes[stackFrameIndex];
writer.Write("{0}.{1}", stackFrame.GetMethod().DeclaringType.Name, stackFrame.GetMethod().Name);
if (stackFrameIndex > 0)
{
writer.Write(" > ");
}
stackFrameIndex--;
}
}
#region Private Static Fields
/// <summary>
/// The fully qualified type of the StackTracePatternConverter class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(StackTracePatternConverter);
#endregion Private Static Fields
}
}
| apache-2.0 | C# | |
08c4327d8d7fecf58265dec5023e626217959dee | Add tests for Get & AddToPayload | bugsnag/bugsnag-dotnet,bugsnag/bugsnag-dotnet | tests/Bugsnag.Tests/PayloadExtensionsTests.cs | tests/Bugsnag.Tests/PayloadExtensionsTests.cs | using Bugsnag.Payload;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Bugsnag.Tests
{
public class PayloadExtensionsTests
{
[Theory]
[MemberData(nameof(PayloadTestData))]
public void AddToPayloadTests(Dictionary<string, object> dictionary, string key, object value, object expectedValue)
{
dictionary.AddToPayload(key, value);
if (expectedValue == null)
{
Assert.DoesNotContain(key, dictionary.Keys);
}
else
{
Assert.Equal(expectedValue, dictionary[key]);
}
}
public static IEnumerable<object[]> PayloadTestData()
{
yield return new object[] { new Dictionary<string, object>(), "key", 1, 1 };
yield return new object[] { new Dictionary<string, object>(), "key", null, null };
yield return new object[] { new Dictionary<string, object>(), "key", "", null };
yield return new object[] { new Dictionary<string, object>(), "key", "value", "value" };
yield return new object[] { new Dictionary<string, object> { { "key", 1 } }, "key", null, null };
yield return new object[] { new Dictionary<string, object> { { "key", 1 } }, "key", "", null };
}
[Fact]
public void GetExistingKey()
{
var dictionary = new Dictionary<string, object> { { "key", "value" } };
Assert.Equal("value", dictionary.Get("key"));
}
[Fact]
public void GetNonExistentKeyReturnsNull()
{
var dictionary = new Dictionary<string, object>();
Assert.Null(dictionary.Get("key"));
}
}
}
| mit | C# | |
80faf48bfe375ab960fc66b7740ee180b6236e62 | add Althash, RPCVersion, Keypaths | dgarage/NBXplorer,dgarage/NBXplorer | NBXplorer.Client/NBXplorerNetworkProvider.Althash.cs | NBXplorer.Client/NBXplorerNetworkProvider.Althash.cs | using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
namespace NBXplorer
{
public partial class NBXplorerNetworkProvider
{
private void InitAlthash(ChainName networkType)
{
Add(new NBXplorerNetwork(NBitcoin.Altcoins.Althash.Instance, networkType)
{
MinRPCVersion = 16990,
CoinType = networkType == ChainName.Mainnet ? new KeyPath("88'") : new KeyPath("1'")
});
}
public NBXplorerNetwork GetALTHASH()
{
return GetFromCryptoCode(NBitcoin.Altcoins.Althash.Instance.CryptoCode);
}
}
}
| mit | C# | |
694b9f9810f106801adcf4d05349e5850fb7b82d | Create SpectralPlot class | SICU-Stress-Measurement-System/frontend-cs | StressMeasurementSystem/Models/Plots/SpectralPlot.cs | StressMeasurementSystem/Models/Plots/SpectralPlot.cs | using OxyPlot;
namespace StressMeasurementSystem.Models.Plots
{
public class SpectralPlot : PlotModel
{
}
} | apache-2.0 | C# | |
b86f650a30c0526d86dc2b4854a7519b7952efd5 | Add test case for TypeRegistry | ViveportSoftware/vita_core_csharp,ViveportSoftware/vita_core_csharp | source/Htc.Vita.Core.Tests/TypeRegistryTest.cs | source/Htc.Vita.Core.Tests/TypeRegistryTest.cs | using Htc.Vita.Core.Util;
using Xunit;
namespace Htc.Vita.Core.Tests
{
public class TypeRegistryTest
{
[Fact]
public static void Default_0_RegisterDefault()
{
TypeRegistry.RegisterDefault<BaseClass, SubClass1>();
}
[Fact]
public static void Default_1_Register()
{
TypeRegistry.RegisterDefault<BaseClass, SubClass1>();
TypeRegistry.Register<BaseClass, SubClass2>();
}
[Fact]
public static void Default_2_GetInstance()
{
TypeRegistry.RegisterDefault<BaseClass, SubClass1>();
TypeRegistry.Register<BaseClass, SubClass2>();
var obj = TypeRegistry.GetInstance<BaseClass>();
Assert.False(obj is SubClass1);
Assert.True(obj is SubClass2);
}
}
public abstract class BaseClass
{
}
public class SubClass1 : BaseClass
{
}
public class SubClass2 : BaseClass
{
}
}
| mit | C# | |
63eb9e60f3f509fd3d62d878a540cd5273c670eb | Add missing file | z4kn4fein/stashbox | test/DependencyBindingTests.cs | test/DependencyBindingTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Stashbox.Tests
{
[TestClass]
public class DependencyBindingTests
{
[TestMethod]
public void DependencyBindingTests_Bind_To_The_Same_Type()
{
var inst = new StashboxContainer()
.Register<ITest1, Test1>("test1")
.Register<ITest1, Test11>("test2")
.Register<ITest1, Test12>("test3")
.Register<Test>(ctx => ctx.WithDependencyBinding(typeof(ITest1), "test2"))
.Resolve<Test>();
Assert.IsInstanceOfType(inst.Test1, typeof(Test11));
Assert.IsInstanceOfType(inst.Test2, typeof(Test11));
Assert.IsInstanceOfType(inst.Test3, typeof(Test11));
}
[TestMethod]
public void DependencyBindingTests_Bind_To_Different_Types()
{
var inst = new StashboxContainer()
.Register<ITest1, Test1>("test1")
.Register<ITest1, Test11>("test2")
.Register<ITest1, Test12>("test3")
.Register<Test>(ctx => ctx
.WithDependencyBinding("test1", "test1")
.WithDependencyBinding("test2", "test2")
.WithDependencyBinding("test3", "test3"))
.Resolve<Test>();
Assert.IsInstanceOfType(inst.Test1, typeof(Test1));
Assert.IsInstanceOfType(inst.Test2, typeof(Test11));
Assert.IsInstanceOfType(inst.Test3, typeof(Test12));
}
[TestMethod]
public void DependencyBindingTests_Override_Typed_Bindings()
{
var inst = new StashboxContainer()
.Register<ITest1, Test1>("test1")
.Register<ITest1, Test11>("test2")
.Register<ITest1, Test12>("test3")
.Register<Test>(ctx => ctx
.WithDependencyBinding("test3", "test3")
.WithDependencyBinding<ITest1>("test2"))
.Resolve<Test>();
Assert.IsInstanceOfType(inst.Test1, typeof(Test11));
Assert.IsInstanceOfType(inst.Test2, typeof(Test11));
Assert.IsInstanceOfType(inst.Test3, typeof(Test12));
}
interface ITest1 { }
class Test1 : ITest1
{ }
class Test11 : ITest1
{ }
class Test12 : ITest1
{ }
class Test
{
public ITest1 Test1 { get; }
public ITest1 Test2 { get; }
public ITest1 Test3 { get; }
public Test(ITest1 test1, ITest1 test2, ITest1 test3)
{
this.Test1 = test1;
this.Test2 = test2;
this.Test3 = test3;
}
}
}
}
| mit | C# | |
cfa84826c3478e58b78b41ca98fb14d3272baef0 | Implement IDisposable for IpcChannel | DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,naoey/osu-framework,NeoAdonis/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,RedNesto/osu-framework,naoey/osu-framework,Tom94/osu-framework,Nabile-Rahmani/osu-framework,NeoAdonis/osu-framework,peppy/osu-framework,Tom94/osu-framework,paparony03/osu-framework,default0/osu-framework,default0/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,RedNesto/osu-framework,smoogipooo/osu-framework,paparony03/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework | osu.Framework/Platform/IpcChannel.cs | osu.Framework/Platform/IpcChannel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace osu.Framework.Platform
{
public class IpcChannel<T> : IDisposable
{
private BasicGameHost host;
public event Action<T> MessageReceived;
public IpcChannel(BasicGameHost host)
{
this.host = host;
this.host.MessageReceived += HandleMessage;
}
public async Task SendMessage(T message)
{
var msg = new IpcMessage
{
Type = typeof(T).AssemblyQualifiedName,
Value = message,
};
await host.SendMessage(msg);
}
private void HandleMessage(IpcMessage message)
{
if (message.Type != typeof(T).AssemblyQualifiedName)
return;
MessageReceived?.Invoke((T)message.Value);
}
public void Dispose()
{
this.host.MessageReceived -= HandleMessage;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace osu.Framework.Platform
{
public class IpcChannel<T>
{
private BasicGameHost host;
public event Action<T> MessageReceived;
public IpcChannel(BasicGameHost host)
{
this.host = host;
this.host.MessageReceived += HandleMessage;
}
public async Task SendMessage(T message)
{
var msg = new IpcMessage
{
Type = typeof(T).AssemblyQualifiedName,
Value = message,
};
await host.SendMessage(msg);
}
private void HandleMessage(IpcMessage message)
{
if (message.Type != typeof(T).AssemblyQualifiedName)
return;
MessageReceived?.Invoke((T)message.Value);
}
}
} | mit | C# |
52f4b18990a7e095bd1c2611967ccf66d83026db | Add Error description classes. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Helpers/ErrorDescriptor.cs | WalletWasabi/Helpers/ErrorDescriptor.cs | using System;
using System.Collections.Generic;
namespace WalletWasabi.Helpers
{
public class ErrorDescriptors : List<ErrorDescriptor>
{
public bool HasErrors => this.Count == 0;
}
public enum ErrorSeverity
{
Default,
Info,
Warning,
Error
}
public struct ErrorDescriptor : IEquatable<ErrorDescriptor>
{
public static ErrorDescriptor Default = new ErrorDescriptor(ErrorSeverity.Default, string.Empty);
public ErrorSeverity Severity { get; }
public string Message { get; }
public ErrorDescriptor(ErrorSeverity severity, string message)
{
this.Severity = severity;
this.Message = message;
}
public bool Equals(ErrorDescriptor other)
{
return (this.Severity == other.Severity && this.Message == other.Message);
}
}
}
| mit | C# | |
672568d1f57a893785f9d13e6992217221e0dba0 | Add missing file | sargin48/Umbraco-CMS,madsoulswe/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,lars-erik/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,tompipe/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS,rustyswayne/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,aadfPT/Umbraco-CMS,umbraco/Umbraco-CMS,rasmuseeg/Umbraco-CMS,base33/Umbraco-CMS,rustyswayne/Umbraco-CMS,tcmorris/Umbraco-CMS,aadfPT/Umbraco-CMS,mattbrailsford/Umbraco-CMS,jchurchley/Umbraco-CMS,NikRimington/Umbraco-CMS,jchurchley/Umbraco-CMS,sargin48/Umbraco-CMS,dawoe/Umbraco-CMS,gavinfaux/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tompipe/Umbraco-CMS,tcmorris/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,sargin48/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,kgiszewski/Umbraco-CMS,arknu/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,aaronpowell/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,base33/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,tompipe/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,gavinfaux/Umbraco-CMS,gavinfaux/Umbraco-CMS,gavinfaux/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,sargin48/Umbraco-CMS,gavinfaux/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,jchurchley/Umbraco-CMS,mattbrailsford/Umbraco-CMS,kgiszewski/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,rustyswayne/Umbraco-CMS,WebCentrum/Umbraco-CMS,rustyswayne/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,aadfPT/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,sargin48/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,WebCentrum/Umbraco-CMS,leekelleher/Umbraco-CMS,rustyswayne/Umbraco-CMS,robertjf/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,lars-erik/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,aaronpowell/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,NikRimington/Umbraco-CMS,kgiszewski/Umbraco-CMS,lars-erik/Umbraco-CMS,aaronpowell/Umbraco-CMS,tcmorris/Umbraco-CMS,base33/Umbraco-CMS,madsoulswe/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS | src/Umbraco.Core/ObjectResolution/WeightAttribute.cs | src/Umbraco.Core/ObjectResolution/WeightAttribute.cs | using System;
namespace Umbraco.Core.ObjectResolution
{
/// <summary>
/// Indicates the relative weight of a resolved object type.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class WeightAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="WeightAttribute"/> class with a weight.
/// </summary>
/// <param name="weight">The object type weight.</param>
public WeightAttribute(int weight)
{
Weight = weight;
}
/// <summary>
/// Gets or sets the weight of the object type.
/// </summary>
public int Weight { get; private set; }
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.