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 |
|---|---|---|---|---|---|---|---|---|
2e1505c69f52045fb8800708726c24630feafaac | Add file missed in bug fix 440109 | nunit/nunit-console,nunit/nunit-console,nunit/nunit-console | src/framework/Templates/Contains.template.cs | src/framework/Templates/Contains.template.cs | // ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// 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.
// ***********************************************************************
// ****************************************************************
// Generated by the NUnit Syntax Generator
//
// Command Line: __COMMANDLINE__
//
// DO NOT MODIFY THIS FILE DIRECTLY
// ****************************************************************
using System;
using System.Collections;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class Contains
{
// $$GENERATE$$ $$STATIC$$
}
}
| mit | C# | |
5ef4ed24fd10679e90092f2c0c90fbf1c44d243b | Add Q221 | txchen/localleet | csharp/Q221_MaximalSquare.cs | csharp/Q221_MaximalSquare.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
//
// For example, given the following matrix:
//
// 1 0 1 0 0
// 1 0 1 1 1
// 1 1 1 1 1
// 1 0 0 1 0
// Return 4.
// https://leetcode.com/problems/maximal-square/
namespace LocalLeet
{
public class Q221
{
public int MaximalSquare(char[,] matrix)
{
int row = matrix.GetLength(0);
int col = matrix.GetLength(1);
// dp[i, j] = n, means i, j is '1', and it is the bottom-right of the square, n is the size
int[,] dp = new int[row, col];
int size = 0;
// init first row and first column
for (int c = 0; c < col; c++)
{
if (matrix[0, c] == '1')
{
dp[0, c] = 1;
size = 1;
}
}
for (int r = 0; r < row; r++)
{
if (matrix[r, 0] == '1')
{
dp[r, 0] = 1;
size = 1;
}
}
// scan the board
for (int r = 1; r < row; r++)
{
for (int c = 1; c < col; c++)
{
if (matrix[r, c] == '1')
{
// size = min(upleft, left, up) + 1
int mySize = Math.Min(dp[r-1, c-1], dp[r-1, c]);
mySize = Math.Min(mySize, dp[r, c-1]) + 1;
dp[r, c] = mySize;
size = Math.Max(size, mySize);
}
}
}
return size * size;
}
[Fact]
public void Q221_MaximalSquare()
{
TestHelper.Run(input => MaximalSquare(input.EntireInput.ToChar2DArray()).ToString());
}
}
}
| mit | C# | |
caa207f59f5c7e9160715172e22bd59659abbeb4 | Add ossl level test for removing an unowned npc | ft-/opensim-optimizations-wip-tests,RavenB/opensim,bravelittlescientist/opensim-performance,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-extras,OpenSimian/opensimulator,TomDataworks/opensim,M-O-S-E-S/opensim,TomDataworks/opensim,RavenB/opensim,BogusCurry/arribasim-dev,justinccdev/opensim,Michelle-Argus/ArribasimExtract,TomDataworks/opensim,Michelle-Argus/ArribasimExtract,BogusCurry/arribasim-dev,Michelle-Argus/ArribasimExtract,justinccdev/opensim,ft-/opensim-optimizations-wip-extras,QuillLittlefeather/opensim-1,ft-/arribasim-dev-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,rryk/omp-server,M-O-S-E-S/opensim,bravelittlescientist/opensim-performance,M-O-S-E-S/opensim,TomDataworks/opensim,bravelittlescientist/opensim-performance,justinccdev/opensim,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-extras,Michelle-Argus/ArribasimExtract,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,ft-/arribasim-dev-tests,QuillLittlefeather/opensim-1,rryk/omp-server,OpenSimian/opensimulator,RavenB/opensim,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,rryk/omp-server,M-O-S-E-S/opensim,justinccdev/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-tests,RavenB/opensim,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,justinccdev/opensim,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,OpenSimian/opensimulator,bravelittlescientist/opensim-performance,ft-/arribasim-dev-extras,ft-/arribasim-dev-extras,justinccdev/opensim,ft-/arribasim-dev-tests,ft-/arribasim-dev-tests,TomDataworks/opensim,QuillLittlefeather/opensim-1,Michelle-Argus/ArribasimExtract,M-O-S-E-S/opensim,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-extras,OpenSimian/opensimulator,rryk/omp-server,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,OpenSimian/opensimulator,RavenB/opensim,ft-/arribasim-dev-tests,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,rryk/omp-server,BogusCurry/arribasim-dev,RavenB/opensim,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip,bravelittlescientist/opensim-performance,rryk/omp-server,TomDataworks/opensim,Michelle-Argus/ArribasimExtract,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC | OpenSim/Region/ScriptEngine/Shared/Tests/OSSL_ApiNpcTests.cs | OpenSim/Region/ScriptEngine/Shared/Tests/OSSL_ApiNpcTests.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Avatar.AvatarFactory;
using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
/// <summary>
/// Tests for OSSL NPC API
/// </summary>
[TestFixture]
public class OSSL_NpcApiAppearanceTest
{
protected Scene m_scene;
protected XEngine.XEngine m_engine;
[SetUp]
public void SetUp()
{
IConfigSource initConfigSource = new IniConfigSource();
IConfig config = initConfigSource.AddConfig("XEngine");
config.Set("Enabled", "true");
config.Set("AllowOSFunctions", "true");
config.Set("OSFunctionThreatLevel", "Severe");
config = initConfigSource.AddConfig("NPC");
config.Set("Enabled", "true");
m_scene = SceneHelpers.SetupScene();
SceneHelpers.SetupSceneModules(m_scene, initConfigSource, new AvatarFactoryModule(), new NPCModule());
m_engine = new XEngine.XEngine();
m_engine.Initialise(initConfigSource);
m_engine.AddRegion(m_scene);
}
/// <summary>
/// Test creation of an NPC where the appearance data comes from an avatar already in the region.
/// </summary>
[Test]
public void TestOsNpcRemove()
{
TestHelpers.InMethod();
// log4net.Config.XmlConfigurator.Configure();
// Store an avatar with a different height from default in a notecard.
UUID userId = TestHelpers.ParseTail(0x1);
float newHeight = 1.9f;
ScenePresence sp = SceneHelpers.AddScenePresence(m_scene, userId);
sp.Appearance.AvatarHeight = newHeight;
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, userId);
SceneObjectPart part = so.RootPart;
m_scene.AddSceneObject(so);
OSSL_Api osslApi = new OSSL_Api();
osslApi.Initialize(m_engine, part, part.LocalId, part.UUID);
string notecardName = "appearanceNc";
osslApi.osOwnerSaveAppearance(notecardName);
string npcRaw
= osslApi.osNpcCreate(
"Jane", "Doe", new LSL_Types.Vector3(128, 128, 128), notecardName, ScriptBaseClass.OS_NPC_NOT_OWNED);
osslApi.osNpcRemove(npcRaw);
UUID npcId = new UUID(npcRaw);
ScenePresence npc = m_scene.GetScenePresence(npcId);
Assert.That(npc, Is.Null);
}
}
} | bsd-3-clause | C# | |
38693035eeacdf4113691d914e31058019cb9f65 | Add MySqlDbUpdateExpression.cs. | shuxinqin/Chloe | src/Chloe.MySql/MySqlDbUpdateExpression.cs | src/Chloe.MySql/MySqlDbUpdateExpression.cs | using Chloe.DbExpressions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Chloe.MySql
{
class MySqlDbUpdateExpression : DbUpdateExpression
{
public MySqlDbUpdateExpression(DbTable table)
: this(table, null)
{
}
public MySqlDbUpdateExpression(DbTable table, DbExpression condition)
: base(table, condition)
{
}
public int? Limits { get; set; }
}
}
| mit | C# | |
dc19cdbd96894460ba70856685d9326d44bf9d6d | Create Armor.cs | TeamLockheed/LockheedTheGame | Lockheed_Inventory/Slots/Armor.cs | Lockheed_Inventory/Slots/Armor.cs | namespace Lockheed_Inventory
{
using System;
using System.Collections.Generic;
using Slots.Interfaces;
public class Armor : Slot, IArmor
{
private List<Item> armorList;
public Armor() :
base()
{
}
public override void Equip(Item item)
{
this.armorList.Add(item);
this.freeSlot = false;
}
public override void UnEquip(Item item)
{
this.armorList.Remove(item);
this.freeSlot = true;
}
public List<Item> ArmorList
{
get { return this.armorList; }
set { this.armorList = value; }
}
public override bool FreeSlot
{
get { return this.freeSlot; }
set { this.freeSlot = value; }
}
}
}
| mit | C# | |
1e2de017c256c508bede3cac5779cce014f29842 | Create RouteExtensions.cs | drawcode/labs-csharp | extension/RouteExtensions.cs | extension/RouteExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
public class LowercaseRoute : Route {
public LowercaseRoute(string url, IRouteHandler routeHandler)
: base(url, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
: base(url, defaults, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
: base(url, defaults, constraints, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler) { }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) {
VirtualPathData path = base.GetVirtualPath(requestContext, values);
if (path != null) {
//if (path.VirtualPath.ToLowerInvariant().Contains("externallogin")) {
// path.VirtualPath = path.VirtualPath; //.ToLowerInvariant();
//}
//else {
path.VirtualPath = path.VirtualPath; //.ToLowerInvariant();
//}
}
return path;
}
}
public static class RouteCollectionExtension {
public static Route MapRouteLowerCase(this RouteCollection routes, string name, string url, object defaults) {
return routes.MapRouteLowerCase(name, url, defaults, null);
}
public static Route MapRouteLowerCase(this RouteCollection routes, string name, string url, object defaults, object constraints) {
Route route = new LowercaseRoute(url, new MvcRouteHandler()) {
Defaults = new RouteValueDictionary(defaults),
Constraints = new RouteValueDictionary(constraints)
};
routes.Add(name, route);
return route;
}
}
| mit | C# | |
009123d040ee97f0b1fae42ae7617263c00d420f | refactor CollectionMetaDataRecord into CollectionRoot | markmeeus/MarcelloDB | Marcello/Records/CollectionRoot.cs | Marcello/Records/CollectionRoot.cs | using System;
using Marcello.Serialization;
namespace Marcello.Records
{
internal class RootBlock
{
internal ListEndPoints DataListEndPoints { get; set;}
internal ListEndPoints EmptyListEndPoints { get; set;}
internal Int64 NamedRecordIndexAddress { get; set;}
internal RootBlock()
{
}
internal static int ByteSize
{
get { return 1024; } //some padding for future use
}
internal byte[] AsBytes()
{
var bytes = new byte[ByteSize];
var bufferWriter = new BufferWriter(bytes, BitConverter.IsLittleEndian);
bufferWriter.WriteInt64(this.DataListEndPoints.StartAddress);
bufferWriter.WriteInt64(this.DataListEndPoints.EndAddress);
bufferWriter.WriteInt64(this.EmptyListEndPoints.StartAddress);
bufferWriter.WriteInt64(this.EmptyListEndPoints.EndAddress);
bufferWriter.WriteInt64(this.NamedRecordIndexAddress);
//do no use the trimmed buffer as we want some padding for future use
return bufferWriter.Buffer;
}
internal static RootBlock FromBytes(byte[] bytes)
{
var bufferReader = new BufferReader(bytes, BitConverter.IsLittleEndian);
var startAddress = bufferReader.ReadInt64();
var endAddress = bufferReader.ReadInt64();
var dataListEndPoints = new ListEndPoints(startAddress, endAddress);
startAddress = bufferReader.ReadInt64();
endAddress = bufferReader.ReadInt64();
var emptyListEndPoints = new ListEndPoints(startAddress, endAddress);
var namedRecordIndexAddress = bufferReader.ReadInt64();
return new RootBlock(){
DataListEndPoints = dataListEndPoints,
EmptyListEndPoints = emptyListEndPoints,
NamedRecordIndexAddress = namedRecordIndexAddress
};
}
internal void Sanitize()
{
//when the data list is empty, the empty list is empty too.
if(this.DataListEndPoints.StartAddress == 0)
{
this.EmptyListEndPoints.StartAddress = 0;
this.EmptyListEndPoints.EndAddress = 0;
}
}
}
}
| mit | C# | |
0e607ac629d194f54d15057a985b7633a80201d2 | Create Day_3_CSharp.cs | leocabrallce/HackerRank,leocabrallce/HackerRank | 30_Days_of_Code_Challenges/Day_3/Day_3_CSharp.cs | 30_Days_of_Code_Challenges/Day_3/Day_3_CSharp.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int N = Convert.ToInt32(Console.ReadLine());
if (N % 2 == 1)
{
Console.WriteLine("Weird");
}
else if (N % 2 == 0)
{
if (N <= 20 && N >= 6)
{
Console.WriteLine("Weird");
}
else {
Console.WriteLine("Not Weird");
}
}
}
}
| mit | C# | |
45808e6983fe8c685ccec2b9cec37a30c19e4f12 | Add IRemovalListener interface. | NextMethod/Tamarind | Tamarind/Cache/IRemovalListener.cs | Tamarind/Cache/IRemovalListener.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tamarind.Cache
{
public interface IRemovalListener<TKey, TValue>
{
void onRemoval(RemovalNotification<TKey, TValue> notification);
}
}
| mit | C# | |
75bc376e564a617030df699fcef4ad31c7503f54 | add UserGroupController. | robertzml/Phoebe | Phoebe.WebAPI/Controllers/UserGroupController.cs | Phoebe.WebAPI/Controllers/UserGroupController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Phoebe.WebAPI.Controllers
{
using Phoebe.Core.BL;
using Phoebe.Core.Entity;
using Phoebe.WebAPI.Model;
/// <summary>
/// 用户组控制器
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class UserGroupController : ControllerBase
{
#region Action
/// <summary>
/// 获取所有用户组
/// </summary>
/// <returns></returns>
public ActionResult<List<UserGroup>> List()
{
UserGroupBusiness userGroupBusiness = new UserGroupBusiness();
return userGroupBusiness.FindAll();
}
#endregion //Action
}
} | mit | C# | |
c587fd04230a71ee6c4dc1e1713f6aef22341744 | Convert Comparables | danielwertheim/Ensure.That,danielwertheim/Ensure.That | src/EnsureThat/EnsureArg.Comparables.cs | src/EnsureThat/EnsureArg.Comparables.cs | using System;
using System.Diagnostics;
using EnsureThat.Extensions;
namespace EnsureThat
{
public static partial class EnsureArg
{
[DebuggerStepThrough]
public static void Is<T>(T param, T expected, string paramName = Param.DefaultName) where T : struct, IComparable<T>
{
if (!Ensure.IsActive)
return;
if (!param.IsEq(expected))
throw new ArgumentException(ExceptionMessages.EnsureExtensions_Is_Failed.Inject(param, expected));
}
[DebuggerStepThrough]
public static void IsNot<T>(T param, T expected, string paramName = Param.DefaultName) where T : struct, IComparable<T>
{
if (!Ensure.IsActive)
return;
if (param.IsEq(expected))
throw new ArgumentException(ExceptionMessages.EnsureExtensions_IsNot_Failed.Inject(param, expected));
}
[DebuggerStepThrough]
public static void IsLt<T>(T param, T limit, string paramName = Param.DefaultName) where T : struct, IComparable<T>
{
if (!Ensure.IsActive)
return;
if (!param.IsLt(limit))
throw new ArgumentException(ExceptionMessages.EnsureExtensions_IsNotLt.Inject(param, limit));
}
[DebuggerStepThrough]
public static void IsLte<T>(T param, T limit, string paramName = Param.DefaultName) where T : struct, IComparable<T>
{
if (!Ensure.IsActive)
return;
if (param.IsGt(limit))
throw new ArgumentException(ExceptionMessages.EnsureExtensions_IsNotLte.Inject(param, limit));
}
[DebuggerStepThrough]
public static void IsGt<T>(T param, T limit, string paramName = Param.DefaultName) where T : struct, IComparable<T>
{
if (!Ensure.IsActive)
return;
if (!param.IsGt(limit))
throw new ArgumentException(ExceptionMessages.EnsureExtensions_IsNotGt.Inject(param, limit));
}
[DebuggerStepThrough]
public static void IsGte<T>(T param, T limit, string paramName = Param.DefaultName) where T : struct, IComparable<T>
{
if (!Ensure.IsActive)
return;
if (param.IsLt(limit))
throw new ArgumentException(ExceptionMessages.EnsureExtensions_IsNotGte.Inject(param, limit));
}
[DebuggerStepThrough]
public static void IsInRange<T>(T param, T min, T max, string paramName = Param.DefaultName) where T : struct, IComparable<T>
{
if (!Ensure.IsActive)
return;
if (param.IsLt(min))
throw new ArgumentException(ExceptionMessages.EnsureExtensions_IsNotInRange_ToLow.Inject(param, min));
if (param.IsGt(max))
throw new ArgumentException(ExceptionMessages.EnsureExtensions_IsNotInRange_ToHigh.Inject(param, max));
}
}
}
| mit | C# | |
3babb41574ea13c469d9c453c98a34f1ab83bab8 | Allow overriding default static files in theme | MattHarrington/sample-sandra-snow-blog,Pxtl/Sandra.Snow,tareq-s/Sandra.Snow,fekberg/Sandra.Snow,darrelmiller/Sandra.Snow,MattHarrington/sample-sandra-snow-blog,tareq-s/Sandra.Snow,Sandra/Sandra.Snow,tareq-s/Sandra.Snow,amitapl/blogamitapple,Sandra/Sandra.Snow,Sandra/Sandra.Snow,darrelmiller/Sandra.Snow,fekberg/Sandra.Snow,Pxtl/Sandra.Snow,MattHarrington/sample-sandra-snow-blog,gsferreira/Sandra.Snow,fekberg/Sandra.Snow,gsferreira/Sandra.Snow,gsferreira/Sandra.Snow,amitapl/blogamitapple,amitapl/blogamitapple,Pxtl/Sandra.Snow,darrelmiller/Sandra.Snow | src/Snow/SnowViewLocationConventions.cs | src/Snow/SnowViewLocationConventions.cs | namespace Snow
{
using System;
using System.Collections.Generic;
using Nancy.Conventions;
using Nancy.ViewEngines;
public class SnowViewLocationConventions : IConvention
{
public static SnowSettings Settings { get; set; }
public void Initialise(NancyConventions conventions)
{
ConfigureViewLocationConventions(conventions);
}
public Tuple<bool, string> Validate(NancyConventions conventions)
{
return Tuple.Create(true, string.Empty);
}
private static void ConfigureViewLocationConventions(NancyConventions conventions)
{
conventions.ViewLocationConventions = new List<Func<string, object, ViewLocationContext, string>>
{
(viewName, model, viewLocationContext) => Settings.PostsRaw.TrimEnd('/') + "/" + viewName,
(viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + Settings.LayoutsRaw.TrimEnd('/') + "/" + viewName,
(viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + viewName,
(viewName, model, viewLocationContext) => viewName,
};
}
}
} | namespace Snow
{
using System;
using System.Collections.Generic;
using Nancy.Conventions;
using Nancy.ViewEngines;
public class SnowViewLocationConventions : IConvention
{
public static SnowSettings Settings { get; set; }
public void Initialise(NancyConventions conventions)
{
ConfigureViewLocationConventions(conventions);
}
public Tuple<bool, string> Validate(NancyConventions conventions)
{
return Tuple.Create(true, string.Empty);
}
private static void ConfigureViewLocationConventions(NancyConventions conventions)
{
conventions.ViewLocationConventions = new List<Func<string, object, ViewLocationContext, string>>
{
(viewName, model, viewLocationContext) => Settings.PostsRaw.TrimEnd('/') + "/" + viewName,
(viewName, model, viewLocationContext) => Settings.ThemesDir + Settings.Theme + "/" + Settings.LayoutsRaw.TrimEnd('/') + "/" + viewName,
(viewName, model, viewLocationContext) => viewName
};
}
}
} | mit | C# |
0ed7722a575517e7e3e8437169a1b1d822adc923 | Add pushconsumer wrap to donet | StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals,StyleTang/incubator-rocketmq-externals | rocketmq-client-donet/src/PushConsumerWrap.cs | rocketmq-client-donet/src/PushConsumerWrap.cs | using System;
using System.Runtime.InteropServices;
namespace RocketMQ.Interop
{
public static class PushConsumerWrap
{
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr CreatePushConsumer(string groupId);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int DestroyPushConsumer(IntPtr consumer);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int StartPushConsumer(IntPtr consumer);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ShutdownPushConsumer(IntPtr consumer);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int SetPushConsumerGroupID(IntPtr consumer, string groupId);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int SetPushConsumerNameServerAddress(IntPtr consumer, string namesrv);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int SetPushConsumerSessionCredentials(IntPtr consumer, string accessKey, string secretKey, string channel);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int Subscribe(IntPtr consumer, string topic, string expression);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "GetPushConsumerGroupID")]
internal static extern IntPtr GetPushConsumerGroupIDInternal(IntPtr consumer);
public static string GetPushConsumerGroupID(IntPtr consumer)
{
var ptr = GetPushConsumerGroupIDInternal(consumer);
if (ptr == IntPtr.Zero) return string.Empty;
return Marshal.PtrToStringAnsi(ptr);
}
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int RegisterMessageCallback(
IntPtr consumer,
[MarshalAs(UnmanagedType.FunctionPtr)]
MessageCallBack pCallback
);
public delegate int MessageCallBack(IntPtr consumer, IntPtr messageIntPtr);
[DllImport(ConstValues.RocketMQDriverDllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int SetPushConsumerLogLevel(IntPtr consumer, CLogLevel level);
}
}
| apache-2.0 | C# | |
dd306666e893f5f94c0451cd6b770d86f5984a41 | Add some provider tests | CoraleStudios/Colore | src/Colore.Tests/ColoreProviderTests.cs | src/Colore.Tests/ColoreProviderTests.cs | // ---------------------------------------------------------------------------------------
// <copyright file="ColoreProviderTests.cs" company="Corale">
// Copyright © 2015-2019 by Adam Hellberg and Brandon Scott.
//
// 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.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Colore.Tests
{
using System.Threading.Tasks;
using Colore.Api;
using Colore.Data;
using Moq;
using NUnit.Framework;
[TestFixture]
public class ColoreProviderTests
{
private static readonly AppInfo TestAppInfo = new AppInfo(
"Colore TestApp",
"Mock app for running Colore tests",
"chroma-sdk",
"colore@sharparam.com",
Category.Application);
[Test]
public async Task ShouldCallUninitializeOnClear()
{
var apiMock = new Mock<IChromaApi>();
await ColoreProvider.CreateAsync(TestAppInfo, apiMock.Object);
await ColoreProvider.CreateAsync(TestAppInfo, apiMock.Object);
apiMock.Verify(a => a.UninitializeAsync(), Times.Once);
}
}
}
| mit | C# | |
033fc4b3d61f47c32828e636e1136c8cb6b9002c | Create IMarkdownViewEngine | hishamco/MarkdownViewEngine | src/MarkdownViewEngine/IMarkdownViewEngine.cs | src/MarkdownViewEngine/IMarkdownViewEngine.cs | using Microsoft.AspNetCore.Mvc.ViewEngines;
namespace MarkdownViewEngine
{
public interface IMarkdownViewEngine : IViewEngine
{
string GetAbsolutePath(string executingFilePath, string pagePath);
}
}
| mit | C# | |
309fe4a21cf48709c4310431afea7ebb7dd27cfb | Fix byte[] compare | k2workflow/Chasm,jannesrsa/Chasm,jcdickinson/Chasm | src/SourceCode.Chasm/Blob.cs | src/SourceCode.Chasm/Blob.cs | using SourceCode.Clay.Buffers;
using System;
namespace SourceCode.Chasm
{
public struct Blob : IEquatable<Blob>
{
#region Constants
public static Blob Empty { get; }
#endregion
#region Properties
public byte[] Data { get; }
#endregion
#region De/Constructors
public Blob(byte[] data)
{
Data = data;
}
public void Deconstruct(out byte[] data)
{
data = Data;
}
#endregion
#region IEquatable
public bool Equals(Blob other)
=> BufferComparer.Default.Equals(Data, other.Data); // Has null-handling logic
public override bool Equals(object obj)
=> obj is Blob blob
&& Equals(blob);
public override int GetHashCode()
=> Data.Length.GetHashCode();
public static bool operator ==(Blob x, Blob y) => x.Equals(y);
public static bool operator !=(Blob x, Blob y) => !x.Equals(y);
#endregion
#region Operators
public override string ToString()
=> $"{nameof(Blob)}: {Data?.Length ?? 0}";
#endregion
}
}
| using System;
namespace SourceCode.Chasm
{
public struct Blob : IEquatable<Blob>
{
#region Constants
public static Blob Empty { get; }
#endregion
#region Properties
public byte[] Data { get; }
#endregion
#region De/Constructors
public Blob(byte[] data)
{
Data = data;
}
public void Deconstruct(out byte[] data)
{
data = Data;
}
#endregion
#region IEquatable
public bool Equals(Blob other)
{
if (Data == null ^ other.Data == null) return false;
if (Data == null) return true;
if (Data.Length != other.Data.Length) return false;
switch (Data.Length)
{
case 0: return true;
case 1: return Data[0] == other.Data[0];
default:
{
for (var i = 0; i < Data.Length; i++)
if (Data[i] != other.Data[i])
return false;
return true;
}
}
}
public override bool Equals(object obj)
=> obj is Blob blob
&& Equals(blob);
public override int GetHashCode()
=> Data.Length.GetHashCode();
public static bool operator ==(Blob x, Blob y) => x.Equals(y);
public static bool operator !=(Blob x, Blob y) => !x.Equals(y);
#endregion
#region Operators
public override string ToString()
=> $"{nameof(Blob)}: {Data?.Length ?? 0}";
#endregion
}
}
| mit | C# |
e5ad7097623c77d945096ea421f422f66c5bdb92 | add new test's to redirect action | takenet/blip-sdk-csharp | src/Take.Blip.Builder.UnitTests/Actions/RedirectActionTests.cs | src/Take.Blip.Builder.UnitTests/Actions/RedirectActionTests.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NSubstitute;
using Serilog;
using Take.Blip.Builder.Actions.Redirect;
using Take.Blip.Builder.Actions.SetVariable;
using Xunit;
namespace Take.Blip.Builder.UnitTests.Actions
{
public class RedirectActionTests : ActionTestsBase
{
public RedirectActionTests()
{
RedirectManager = Substitute.For<IRedirectManager>();
Logger = Substitute.For<ILogger>();
}
//public SetVariableSettings Settings { get; }
private RedirectAction GetTarget()
{
return new RedirectAction(RedirectManager, Logger);
}
public ILogger Logger { get; }
public IRedirectManager RedirectManager { get; }
[Fact]
public async Task ExecuteShouldSuccess()
{
// Arrange
var target = GetTarget();
var redirect = new JObject();
redirect.Add("address", "bot1");
// Act
await target.ExecuteAsync(Context, redirect, CancellationToken);
// Assert
Context.Received(1);
}
[Fact]
public async Task ExecuteWithLogShouldSuccess()
{
// Arrange
var target = GetTarget();
var redirect = new JObject();
redirect.Add("address", "bot1");
Context.Input.Message.Metadata = new Dictionary<string, string> { { "REDIRECT_TEST_LOG", "bot1" } };
// Act
await target.ExecuteAsync(Context, redirect, CancellationToken);
// Assert
Context.Received(1);
}
[Fact]
public async Task ExecuteShouldFailure()
{
// Arrange
var target = GetTarget();
// Act
try
{
await target.ExecuteAsync(Context, null, CancellationToken);
}
catch (Exception e) {
Context.DidNotReceive();
}
}
}
} | apache-2.0 | C# | |
ed61975f3320d2341ed54337c1ac42d0ca6a8703 | Test project | themehrdad/NetTelebot,vertigra/NetTelebot-2.0 | NetTelebot.Tests/TestGetUpdates.cs | NetTelebot.Tests/TestGetUpdates.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NetTelebot.Tests
{
[TestClass]
public class TestGetUpdates
{
TelegramBotClient client;
[TestInitialize]
public void Initialize()
{
client = new TelegramBotClient()
{
Token = ""
};
}
[TestMethod]
public void TestExceptions()
{
client.GetUpdatesError += client_GetUpdatesError;
client.UpdatesReceived += client_UpdatesReceived;
client.StartCheckingUpdates();
var time = DateTime.Now.AddSeconds(10);
while (DateTime.Now < time)
{
}
}
void client_UpdatesReceived(object sender, TelegramUpdateEventArgs e)
{
Console.WriteLine("Updates received: {0}", e.Updates.Length);
}
void client_GetUpdatesError(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("Error occured: {0}", ((Exception)e.ExceptionObject).Message);
}
}
}
| mit | C# | |
7a6ed27bef998e815cab43870a1135c98033e61f | Remove unused method | FakeItEasy/FakeItEasy,blairconrad/FakeItEasy,thomaslevesque/FakeItEasy,thomaslevesque/FakeItEasy,adamralph/FakeItEasy,blairconrad/FakeItEasy,adamralph/FakeItEasy,FakeItEasy/FakeItEasy | src/FakeItEasy.Analyzer/DiagnosticDefinitions.cs | src/FakeItEasy.Analyzer/DiagnosticDefinitions.cs | namespace FakeItEasy.Analyzer
{
using Microsoft.CodeAnalysis;
internal static class DiagnosticDefinitions
{
public static DiagnosticDescriptor UnusedCallSpecification { get; } =
CreateDiagnosticDescriptor(
nameof(UnusedCallSpecification), "FakeItEasy0001", "FakeItEasy.Usage", DiagnosticSeverity.Error, true);
private static DiagnosticDescriptor CreateDiagnosticDescriptor(
string name, string id, string category, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault)
{
var title = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.Title));
var messageFormat = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.MessageFormat));
var description = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.Description));
return new DiagnosticDescriptor(id, title, messageFormat, category, defaultSeverity, isEnabledByDefault, description);
}
private static LocalizableResourceString GetDiagnosticResourceString(string name, string propertyName)
{
return new LocalizableResourceString(name + propertyName, Resources.ResourceManager, typeof(Resources));
}
}
}
| namespace FakeItEasy.Analyzer
{
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.CodeAnalysis;
internal static class DiagnosticDefinitions
{
public static DiagnosticDescriptor UnusedCallSpecification { get; } =
CreateDiagnosticDescriptor(
nameof(UnusedCallSpecification), "FakeItEasy0001", "FakeItEasy.Usage", DiagnosticSeverity.Error, true);
[SuppressMessage(
"Microsoft.Globalization",
"CA1305:SpecifyIFormatProvider",
MessageId = "System.String.Format(System.String,System.Object[])",
Justification = "Irrelevant in this case")]
public static ImmutableDictionary<string, DiagnosticDescriptor> GetDiagnosticsMap(params string[] diagnosticNames)
{
if (diagnosticNames == null)
{
throw new ArgumentNullException(nameof(diagnosticNames));
}
var builder = ImmutableDictionary.CreateBuilder<string, DiagnosticDescriptor>();
var typeInfo = typeof(DiagnosticDefinitions).GetTypeInfo();
foreach (var diagnosticName in diagnosticNames)
{
var property = typeInfo.GetDeclaredProperty(diagnosticName);
var descriptor = property?.GetValue(null) as DiagnosticDescriptor;
if (descriptor == null)
{
throw new ArgumentException($"There is no diagnostic named '{diagnosticName}'");
}
builder.Add(diagnosticName, descriptor);
}
return builder.ToImmutable();
}
private static DiagnosticDescriptor CreateDiagnosticDescriptor(
string name, string id, string category, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault)
{
var title = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.Title));
var messageFormat = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.MessageFormat));
var description = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.Description));
return new DiagnosticDescriptor(id, title, messageFormat, category, defaultSeverity, isEnabledByDefault, description);
}
private static LocalizableResourceString GetDiagnosticResourceString(string name, string propertyName)
{
return new LocalizableResourceString(name + propertyName, Resources.ResourceManager, typeof(Resources));
}
}
}
| mit | C# |
fd5459076e5033c4cef18c72d3481f712ce54988 | Add ControllerTypeMerger | folkelib/Folke.Mvc.Extensions | src/Folke.Mvc.Extensions/ControllerTypeMerger.cs | src/Folke.Mvc.Extensions/ControllerTypeMerger.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNet.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection;
namespace Folke.Mvc.Extensions
{
public class ControllerTypeMerger : IControllerTypeProvider
{
private readonly IServiceProvider serviceLocator;
public ControllerTypeMerger(IServiceProvider serviceLocator)
{
this.serviceLocator = serviceLocator;
}
public IEnumerable<TypeInfo> ControllerTypes
{
get
{
var providers = serviceLocator.GetServices<IControllerTypeProvider>();
foreach (var provider in providers)
{
if (provider is ControllerTypeMerger) continue;
foreach (var typeInfo in provider.ControllerTypes)
{
yield return typeInfo;
}
}
}
}
}
}
| mit | C# | |
633e1ed62cadbdc06592e19bbb1cfaa6fbae72b2 | Add missing ConsoleUtil from last commit | RavenB/opensim,TomDataworks/opensim,QuillLittlefeather/opensim-1,BogusCurry/arribasim-dev,rryk/omp-server,TomDataworks/opensim,BogusCurry/arribasim-dev,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip-tests,justinccdev/opensim,BogusCurry/arribasim-dev,TomDataworks/opensim,QuillLittlefeather/opensim-1,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,bravelittlescientist/opensim-performance,BogusCurry/arribasim-dev,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip,QuillLittlefeather/opensim-1,Michelle-Argus/ArribasimExtract,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-extras,rryk/omp-server,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip,OpenSimian/opensimulator,justinccdev/opensim,OpenSimian/opensimulator,rryk/omp-server,ft-/arribasim-dev-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/arribasim-dev-tests,ft-/opensim-optimizations-wip,OpenSimian/opensimulator,RavenB/opensim,M-O-S-E-S/opensim,Michelle-Argus/ArribasimExtract,justinccdev/opensim,bravelittlescientist/opensim-performance,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-tests,OpenSimian/opensimulator,Michelle-Argus/ArribasimExtract,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip-extras,OpenSimian/opensimulator,bravelittlescientist/opensim-performance,justinccdev/opensim,OpenSimian/opensimulator,ft-/arribasim-dev-extras,ft-/arribasim-dev-tests,TomDataworks/opensim,ft-/opensim-optimizations-wip-tests,BogusCurry/arribasim-dev,TomDataworks/opensim,QuillLittlefeather/opensim-1,TomDataworks/opensim,rryk/omp-server,RavenB/opensim,ft-/opensim-optimizations-wip-extras,justinccdev/opensim,M-O-S-E-S/opensim,ft-/arribasim-dev-tests,ft-/opensim-optimizations-wip-tests,QuillLittlefeather/opensim-1,ft-/arribasim-dev-extras,RavenB/opensim,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,Michelle-Argus/ArribasimExtract,Michelle-Argus/ArribasimExtract,BogusCurry/arribasim-dev,justinccdev/opensim,bravelittlescientist/opensim-performance,M-O-S-E-S/opensim,M-O-S-E-S/opensim,ft-/arribasim-dev-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip-extras,QuillLittlefeather/opensim-1,ft-/arribasim-dev-tests,rryk/omp-server,rryk/omp-server,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,RavenB/opensim | OpenSim/Framework/Console/ConsoleUtil.cs | OpenSim/Framework/Console/ConsoleUtil.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using log4net;
using OpenMetaverse;
public class ConsoleUtil
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const string MinRawConsoleVectorValue = "-~";
public const string MaxRawConsoleVectorValue = "~";
public const string VectorSeparator = ",";
public static char[] VectorSeparatorChars = VectorSeparator.ToCharArray();
/// <summary>
/// Convert a minimum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMinVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MinValue.ToString(), out vector);
}
/// <summary>
/// Convert a maximum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMaxVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MaxValue.ToString(), out vector);
}
/// <summary>
/// Convert a vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>
/// A string in the form <x>,<y>,<z> where there is no space between values.
/// Any component can be missing (e.g. ,,40). blankComponentFunc is invoked to replace the blank with a suitable value
/// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40,30 or 40)
/// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue
/// Other than that, component values must be numeric.
/// </param>
/// <param name='blankComponentFunc'></param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleVector(
string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector3 vector)
{
List<string> components = rawConsoleVector.Split(VectorSeparatorChars).ToList();
if (components.Count < 1 || components.Count > 3)
return false;
for (int i = components.Count; i < 3; i++)
components.Add("");
List<string> semiDigestedComponents
= components.ConvertAll<string>(
c =>
{
if (c == "")
return blankComponentFunc.Invoke(c);
else if (c == MaxRawConsoleVectorValue)
return float.MaxValue.ToString();
else if (c == MinRawConsoleVectorValue)
return float.MinValue.ToString();
else
return c;
});
string semiDigestedConsoleVector = string.Join(VectorSeparator, semiDigestedComponents.ToArray());
m_log.DebugFormat("[CONSOLE UTIL]: Parsing {0} into OpenMetaverse.Vector3", semiDigestedConsoleVector);
return Vector3.TryParse(semiDigestedConsoleVector, out vector);
}
} | bsd-3-clause | C# | |
f48e9679969842030b933fafb8b3958941432c17 | Create Problem134.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem134.cs | Problems/Problem134.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
namespace ProjectEuler.Problems
{
class Problem134
{
private static BigInteger CommonP1P2(long p1, long p2)
{
string p1Str = p1.ToString();
string p2str;
for (BigInteger i = 1; ; i++)
{
p2str = (p2 * i).ToString();
if (p2str.Substring(p2str.Length - p1Str.Length) == p1Str)
{
return p2*i;
}
}
}
private static BigInteger CommonP1P2N(long p1, long p2)
{
BigInteger p2i;
int p1Length = ((int)Math.Log10(p1)) + 1;
BigInteger p1size = BigInteger.Pow(10, p1Length);
for (BigInteger i = 1; ; i++)
{
p2i = p2 * i;
if ((p2i - p1) % p1size == 0)
{
return p2i;
}
}
}
public static void Run()
{
int upper = 1000000;
Sieve s = new Sieve(upper + (upper / 10));
BigInteger sum = 0;
DateTime start = DateTime.Now;
for (int p_index = 2; s.primeList[p_index] < upper; p_index++)
{
//Console.WriteLine("{0},{1}: {2}", s.primeList[p_index], s.primeList[p_index + 1], CommonP1P2(s.primeList[p_index], s.primeList[p_index + 1]));
sum += CommonP1P2N(s.primeList[p_index], s.primeList[p_index + 1]);
}
Console.WriteLine(sum);
Console.WriteLine("{0}ms", (DateTime.Now - start).TotalMilliseconds);
using (StreamWriter swr = new StreamWriter("Output/p134.txt", true))
{
swr.WriteLine("E 134: {0} minutes", (DateTime.Now - start).TotalMinutes);
swr.WriteLine(DateTime.Now);
swr.WriteLine(sum);
}
//Console.ReadLine();
}
}
}
| mit | C# | |
f9e2e808743403cafd862f1fd1177a1bc0f8b4f1 | Add testing for auto-restart behaviour | peppy/osu,peppy/osu-new,ppy/osu,smoogipooo/osu,ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu | osu.Game.Tests/Visual/Mods/TestSceneModFailCondition.cs | osu.Game.Tests/Visual/Mods/TestSceneModFailCondition.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.Linq;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Screens.Play;
namespace osu.Game.Tests.Visual.Mods
{
public class TestSceneModFailCondition : ModTestScene
{
private bool restartRequested;
protected override Ruleset CreatePlayerRuleset() => new OsuRuleset();
protected override TestPlayer CreateModPlayer(Ruleset ruleset)
{
var player = base.CreateModPlayer(ruleset);
player.RestartRequested = () => restartRequested = true;
return player;
}
protected override bool AllowFail => true;
[SetUpSteps]
public void SetUp()
{
AddStep("reset flag", () => restartRequested = false);
}
[Test]
public void TestRestartOnFailDisabled() => CreateModTest(new ModTestData
{
Autoplay = false,
Mod = new OsuModSuddenDeath(),
PassCondition = () => !restartRequested && Player.ChildrenOfType<FailOverlay>().Single().State.Value == Visibility.Visible
});
[Test]
public void TestRestartOnFailEnabled() => CreateModTest(new ModTestData
{
Autoplay = false,
Mod = new OsuModSuddenDeath
{
Restart = { Value = true }
},
PassCondition = () => restartRequested && Player.ChildrenOfType<FailOverlay>().Single().State.Value == Visibility.Hidden
});
}
}
| mit | C# | |
574a8b5c52097434d3bf8bbba3e392d903a9deeb | Create SNI.cs | imba-tjd/CSharp-Code-Repository | 单个文件的程序/SNI.cs | 单个文件的程序/SNI.cs | using System;
using System.Diagnostics;
class SNI
{
const string TargetIP = "104.131.212.184"; // 用于域前置的IP;community.notepad-plus-plus.org
const string NormalNCNHost = "usa.baidu.com"; // 用于检测TargetIP是否被封,必须用正常的域名
const string NormalCNHost = "www.baidu.com"; // 用于检测是否联网,可换成其它普通国内域名/IP
static int Main(string[] args)
{
#if DEBUG
args = new[] { "www.bbc.com" };
#endif
if (args.Length != 1)
throw new ArgumentException("Expect one and only one url.");
string host = new UriBuilder(args[0]).Host;
return new SNI().Run(host);
}
int Run(string requestedHost) =>
PingFailed(NormalCNHost) ? Log("Check your internet connection.", 3) :
HasSniRst(NormalNCNHost) ? Log("Cannot connect to target IP.", 2) :
HasSniRst(requestedHost) ? Log("Has SNI RST.", 1) :
Log("Not SNI RST.", 0);
bool HasSniRst(string host)
{
var psi = new ProcessStartInfo("curl", $"-I -sS --resolve {host}:443:{TargetIP} https://{host}")
{ UseShellExecute = false, RedirectStandardError = true };
var p = Process.Start(psi);
p.WaitForExit();
string result = p.StandardError.ReadToEnd();
return result.Contains("failed to receive handshake"); // 为false时并不意味着就没有SNI RST了
}
bool PingFailed(string host)
{
var p = Process.Start(
new ProcessStartInfo("ping", $"-{GetParam()} 2 {host}")
{ UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true }
);
p.WaitForExit();
return p.ExitCode != 0;
string GetParam() => // Win下是-n,Linux下是-c
Environment.OSVersion.Platform == PlatformID.Win32NT ? "n" : "c";
}
// 为了能在Run用三元表达式
int Log(string message, int returncode)
{
Console.WriteLine(message);
return returncode;
}
}
| mit | C# | |
c02b92fef3a9da24849515f3f3beb3781c1aefce | add missing file | esskar/Serialize.Linq | src/Serialize.Linq/Internals/ValueConverter.cs | src/Serialize.Linq/Internals/ValueConverter.cs | using System;
namespace Serialize.Linq.Internals
{
public static class ValueConverter
{
public static object Convert(object value, Type type)
{
if (value == null)
return type.IsValueType ? Activator.CreateInstance(type) : null;
if (type.IsInstanceOfType(value))
return value;
if (type.IsArray && value.GetType().IsArray)
{
var valArray = (Array)value;
var result = Array.CreateInstance(type.GetElementType(), valArray.Length);
for (var i = 0; i < valArray.Length; ++i)
result.SetValue(valArray.GetValue(i), i);
return result;
}
return Activator.CreateInstance(type, value);
}
}
}
| mit | C# | |
8e0536e1e2d2eb66a7572dcf27f19d65cb4f5e7c | Add failing test scene | smoogipoo/osu,peppy/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu | osu.Game.Tests/Visual/Editing/TestSceneBlueprintSelection.cs | osu.Game.Tests/Visual/Editing/TestSceneBlueprintSelection.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.Linq;
using NUnit.Framework;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Screens.Edit.Compose.Components;
using osu.Game.Tests.Beatmaps;
using osuTK;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Editing
{
public class TestSceneBlueprintSelection : EditorTestScene
{
protected override Ruleset CreateEditorRuleset() => new OsuRuleset();
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) => new TestBeatmap(ruleset, false);
private BlueprintContainer blueprintContainer
=> Editor.ChildrenOfType<BlueprintContainer>().First();
[Test]
public void TestSelectedObjectHasPriorityWhenOverlapping()
{
var firstSlider = new Slider
{
Path = new SliderPath(new[]
{
new PathControlPoint(new Vector2()),
new PathControlPoint(new Vector2(150, -50)),
new PathControlPoint(new Vector2(300, 0))
}),
Position = new Vector2(0, 100)
};
var secondSlider = new Slider
{
Path = new SliderPath(new[]
{
new PathControlPoint(new Vector2()),
new PathControlPoint(new Vector2(-50, 50)),
new PathControlPoint(new Vector2(-100, 100))
}),
Position = new Vector2(200, 0)
};
AddStep("add overlapping sliders", () =>
{
EditorBeatmap.Add(firstSlider);
EditorBeatmap.Add(secondSlider);
});
AddStep("select first slider", () => EditorBeatmap.SelectedHitObjects.Add(firstSlider));
AddStep("move mouse to common point", () =>
{
var pos = blueprintContainer.ChildrenOfType<PathControlPointPiece>().ElementAt(1).ScreenSpaceDrawQuad.Centre;
InputManager.MoveMouseTo(pos);
});
AddStep("right click", () => InputManager.Click(MouseButton.Right));
AddAssert("selection is unchanged", () => EditorBeatmap.SelectedHitObjects.Single() == firstSlider);
}
}
}
| mit | C# | |
85cd88e490b853b09260daf9693342380423ea49 | Create registry | ektrah/nsec | tests/Registry.cs | tests/Registry.cs | using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests
{
internal static class Registry
{
#region Algorithms By Base Class
public static readonly TheoryData<Type> AeadAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> AuthenticationAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> HashAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> KeyAgreementAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> KeyDerivationAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> PasswordHashAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> SignatureAlgorithms = new TheoryData<Type>
{
};
#endregion
#region Algorithms By Key Type
public static readonly TheoryData<Type> AsymmetricAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> SymmetricAlgorithms = new TheoryData<Type>
{
};
public static readonly TheoryData<Type> KeylessAlgorithms = new TheoryData<Type>
{
};
#endregion
#region Key Blob Formats
public static readonly TheoryData<Type, KeyBlobFormat> PublicKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
};
public static readonly TheoryData<Type, KeyBlobFormat> PrivateKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
};
public static readonly TheoryData<Type, KeyBlobFormat> SymmetricKeyBlobFormats = new TheoryData<Type, KeyBlobFormat>
{
};
#endregion
}
}
| mit | C# | |
b3899c1de9a398cbfdbd1e444b09fd3b34d8d48f | Add Create.cshtml page | Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog | SpaceBlog/SpaceBlog/Views/Home/Create.cshtml | SpaceBlog/SpaceBlog/Views/Home/Create.cshtml | @{
ViewBag.Title = "Create";
Layout = null;
}
<div class="container">
<h2>@ViewBag.Title</h2>
<div class="container body-content span=8 offset=2">
<form class="form-horizontal">
<fieldset>
<legend>New Post</legend>
<div class="form-group">
<label class="col-sm-4 control-label">Post Title</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="postTitle" placeholder="Post Title">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Author</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="postAuthor" placeholder="Author">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Content</label>
<div class="col-sm-6">
<textarea class="form-control" rows="5" id="postContent"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-4">
<input type="reset" class="btn btn-danger" onclick="location.href='#';" value="Cancel" />
<input type="reset" class="btn btn-primary" onclick="location.href='#';" value="Submit" />
</div>
</div>
</fieldset>
</form>
</div>
</div> | mit | C# | |
a3deb4ca626615291462c6b6bd2c240b720cb759 | add MSharpException | marihachi/MSharp | src/MSharp/Core/MSharpException.cs | src/MSharp/Core/MSharpException.cs | using System;
namespace MSharp.Core
{
/// <summary>
/// MSharpの全般的なエラーを表します。
/// </summary>
public class MSharpException : ApplicationException
{
public MSharpException(string message)
: base(message) { }
public MSharpException(string message, Exception innerException)
: base(message, innerException) { }
}
}
| mit | C# | |
ce67fd075972ba82cefb896c0a5185f7c9715898 | set scheme to default for default key values. | morkt/GARbro,morkt/GARbro,dsp2003/GARbro,dsp2003/GARbro,dsp2003/GARbro | ArcFormats/WidgetDPK.xaml.cs | ArcFormats/WidgetDPK.xaml.cs | using System.Windows.Controls;
using GameRes.Formats.Dac;
using GameRes.Formats.Properties;
namespace GameRes.Formats.GUI
{
/// <summary>
/// Interaction logic for WidgetDPK.xaml
/// </summary>
public partial class WidgetDPK : Grid
{
public WidgetDPK ()
{
InitializeComponent ();
var last_scheme = EncScheme.SelectedItem as DpkScheme;
if (null == last_scheme)
last_scheme = DpkOpener.KnownSchemes[0];
uint key1 = Settings.Default.DPKKey1;
uint key2 = Settings.Default.DPKKey2;
if (last_scheme.Key1 != key1 || last_scheme.Key2 != key2)
EncScheme.SelectedIndex = -1;
else if (null == EncScheme.SelectedItem)
EncScheme.SelectedIndex = 0;
Key1.Text = key1.ToString ("X");
Key2.Text = key2.ToString ("X8");
EncScheme.SelectionChanged += OnSchemeChanged;
}
void OnSchemeChanged (object sender, SelectionChangedEventArgs e)
{
var widget = sender as ComboBox;
var scheme = widget.SelectedItem as DpkScheme;
if (null != scheme)
{
Key1.Text = scheme.Key1.ToString ("X");
Key2.Text = scheme.Key2.ToString ("X8");
}
}
}
}
| using System.Windows.Controls;
using GameRes.Formats.Dac;
using GameRes.Formats.Properties;
namespace GameRes.Formats.GUI
{
/// <summary>
/// Interaction logic for WidgetDPK.xaml
/// </summary>
public partial class WidgetDPK : Grid
{
public WidgetDPK ()
{
InitializeComponent ();
var last_scheme = EncScheme.SelectedItem as DpkScheme;
if (null == last_scheme)
last_scheme = DpkOpener.KnownSchemes[0];
uint key1 = Settings.Default.DPKKey1;
uint key2 = Settings.Default.DPKKey2;
if (last_scheme.Key1 != key1 || last_scheme.Key2 != key2)
EncScheme.SelectedIndex = -1;
Key1.Text = key1.ToString ("X");
Key2.Text = key2.ToString ("X8");
EncScheme.SelectionChanged += OnSchemeChanged;
}
void OnSchemeChanged (object sender, SelectionChangedEventArgs e)
{
var widget = sender as ComboBox;
var scheme = widget.SelectedItem as DpkScheme;
if (null != scheme)
{
Key1.Text = scheme.Key1.ToString ("X");
Key2.Text = scheme.Key2.ToString ("X8");
}
}
}
}
| mit | C# |
fd961287d0cb70f5e4cedfbe12e7c797158874b1 | Add SingleCalloutSample | pauldendulk/Mapsui,charlenni/Mapsui,charlenni/Mapsui | Samples/Mapsui.Samples.Common/Maps/Callouts/SingleCalloutSample.cs | Samples/Mapsui.Samples.Common/Maps/Callouts/SingleCalloutSample.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Mapsui.Layers;
using Mapsui.Logging;
using Mapsui.Projection;
using Mapsui.Providers;
using Mapsui.Rendering.Skia;
using Mapsui.Styles;
using Mapsui.UI;
using Mapsui.Utilities;
using Mapsui.Widgets;
using Newtonsoft.Json;
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable once ClassNeverInstantiated.Local
namespace Mapsui.Samples.Common.Maps.Callouts
{
public class SingleCalloutSample : ISample
{
public string Name => "1 Simple Callout";
public string Category => "Info";
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.Centroid, map.Resolutions[5]);
map.Info += MapOnInfo;
return map;
}
private static void MapOnInfo(object sender, MapInfoEventArgs e)
{
var calloutStyle = e.MapInfo.Feature?.Styles.Where(s => s is CalloutStyle).Cast<CalloutStyle>().FirstOrDefault();
if (calloutStyle != null)
{
calloutStyle.Enabled = !calloutStyle.Enabled;
e.MapInfo.Layer.DataHasChanged(); // To trigger a refresh of graphics.
}
}
private static MemoryLayer CreatePointLayer()
{
return new MemoryLayer
{
Name = "Points",
IsMapInfoLayer = true,
DataSource = new MemoryProvider(GetCitiesFromEmbeddedResource()),
Style = new VectorStyle()
};
}
private static IEnumerable<IFeature> GetCitiesFromEmbeddedResource()
{
var path = "Mapsui.Samples.Common.EmbeddedResources.congo.json";
var assembly = typeof(PointsSample).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream(path);
var cities = DeserializeFromStream<City>(stream);
return cities.Select(c =>
{
var feature = new Feature();
var point = SphericalMercator.FromLonLat(c.Lng, c.Lat);
feature.Geometry = point;
feature["name"] = c.Name;
feature["country"] = c.Country;
var calloutStyle = CreateCalloutStyle(c.Name);
feature.Styles.Add(calloutStyle);
return feature;
});
}
private static CalloutStyle CreateCalloutStyle(string name)
{
return new CalloutStyle
{
Title = name,
Type = CalloutType.Single,
Content = -1,
TitleFont = { FontFamily = null, Size = 12, Italic = false, Bold = true },
TitleFontColor = Color.Gray,
TitleTextAlignment = Alignment.Center,
Spacing = 2,
MaxWidth = 111,
RectRadius = 10,
ShadowWidth = 4,
StrokeWidth = 0,
ArrowAlignment = ArrowAlignment.Bottom,
Offset = new Offset(SymbolStyle.DefaultHeight * 0.5f, 0),
RotateWithMap = true,
ArrowPosition = 1,
Enabled = true,
SymbolOffset = new Offset(-SymbolStyle.DefaultHeight * 0.5f, 0)
};
}
private class City
{
public string Country { get; set; }
public string Name { get; set; }
public double Lat { get; set; }
public double Lng { get; set; }
}
public static IEnumerable<T> DeserializeFromStream<T>(Stream stream)
{
var serializer = new JsonSerializer();
using var sr = new StreamReader(stream);
using var jsonTextReader = new JsonTextReader(sr);
return serializer.Deserialize<List<T>>(jsonTextReader);
}
}
} | mit | C# | |
6d14e91dd317399d87408690b97a41cf4cf28040 | Create MultipartFormDataExtension.cs | oceanho/MultipartFormData,Mr-hai/MultipartFormData | MultipartFormDataExtension.cs | MultipartFormDataExtension.cs | mit | C# | ||
1b62f9ebcb08c1953d4e72d382a9dd5e375b9a7a | Add HeapBase.IsBig property | modulexcite/dnlib,jorik041/dnlib,ilkerhalil/dnlib,kiootic/dnlib,0xd4d/dnlib,Arthur2e5/dnlib,yck1509/dnlib,ZixiangBoy/dnlib,picrap/dnlib | src/DotNet/Writer/HeapBase.cs | src/DotNet/Writer/HeapBase.cs | using System.IO;
using dot10.IO;
using dot10.PE;
namespace dot10.DotNet.Writer {
/// <summary>
/// Base class of most heaps
/// </summary>
public abstract class HeapBase : IHeap {
FileOffset offset;
RVA rva;
/// <inheritdoc/>
public FileOffset FileOffset {
get { return offset; }
}
/// <inheritdoc/>
public RVA RVA {
get { return rva; }
}
/// <inheritdoc/>
public abstract string Name { get; }
/// <inheritdoc/>
public bool IsEmpty {
get { return GetLength() <= 1; }
}
/// <summary>
/// <c>true</c> if offsets require 4 bytes instead of 2 bytes.
/// </summary>
public bool IsBig {
get { return GetLength() > 0xFFFF; }
}
/// <inheritdoc/>
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
}
/// <inheritdoc/>
public abstract uint GetLength();
/// <inheritdoc/>
public abstract void WriteTo(BinaryWriter writer);
/// <inheritdoc/>
public override string ToString() {
return Name;
}
}
}
| using System.IO;
using dot10.IO;
using dot10.PE;
namespace dot10.DotNet.Writer {
/// <summary>
/// Base class of most heaps
/// </summary>
public abstract class HeapBase : IHeap {
FileOffset offset;
RVA rva;
/// <inheritdoc/>
public FileOffset FileOffset {
get { return offset; }
}
/// <inheritdoc/>
public RVA RVA {
get { return rva; }
}
/// <inheritdoc/>
public abstract string Name { get; }
/// <inheritdoc/>
public bool IsEmpty {
get { return GetLength() <= 1; }
}
/// <inheritdoc/>
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
}
/// <inheritdoc/>
public abstract uint GetLength();
/// <inheritdoc/>
public abstract void WriteTo(BinaryWriter writer);
/// <inheritdoc/>
public override string ToString() {
return Name;
}
}
}
| mit | C# |
69fc32a09b6d955973d1f09732258ad63c91215a | Create MainWindow.xaml.cs | ewasow/learning-cs | MainWindow.xaml.cs | MainWindow.xaml.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MessParser
{
public class InputFile
{
public string inputPath;
public InputFile(string path)
{
this.inputPath = path;
}
}
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private void MenuItem_Exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
public void MenuItem_Open_Click(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFileDialog();
dialog.DefaultExt = ".txt";
dialog.Filter = "TXT Files (*.txt)|*.txt";
bool? result = dialog.ShowDialog();
if (result == true)
{
var filename = new InputFile(dialog.FileName);
var content = File.ReadAllText(filename.inputPath);
tbContent.Text = content;
MessParser.Properties.Settings.Default.LastFile = filename.inputPath;
MessParser.Properties.Settings.Default.Save();
}
}
private void MenuItem_About_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("ESO little project for mess files.", "About", MessageBoxButton.OK,
MessageBoxImage.Information);
}
private void MenuItem_Save_Click(object sender, RoutedEventArgs e)
{
//File.WriteAllText();
}
private void MenuItem_SaveAs_Click(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.DefaultExt = ".txt";
dialog.Filter = "TXT Files (*.txt)|*.txt";
if (dialog.ShowDialog() == true)
{
File.WriteAllText(dialog.FileName, tbContent.Text);
}
}
private void MenuItem_RecentFile_Click(object sender, RoutedEventArgs e)
{
var lastFile = MessParser.Properties.Settings.Default.LastFile;
if (lastFile == "(empty)")
{
return;
}
var content = File.ReadAllText(lastFile);
tbContent.Text = content;
}
}
}
| mit | C# | |
8d1c5a58fea3be02b97ee597aaae28816ac290b6 | Add UtcHelper with only a "Now" method | rapidcore/rapidcore,rapidcore/rapidcore | src/core/main/Globalization/UtcHelper.cs | src/core/main/Globalization/UtcHelper.cs | using System;
namespace RapidCore.Globalization
{
/// <summary>
/// Knows how to handle UTC.
/// </summary>
public class UtcHelper
{
/// <summary>
/// Get the current date and time in UTC
/// </summary>
public virtual DateTime Now()
{
return DateTime.UtcNow;
}
}
} | mit | C# | |
f8dfa99be7b2c30386562446326ed40daf3b65e8 | access point | AlejoJamC/invoper-cli | invoper-cli/Program.cs | invoper-cli/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace invoper_cli
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# | |
cf3bc2bb338d39c9f359d4326b9ddd2f8a76b917 | Add visual-only execution mode toggle test scene | ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ZLima12/osu-framework | osu.Framework.Tests/Visual/Platform/TestSceneExecutionModes.cs | osu.Framework.Tests/Visual/Platform/TestSceneExecutionModes.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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Platform;
namespace osu.Framework.Tests.Visual.Platform
{
[Ignore("This test does not cover correct GL context acquire/release when ran headless.")]
public class TestSceneExecutionModes : FrameworkTestScene
{
private Bindable<ExecutionMode> executionMode;
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager configManager)
{
executionMode = configManager.GetBindable<ExecutionMode>(FrameworkSetting.ExecutionMode);
}
[Test]
public void ToggleModeSmokeTest()
{
AddRepeatStep("toggle execution mode", () => executionMode.Value = executionMode.Value == ExecutionMode.MultiThreaded
? ExecutionMode.SingleThread
: ExecutionMode.MultiThreaded, 2);
}
}
}
| mit | C# | |
72742d31fa6aedd2da7802bc83084f6b58f89123 | Add abstract Effect class | axazeano/ImageEditor | ImageEditor/Effect.cs | ImageEditor/Effect.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageEditor
{
abstract class Effect
{
public String name;
private Bitmap prevImage;
private Bitmap newImage;
abstract public Bitmap apply(Bitmap image);
abstract public Bitmap reverse();
}
}
| mit | C# | |
765421264b374014b59ddf7308099f0d6a5206bd | Create a new diagram example | aspose-diagram/Aspose.Diagram-for-.NET,asposediagram/Aspose_Diagram_NET | Examples/CSharp/ProgrammersGuide/Load-Save-Convert/CreateNewVisio.cs | Examples/CSharp/ProgrammersGuide/Load-Save-Convert/CreateNewVisio.cs | using Aspose.Diagram;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharp.ProgrammersGuide.Load_Save_Convert
{
public class CreateNewVisio
{
public static void Run()
{
//ExStart:CreateNewVisio
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_LoadSaveConvert();
// initialize a Diagram class
Diagram diagram = new Diagram();
// save diagram in the VSDX format
diagram.Save(dataDir + "MyDiagram.vsdx", SaveFileFormat.VSDX);
//ExEnd:CreateNewVisio
}
}
}
| mit | C# | |
2025dd25f6041e276e9ecde6829d0c51a565fae5 | Add missing file BaseOutputStreamHandler.cs from recent commit e19defd | Michelle-Argus/ArribasimExtract,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,M-O-S-E-S/opensim,TomDataworks/opensim,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-tests,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-extras,RavenB/opensim,M-O-S-E-S/opensim,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,bravelittlescientist/opensim-performance,OpenSimian/opensimulator,TomDataworks/opensim,ft-/arribasim-dev-tests,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,bravelittlescientist/opensim-performance,M-O-S-E-S/opensim,justinccdev/opensim,Michelle-Argus/ArribasimExtract,justinccdev/opensim,ft-/arribasim-dev-extras,OpenSimian/opensimulator,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-extras,TomDataworks/opensim,RavenB/opensim,QuillLittlefeather/opensim-1,TomDataworks/opensim,ft-/arribasim-dev-extras,bravelittlescientist/opensim-performance,M-O-S-E-S/opensim,TomDataworks/opensim,Michelle-Argus/ArribasimExtract,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,justinccdev/opensim,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,Michelle-Argus/ArribasimExtract,BogusCurry/arribasim-dev,RavenB/opensim,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip,QuillLittlefeather/opensim-1,RavenB/opensim,ft-/opensim-optimizations-wip-tests,RavenB/opensim,ft-/arribasim-dev-tests,ft-/arribasim-dev-tests,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-extras,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,ft-/arribasim-dev-extras,OpenSimian/opensimulator,ft-/arribasim-dev-extras,TomDataworks/opensim,ft-/opensim-optimizations-wip-tests,QuillLittlefeather/opensim-1,justinccdev/opensim,bravelittlescientist/opensim-performance,justinccdev/opensim,ft-/opensim-optimizations-wip-extras,RavenB/opensim,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip,justinccdev/opensim,RavenB/opensim,QuillLittlefeather/opensim-1,ft-/arribasim-dev-tests,OpenSimian/opensimulator,Michelle-Argus/ArribasimExtract,BogusCurry/arribasim-dev,TomDataworks/opensim,ft-/opensim-optimizations-wip,OpenSimian/opensimulator,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1 | OpenSim/Framework/Servers/HttpServer/BaseOutputStreamHandler.cs | OpenSim/Framework/Servers/HttpServer/BaseOutputStreamHandler.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.IO;
namespace OpenSim.Framework.Servers.HttpServer
{
/// <summary>
/// Base handler for writing to an output stream
/// </summary>
/// <remarks>
/// Inheriting classes should override ProcessRequest() rather than Handle()
/// </remarks>
public abstract class BaseOutputStreamHandler : BaseRequestHandler, IRequestHandler
{
protected BaseOutputStreamHandler(string httpMethod, string path) : this(httpMethod, path, null, null) {}
protected BaseOutputStreamHandler(string httpMethod, string path, string name, string description)
: base(httpMethod, path, name, description) {}
public virtual void Handle(
string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
RequestsReceived++;
ProcessRequest(path, request, response, httpRequest, httpResponse);
RequestsHandled++;
}
protected virtual void ProcessRequest(
string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
}
}
} | bsd-3-clause | C# | |
ac8624c0bb2240d6de749116f2ea9045524c00ba | Create Anagram.cs | ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms | strings/string_fundamental/csharp/Anagram.cs | strings/string_fundamental/csharp/Anagram.cs | static void Main(string[] args)
{
Console.WriteLine(Anagram("Tom Marvolo Riddle", "I am Lord Voldemort"));
Console.ReadKey();
}
public static Boolean Anagram(String input1, String input2)
{
// Convert both inputs to lower case, and remove non-alphabetical characters
Regex rgx = new System.Text.RegularExpressions.Regex("[^a-z0-9]");
input1 = rgx.Replace(input1.ToLower(), "");
input2 = rgx.Replace(input2.ToLower(), "");
// Break both inputs down into character arrays
char[] process1 = input1.ToCharArray();
char[] process2 = input2.ToCharArray();
// Prepare two arrays to count ocurrences each letter of the alphabet in their respective inputs
int[] array1 = new int[26];
int[] array2 = new int[26];
// Count up the letters in the first input
for (int i = 0; i < input1.Length; i++)
{
int v = (int)process1[i] - 97;
array1[v]++;
}
// Count up the letters in the second input
for (int i = 0; i < input2.Length; i++)
{
array2[((int)process2[i])-97]++;
}
for (int i = 0; i < 26; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}
return true;
}
| cc0-1.0 | C# | |
fae5741c045865880cfa8637c9c267e7c063aaaa | Test fixed | kaffeebrauer/Lean,kaffeebrauer/Lean,redmeros/Lean,kaffeebrauer/Lean,redmeros/Lean,AnshulYADAV007/Lean,StefanoRaggi/Lean,AnshulYADAV007/Lean,QuantConnect/Lean,redmeros/Lean,StefanoRaggi/Lean,Jay-Jay-D/LeanSTP,jameschch/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,AlexCatarino/Lean,QuantConnect/Lean,Jay-Jay-D/LeanSTP,JKarathiya/Lean,AnshulYADAV007/Lean,AnshulYADAV007/Lean,QuantConnect/Lean,kaffeebrauer/Lean,QuantConnect/Lean,jameschch/Lean,kaffeebrauer/Lean,AlexCatarino/Lean,AlexCatarino/Lean,redmeros/Lean,StefanoRaggi/Lean,Jay-Jay-D/LeanSTP,JKarathiya/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,jameschch/Lean,JKarathiya/Lean,StefanoRaggi/Lean,JKarathiya/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,AnshulYADAV007/Lean | Tests/Indicators/MovingAverageConvergenceDivergenceTests.cs | Tests/Indicators/MovingAverageConvergenceDivergenceTests.cs | /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
using QuantConnect.Indicators;
using System;
namespace QuantConnect.Tests.Indicators
{
[TestFixture]
public class MovingAverageConvergenceDivergenceTests : CommonIndicatorTests<IndicatorDataPoint>
{
protected override IndicatorBase<IndicatorDataPoint> CreateIndicator()
{
return new MovingAverageConvergenceDivergence(12, 26, 9);
}
protected override string TestFileName => "spy_macd.csv";
protected override string TestColumnName => "MACD";
}
}
| /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
using QuantConnect.Indicators;
using System;
namespace QuantConnect.Tests.Indicators
{
[TestFixture]
public class MovingAverageConvergenceDivergenceTests : CommonIndicatorTests<IndicatorDataPoint>
{
protected override IndicatorBase<IndicatorDataPoint> CreateIndicator()
{
if (DateTime.Now < new DateTime(2018, 03, 01))
{
return new MovingAverageConvergenceDivergence(12, 26, 9, MovingAverageType.Exponential);
}
else
{
// This is a kind of reminder, if the default MovingAverageType is not changed by the 2018-03-01, then this test will fail.
return new MovingAverageConvergenceDivergence(12, 26, 9);
}
}
protected override string TestFileName => "spy_macd.csv";
protected override string TestColumnName => "MACD";
}
}
| apache-2.0 | C# |
b46c1d47797306340dccb9b599af1ade6fdee23f | Rename command (#6091) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/Mind/Commands/RenameCommand.cs | Content.Server/Mind/Commands/RenameCommand.cs | using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Content.Server.Access.Systems;
using Content.Server.Administration;
using Content.Server.Cloning;
using Content.Server.Mind.Components;
using Content.Server.PDA;
using Content.Shared.Access.Components;
using Content.Shared.Administration;
using Content.Shared.PDA;
using Robust.Server.Player;
using Robust.Shared.Console;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
namespace Content.Server.Mind.Commands;
[AdminCommand(AdminFlags.VarEdit)]
public class RenameCommand : IConsoleCommand
{
public string Command => "rename";
public string Description => "Renames an entity and its cloner entries, ID cards, and PDAs.";
public string Help => "rename <Username|EntityUid> <New character name>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length != 2)
{
shell.WriteLine(Help);
return;
}
var name = args[1];
if (name.Length > SharedIdCardConsoleComponent.MaxFullNameLength)
{
shell.WriteLine("Name is too long.");
return;
}
var entMan = IoCManager.Resolve<IEntityManager>();
if (!TryParseUid(args[0], shell, entMan, out var entityUid))
return;
// Metadata
var metadata = entMan.GetComponent<MetaDataComponent>(entityUid);
var oldName = metadata.EntityName;
metadata.EntityName = name;
var entSysMan = IoCManager.Resolve<IEntitySystemManager>();
if (entMan.TryGetComponent(entityUid, out MindComponent mind) && mind.Mind != null)
{
// Mind
mind.Mind.CharacterName = name;
// Cloner entries
if (entSysMan.TryGetEntitySystem<CloningSystem>(out var cloningSystem)
&& cloningSystem.MindToId.TryGetValue(mind.Mind, out var cloningId)
&& cloningSystem.IdToDNA.ContainsKey(cloningId))
{
cloningSystem.IdToDNA[cloningId] =
new ClonerDNAEntry(mind.Mind, cloningSystem.IdToDNA[cloningId].Profile.WithName(name));
}
}
// Id Cards
if (entSysMan.TryGetEntitySystem<IdCardSystem>(out var idCardSystem))
{
if (idCardSystem.TryFindIdCard(entityUid, out var idCard))
idCardSystem.TryChangeFullName(idCard.Owner, name, idCard);
else
{
foreach (var idCardComponent in entMan.EntityQuery<IdCardComponent>())
{
if (idCardComponent.OriginalOwnerName != oldName)
continue;
idCardSystem.TryChangeFullName(idCardComponent.Owner, name, idCardComponent);
}
}
}
// PDAs
if (entSysMan.TryGetEntitySystem<PDASystem>(out var pdaSystem))
{
foreach (var pdaComponent in entMan.EntityQuery<PDAComponent>())
{
if (pdaComponent.OwnerName != oldName)
continue;
pdaSystem.SetOwner(pdaComponent, name);
}
}
}
private static bool TryParseUid(string str, IConsoleShell shell,
IEntityManager entMan, out EntityUid entityUid)
{
if (EntityUid.TryParse(str, out entityUid) && entMan.EntityExists(entityUid))
return true;
var playerMan = IoCManager.Resolve<IPlayerManager>();
if (playerMan.TryGetSessionByUsername(str, out var session) && session.AttachedEntity.HasValue)
{
entityUid = session.AttachedEntity.Value;
return true;
}
if (session == null)
shell.WriteError("Can't find username/uid: " + str);
else
shell.WriteError(str + " does not have an entity.");
return false;
}
}
| mit | C# | |
70ca929d17cf6fd064eaa6af1dad9cd5bce66bef | create tests against test infrastructure | sqlkata/querybuilder | QueryBuilder.Tests/InfrastructureTests.cs | QueryBuilder.Tests/InfrastructureTests.cs | using System;
using System.Linq;
using SqlKata.Compilers;
using Xunit;
namespace SqlKata.Tests.Infrastructure
{
public class InfrastructureTests : TestSupport
{
[Fact]
public void CanGetCompiler()
{
var compiler = Compilers.Get(EngineCodes.SqlServer);
Assert.NotNull(compiler);
Assert.IsType<SqlServerCompiler>(compiler);
}
[Fact]
public void CanCompile()
{
var results = Compilers.Compile(new Query("Table"));
Assert.NotNull(results);
Assert.Equal(Compilers.KnownEngineCodes.Count(), results.Count);
}
[Fact]
public void CanCompileSelectively()
{
var desiredEngines = new[] {EngineCodes.SqlServer, EngineCodes.MySql};
var results = Compilers.Compile(desiredEngines, new Query("Table"));
Assert.Equal(desiredEngines.Length, results.Count);
Assert.Contains(results, a =>a.Key == EngineCodes.SqlServer);
Assert.Contains(results, a => a.Key == EngineCodes.MySql);
}
[Fact]
public void ShouldThrowIfInvalidEngineCode()
{
Assert.Throws<InvalidOperationException>(() => Compilers.CompileFor("XYZ", new Query()));
}
[Fact]
public void ShouldThrowIfAnyEngineCodesAreInvalid()
{
var codes = new[] {EngineCodes.SqlServer, "123", EngineCodes.MySql, "abc"};
Assert.Throws<InvalidOperationException>(() => Compilers.Compile(codes, new Query()));
}
}
} | mit | C# | |
4eac3848a15380b7c6dbac307ed200c222716e0d | Revert removal of MissingNamespaceId | reaction1989/roslyn,dpoeschl/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,davkean/roslyn,yeaicc/roslyn,jasonmalinowski/roslyn,orthoxerox/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,DustinCampbell/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ErikSchierboom/roslyn,AlekseyTs/roslyn,Giftednewt/roslyn,DustinCampbell/roslyn,panopticoncentral/roslyn,mgoertz-msft/roslyn,bbarry/roslyn,Hosch250/roslyn,vslsnap/roslyn,jmarolf/roslyn,jeffanders/roslyn,genlu/roslyn,stephentoub/roslyn,jcouv/roslyn,mmitche/roslyn,srivatsn/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,pdelvo/roslyn,wvdd007/roslyn,KevinRansom/roslyn,xasx/roslyn,orthoxerox/roslyn,mgoertz-msft/roslyn,paulvanbrenk/roslyn,physhi/roslyn,VSadov/roslyn,AnthonyDGreen/roslyn,physhi/roslyn,AArnott/roslyn,mattscheffer/roslyn,brettfo/roslyn,srivatsn/roslyn,jeffanders/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,MattWindsor91/roslyn,cston/roslyn,MattWindsor91/roslyn,akrisiun/roslyn,wvdd007/roslyn,jkotas/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,kelltrick/roslyn,CyrusNajmabadi/roslyn,zooba/roslyn,diryboy/roslyn,bartdesmet/roslyn,MattWindsor91/roslyn,akrisiun/roslyn,lorcanmooney/roslyn,cston/roslyn,mattwar/roslyn,OmarTawfik/roslyn,jeffanders/roslyn,xasx/roslyn,davkean/roslyn,physhi/roslyn,agocke/roslyn,mavasani/roslyn,jcouv/roslyn,weltkante/roslyn,agocke/roslyn,tannergooding/roslyn,dotnet/roslyn,bkoelman/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,jamesqo/roslyn,yeaicc/roslyn,jamesqo/roslyn,a-ctor/roslyn,nguerrera/roslyn,mattwar/roslyn,xoofx/roslyn,lorcanmooney/roslyn,wvdd007/roslyn,tvand7093/roslyn,abock/roslyn,agocke/roslyn,xoofx/roslyn,tmat/roslyn,KevinH-MS/roslyn,AArnott/roslyn,bkoelman/roslyn,AnthonyDGreen/roslyn,robinsedlaczek/roslyn,srivatsn/roslyn,jasonmalinowski/roslyn,genlu/roslyn,tvand7093/roslyn,CyrusNajmabadi/roslyn,zooba/roslyn,mmitche/roslyn,davkean/roslyn,robinsedlaczek/roslyn,tmat/roslyn,drognanar/roslyn,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,CaptainHayashi/roslyn,zooba/roslyn,bkoelman/roslyn,bbarry/roslyn,OmarTawfik/roslyn,gafter/roslyn,tannergooding/roslyn,VSadov/roslyn,reaction1989/roslyn,jmarolf/roslyn,jkotas/roslyn,a-ctor/roslyn,jkotas/roslyn,bartdesmet/roslyn,dpoeschl/roslyn,amcasey/roslyn,xasx/roslyn,khyperia/roslyn,lorcanmooney/roslyn,jamesqo/roslyn,xoofx/roslyn,CaptainHayashi/roslyn,brettfo/roslyn,genlu/roslyn,VSadov/roslyn,mattscheffer/roslyn,drognanar/roslyn,paulvanbrenk/roslyn,dpoeschl/roslyn,TyOverby/roslyn,MattWindsor91/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,MichalStrehovsky/roslyn,mattwar/roslyn,robinsedlaczek/roslyn,Hosch250/roslyn,a-ctor/roslyn,amcasey/roslyn,nguerrera/roslyn,sharwell/roslyn,aelij/roslyn,AnthonyDGreen/roslyn,DustinCampbell/roslyn,heejaechang/roslyn,mmitche/roslyn,paulvanbrenk/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,tmat/roslyn,aelij/roslyn,Hosch250/roslyn,jmarolf/roslyn,aelij/roslyn,brettfo/roslyn,abock/roslyn,heejaechang/roslyn,orthoxerox/roslyn,mgoertz-msft/roslyn,mattscheffer/roslyn,khyperia/roslyn,reaction1989/roslyn,khyperia/roslyn,AlekseyTs/roslyn,pdelvo/roslyn,eriawan/roslyn,dotnet/roslyn,yeaicc/roslyn,KevinRansom/roslyn,tmeschter/roslyn,sharwell/roslyn,weltkante/roslyn,gafter/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,kelltrick/roslyn,OmarTawfik/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,AArnott/roslyn,abock/roslyn,drognanar/roslyn,KevinH-MS/roslyn,cston/roslyn,Giftednewt/roslyn,nguerrera/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,kelltrick/roslyn,tvand7093/roslyn,CaptainHayashi/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,tmeschter/roslyn,Giftednewt/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,vslsnap/roslyn,TyOverby/roslyn,stephentoub/roslyn,akrisiun/roslyn,swaroop-sridhar/roslyn,diryboy/roslyn,vslsnap/roslyn,pdelvo/roslyn,gafter/roslyn,KevinH-MS/roslyn,amcasey/roslyn,TyOverby/roslyn,tmeschter/roslyn,jcouv/roslyn,AmadeusW/roslyn,eriawan/roslyn,bbarry/roslyn,mavasani/roslyn,ErikSchierboom/roslyn | src/VisualStudio/Xaml/Impl/Diagnostics/XamlDiagnosticIds.cs | src/VisualStudio/Xaml/Impl/Diagnostics/XamlDiagnosticIds.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Editor.Xaml.Diagnostics
{
internal static class XamlDiagnosticIds
{
public const string UnnecessaryNamespacesId = "XAML1103";
public const string MissingNamespaceId = "XAML0002";
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Editor.Xaml.Diagnostics
{
internal static class XamlDiagnosticIds
{
public const string UnnecessaryNamespacesId = "XAML1103";
}
}
| mit | C# |
397749887959537f2aa38739201d36fae3b80c74 | Add SmtpServer class to simplify server creation. | msoler8785/ExoMail | ExoMail.Smtp/Network/SmtpServer.cs | ExoMail.Smtp/Network/SmtpServer.cs | using ExoMail.Smtp.Extensions;
using ExoMail.Smtp.Interfaces;
using ExoMail.Smtp.Protocol;
using ExoMail.Smtp.Server.Authentication;
using ExoMail.Smtp.Services;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace ExoMail.Smtp.Network
{
public class SmtpServer
{
private IServerConfig _serverConfig { get; set; }
private IMessageStore _messageStore { get; set; }
private TcpListener _tcpListener { get; set; }
private CancellationToken _token { get; set; }
private List<ISaslMechanism> _saslMechanisms { get; set; }
public SmtpServer(IServerConfig serverConfig, IMessageStore messageStore)
{
this._serverConfig = serverConfig;
this._messageStore = messageStore;
this._saslMechanisms = new List<ISaslMechanism>();
}
public async Task StartAsync(CancellationToken token)
{
this._token = token;
this._tcpListener = new TcpListener(this._serverConfig.ServerIpBinding, this._serverConfig.Port);
this._tcpListener.Start();
this._saslMechanisms.Add(new LoginSaslMechanism());
TcpClient tcpClient;
while (!this._token.IsCancellationRequested)
{
tcpClient = await this._tcpListener.AcceptTcpClientAsync().WithCancellation(this._token);
CreateSession(tcpClient);
}
SessionManager.GetSessionManager.StopSessions();
}
private void CreateSession(TcpClient tcpClient)
{
Task.Run(async () =>
{
var session = new SmtpSession()
{
ServerConfig = this._serverConfig,
MessageStore = this._messageStore,
SaslMechanisms = this._saslMechanisms
};
try
{
SessionManager.GetSessionManager.SmtpSessions.Add(session);
await session.BeginSession(tcpClient);
}
finally
{
SessionManager.GetSessionManager.SmtpSessions.Remove(session);
}
});
}
}
} | mit | C# | |
4fab0eccbe3d3593785ab8c81c7fa3961b9f00f9 | Insert interval | Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews | LeetCode/remote/insert_interval.cs | LeetCode/remote/insert_interval.cs | // https://leetcode.com/problems/insert-interval/
//
// Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
//
// You may assume that the intervals were initially sorted according to their start times.
//
// Example 1:
// Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
//
// Example 2:
// Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
//
// This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
//
//
// Submission Details
// 151 / 151 test cases passed.
// Status: Accepted
// Runtime: 568 ms
//
// Submitted: 0 minutes ago
//
// 2 errors
// - IList fixed size (probably array)
// - Overlaps needs to be commutative
using System;
using System.Collections.Generic;
using System.Linq;
public class Interval {
public int start;
public int end;
public Interval() { start = 0; end = 0; }
public Interval(int s, int e) { start = s; end = e; }
public override String ToString()
{
return String.Format("[{0}, {1}] ", start, end);
}
}
public class Solution {
public static IList<Interval> Insert(IList<Interval> intervals, Interval newInterval) {
intervals = intervals.ToList();
intervals.Add(newInterval);
var result = new List<Interval>();
result.AddRange(intervals.Where(x => x.end < newInterval.start));
result.Add(intervals
.Where(x => Overlaps(x, newInterval) || Overlaps(newInterval, x))
.Aggregate(new Interval(int.MaxValue, int.MinValue),
(acc, x) => {
acc.start = Math.Min(acc.start, x.start);
acc.end = Math.Max(acc.end, x.end);
return acc;
}));
result.AddRange(intervals.Where(x => x.start > newInterval.end));
return result;
}
static bool Overlaps(Interval a, Interval b)
{
return b.start <= a.start && a.start <= b.end ||
b.start <= a.end && a.end <= b.end;
}
static void Main()
{
Console.WriteLine(String.Join(", ", Insert(new List<Interval> {
new Interval(1, 5)
}, new Interval(2, 3))));
Console.WriteLine(String.Join(", ", Insert(new List<Interval> {
new Interval(1, 3),
new Interval(6, 9)
}, new Interval(2, 5))));
Console.WriteLine(String.Join(", ", Insert(new List<Interval> {
new Interval(1, 2),
new Interval(3, 5),
new Interval(6, 7),
new Interval(8, 10),
new Interval(12, 16),
}, new Interval(4, 9))));
}
}
| mit | C# | |
4b9235831e1cf668ac91e1591bb05d69057aa9a8 | add ProductVariantService | vinhch/BizwebSharp | src/BizwebSharp/Services/ProductVariant/ProductVariantService.cs | src/BizwebSharp/Services/ProductVariant/ProductVariantService.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using BizwebSharp.Entities;
using BizwebSharp.Infrastructure;
using BizwebSharp.Options;
namespace BizwebSharp.Services
{
public class ProductVariantService : BaseServiceWithSimpleCRUD<ProductVariant, ListOption>
{
public ProductVariantService(BizwebAuthorizationState authState) : base(authState, "variant", "variants")
{
}
public virtual async Task<int> CountAsync(long productId, ListOption option = null)
{
return
await
MakeRequest<int>($"products/{productId}/{ApiClassPathInPlural}/count.json", HttpMethod.GET, "count",
option);
}
public virtual async Task<IEnumerable<ProductVariant>> ListAsync(long productId, ListOption option = null)
{
return
await
MakeRequest<List<ProductVariant>>($"products/{productId}/{ApiClassPathInPlural}.json",
HttpMethod.GET, ApiClassPathInPlural, option);
}
public virtual async Task<ProductVariant> CreateAsync(long productId, ProductVariant variant)
{
var root = new Dictionary<string, object>
{
{ApiClassPath, variant}
};
return
await
MakeRequest<ProductVariant>($"products/{productId}/{ApiClassPathInPlural}.json", HttpMethod.POST,
ApiClassPath, root);
}
public virtual async Task DeleteAsync(long productId, long variantId)
{
await MakeRequest($"products/{productId}/{ApiClassPathInPlural}/{variantId}.json", HttpMethod.DELETE);
}
}
}
| mit | C# | |
81d0b42930426bddb6793411ae9dce234fbd9c9f | Add failing test case | ppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu | osu.Game.Tests/NonVisual/Skinning/LegacySkinAnimationTest.cs | osu.Game.Tests/NonVisual/Skinning/LegacySkinAnimationTest.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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Animations;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Textures;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Audio;
using osu.Game.Skinning;
using osu.Game.Tests.Visual;
namespace osu.Game.Tests.NonVisual.Skinning
{
[HeadlessTest]
public class LegacySkinAnimationTest : OsuTestScene
{
private const string animation_name = "animation";
private const int frame_count = 6;
[Cached(typeof(IAnimationTimeReference))]
private TestAnimationTimeReference animationTimeReference = new TestAnimationTimeReference();
private TextureAnimation animation;
[Test]
public void TestAnimationTimeReferenceChange()
{
ISkin skin = new TestSkin();
AddStep("get animation", () => Add(animation = (TextureAnimation)skin.GetAnimation(animation_name, true, false)));
AddAssert("frame count correct", () => animation.FrameCount == frame_count);
assertPlaybackPosition(0);
AddStep("set start time to 1000", () => animationTimeReference.AnimationStartTime = 1000);
assertPlaybackPosition(-1000);
AddStep("set current time to 500", () => animationTimeReference.ManualClock.CurrentTime = 500);
assertPlaybackPosition(-500);
}
private void assertPlaybackPosition(double expectedPosition)
=> AddAssert($"playback position is {expectedPosition}", () => animation.PlaybackPosition == expectedPosition);
private class TestSkin : ISkin
{
private static readonly string[] lookup_names = Enumerable.Range(0, frame_count).Select(frame => $"{animation_name}-{frame}").ToArray();
public Texture GetTexture(string componentName, WrapMode wrapModeS, WrapMode wrapModeT)
{
return lookup_names.Contains(componentName) ? Texture.WhitePixel : null;
}
public Drawable GetDrawableComponent(ISkinComponent component) => throw new NotSupportedException();
public SampleChannel GetSample(ISampleInfo sampleInfo) => throw new NotSupportedException();
public IBindable<TValue> GetConfig<TLookup, TValue>(TLookup lookup) => throw new NotSupportedException();
}
private class TestAnimationTimeReference : IAnimationTimeReference
{
public ManualClock ManualClock { get; }
public IFrameBasedClock Clock { get; }
public double AnimationStartTime { get; set; }
public TestAnimationTimeReference()
{
ManualClock = new ManualClock();
Clock = new FramedClock(ManualClock);
}
}
}
}
| mit | C# | |
f8d357f9926e039a74336fc85348e0a5515f361e | Add UmbracoAuthorizedController | robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS | src/Umbraco.Web.Common/Controllers/UmbracoAuthorizedController.cs | src/Umbraco.Web.Common/Controllers/UmbracoAuthorizedController.cs | using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Cms.Web.Common.Filters;
namespace Umbraco.Cms.Web.Common.Controllers
{
/// <summary>
/// Provides a base class for backoffice authorized controllers.
/// </summary>
[Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)]
[DisableBrowserCache]
public abstract class UmbracoAuthorizedController : ControllerBase
{
}
}
| mit | C# | |
3fe4297cd808a4b55eda74e6987ddfc3b5def30a | Create Encrypt.cs | Anand1907/cordova-plugin-encrypt,Anand1907/cordova-plugin-encrypt | src/wp/Encrypt.cs | src/wp/Encrypt.cs | /*
MIT License
*/
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Info;
using System.IO.IsolatedStorage;
using System.Windows.Resources;
using System.IO;
using System.Diagnostics;
namespace WPCordovaClassLib.Cordova.Commands
{
public class Encrypt : BaseCommand
{
public void getKeyDetails(string notused)
{
string res = String.Format("\"getKey\":\"{0}\"",
this.platform);
res = "{" + res + "}";
//Debug.WriteLine("Result::" + res);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, res));
}
public string platform
{
get
{
return Environment.OSVersion.Platform.ToString();
}
}
}
}
| mit | C# | |
092d0f9b7678a075011029b3300a07b5d111f70f | add breadcrumb header test scene | NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu | osu.Game.Tests/Visual/UserInterface/TestSceneBreadcrumbControlHeader.cs | osu.Game.Tests/Visual/UserInterface/TestSceneBreadcrumbControlHeader.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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Overlays;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneBreadcrumbControlHeader : OsuTestScene
{
private static readonly string[] items = { "first", "second", "third", "fourth", "fifth" };
[Cached]
private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Red);
private TestHeader header;
[SetUp]
public void SetUp() => Schedule(() =>
{
Child = header = new TestHeader
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
};
});
[Test]
public void TestAddAndRemoveItem()
{
foreach (var item in items.Skip(1))
AddStep($"Add {item} item", () => header.AddItem(item));
foreach (var item in items.Reverse().SkipLast(3))
AddStep($"Remove {item} item", () => header.RemoveItem(item));
AddStep($"Clear item", () => header.ClearItem());
foreach (var item in items)
AddStep($"Add {item} item", () => header.AddItem(item));
foreach (var item in items)
AddStep($"Remove {item} item", () => header.RemoveItem(item));
}
private class TestHeader : BreadcrumbControlOverlayHeader
{
public TestHeader()
{
TabControl.AddItem(items[0]);
Current.Value = items[0];
}
public void AddItem(string value)
{
TabControl.AddItem(value);
Current.Value = TabControl.Items.LastOrDefault();
}
public void RemoveItem(string value)
{
TabControl.RemoveItem(value);
Current.Value = TabControl.Items.LastOrDefault();
}
public void ClearItem()
{
TabControl.Clear();
Current.Value = null;
}
protected override OverlayTitle CreateTitle() => new TestTitle();
}
private class TestTitle : OverlayTitle
{
public TestTitle()
{
Title = "Test Title";
}
}
}
}
| mit | C# | |
f466c636bef825822eb7510c63dd5798977e61ba | Add csharp 5.x rest/taskrouter/statistics | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets | rest/taskrouter/statistics/workflow/example-1/example-1.5.x.cs | rest/taskrouter/statistics/workflow/example-1/example-1.5.x.cs | // Download the twilio-csharp library from
// https://www.twilio.com/docs/libraries/csharp#installation
using Newtonsoft.Json.Linq;
using System;
using Twilio;
using Twilio.Rest.Taskrouter.V1.Workspace.Workflow;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
const string workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string workflowSid = "WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var stats = WorkflowStatisticsResource.Fetch(workspaceSid, workflowSid);
var cumulativeStats = JObject.FromObject(stats.Cumulative);
Console.WriteLine(cumulativeStats["avg_task_acceptance_time"]
.Value<DateTime>());
Console.WriteLine(cumulativeStats["tasks_entered"]
.Value<int>());
var taskByStatusStats = JObject.FromObject(stats.Realtime)["tasks_by_status"]
.Value<JObject>();
Console.WriteLine(taskByStatusStats["pending"].Value<int>());
Console.WriteLine(taskByStatusStats["assigned"].Value<int>());
}
}
| // Download the twilio-csharp library from
// https://www.twilio.com/docs/libraries/csharp#installation
using Newtonsoft.Json.Linq;
using System;
using Twilio;
using Twilio.Rest.Taskrouter.V1.Workspace.Workflow;
class Example
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/console
const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string authToken = "your_auth_token";
const string workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
const string WorkflowSid = "WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
TwilioClient.Init(accountSid, authToken);
var stats = WorkflowStatisticsResource.Fetch(workspaceSid, WorkflowSid);
var cumulativeStats = JObject.FromObject(stats.Cumulative);
Console.WriteLine(cumulativeStats["avg_task_acceptance_time"]
.Value<DateTime>());
Console.WriteLine(cumulativeStats["tasks_entered"]
.Value<int>());
var taskByStatusStats = JObject.FromObject(stats.Realtime)["tasks_by_status"]
.Value<JObject>();
Console.WriteLine(taskByStatusStats["pending"].Value<int>());
Console.WriteLine(taskByStatusStats["assigned"].Value<int>());
}
}
| mit | C# |
bfe97ce2150b653eff375ad032a069fe4cbdd032 | Create RoadsandLibraries.cs | shivkrthakur/HackerRankSolutions,shivkrthakur/HackerRankSolutions,shivkrthakur/HackerRankSolutions,shivkrthakur/HackerRankSolutions | Practice/AllDomains/Algorithms/GraphTheory/RoadsandLibraries.cs | Practice/AllDomains/Algorithms/GraphTheory/RoadsandLibraries.cs | mit | C# | ||
8559f589f234416977322fdfe43ca9a3aa6f51ea | Revert "Delete Program.cs" | wangzheng888520/CefSharp,wangzheng888520/CefSharp,wangzheng888520/CefSharp,wangzheng888520/CefSharp | CefSharp.WinForms.Example/Program.cs | CefSharp.WinForms.Example/Program.cs | // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows.Forms;
using CefSharp.Example;
using CefSharp.WinForms.Example.Minimal;
namespace CefSharp.WinForms.Example
{
public class Program
{
[STAThread]
public static void Main()
{
#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
{
MessageBox.Show("When running this Example outside of Visual Studio" +
"please make sure you compile in `Release` mode.", "Warning");
}
#endif
//坑爹呢 .NET4.5编译的项目啊 让XP怎么办呢?
//自己来编译源码吧 哎 又是C++
const bool multiThreadedMessageLoop = true;
CefExample.Init(false, multiThreadedMessageLoop: multiThreadedMessageLoop);
if(multiThreadedMessageLoop == false)
{
//http://magpcss.org/ceforum/apidocs3/projects/%28default%29/%28_globals%29.html#CefDoMessageLoopWork%28%29
//Perform a single iteration of CEF message loop processing.
//This function is used to integrate the CEF message loop into an existing application message loop.
//Care must be taken to balance performance against excessive CPU usage.
//This function should only be called on the main application thread and only if CefInitialize() is called with a CefSettings.multi_threaded_message_loop value of false.
//This function will not block.
Application.Idle += (s, e) => Cef.DoMessageLoopWork();
}
var browser = new BrowserForm();
//var browser = new SimpleBrowserForm();
//var browser = new TabulationDemoForm();
Application.Run(browser);
}
}
}
| bsd-3-clause | C# | |
2bf2bee0ecc04c1ae6ab0990a3e1de77314ea14f | Create DeltaCVVCPhonemizer.cs | stakira/OpenUtau,stakira/OpenUtau | OpenUtau.Plugin.Builtin/DeltaCVVCPhonemizer.cs | OpenUtau.Plugin.Builtin/DeltaCVVCPhonemizer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenUtau.Api;
namespace OpenUtau.Plugin.Builtin {
[Phonemizer("English CVVC Phonemizer", "EN CVVC", "nago")]
public class DeltaCVVCPhonemizer : SyllableBasedPhonemizer {
private readonly string[] vowels = "a,A,@,{,V,O,aU,aI,E,3,eI,I,i,oU,OI,U,u".Split(",");
private readonly string[] consonants = "b,tS,d,D,f,g,h,dZ,k,l,m,n,N,p,r,s,S,t,T,v,w,j,z,Z".Split(",");
private readonly Dictionary<string, string> dictionaryReplacements = ("AA=A;AA0=A;AA1=A;AA2=A;AE={;AE0={;AE1={;AE2={;AH=V;AH0=V;AH1=V"
+ "AH2=V;AO=O;AO0=O;AO1=O;AO2=O;AW=aU;AW0=aU;AW1=aU;AW2=aU;AY=aI;AY0=aI;AY1=aI;AY2=aI;B=b;CH=tS;D=d;DH=D;EH=E;EH0=E;EH1=E;EH2=E;ER=3"
+ "ER0=3;ER1=3;ER2=3;EY=eI;EY0=eI;EY1=eI;EY2=eI;F=f;G=g;HH=h;IH=I;IH0=I;IH1=I;IH2=I;IY=i;IY0=i;IY1=i;IY2=i;JH=dZ;K=k;L=l;M=m;N=n;NG=N"
+ "OW=oU;OW0=oU;OW1=oU;OW2=oU;OY=OI;OY0=OI;OY1=OI;OY2=OI;P=p;R=r;S=s;SH=S;T=t;TH=T;UH=U;UH0=U;UH1=U;UH2=U;UW=u;UW0=u;UW1=u;UW2=u;V=v"
+ "W=w;Y=j;Z=z;ZH=Z").Split(';')
.Select(entry => entry.Split('='))
.Where(parts => parts.Length == 2)
.Where(parts => parts[0] != parts[1])
.ToDictionary(parts => parts[0], parts => parts[1]);
protected override string[] GetVowels() => vowels;
protected override string[] GetConsonants() => consonants;
protected override string GetDictionaryName() => "cmudict-0_7b.txt";
protected override Dictionary<string, string> GetDictionaryPhonemesReplacement() => dictionaryReplacements;
protected override List<string> ProcessSyllable(Syllable syllable) {
string prevV = syllable.prevV;
string[] cc = syllable.cc;
string v = syllable.v;
string basePhoneme;
var phonemes = new List<string>();
if (syllable.IsStartingV) {
basePhoneme = $"- {v}";
}
else if (syllable.IsVV) {
basePhoneme = v;
}
else if (syllable.IsStartingCV) {
basePhoneme = $"- {cc.Last()}{v}";
for (var i = 0; i < cc.Length - 1; i++) {
phonemes.Add($"- {cc[i]}");
}
}
else { // VCV
if (cc.Length == 1) {
basePhoneme = $"{cc.Last()}{v}";
} else {
basePhoneme = $"- {cc.Last()}{v}";
}
}
phonemes.Add(basePhoneme);
return phonemes;
}
protected override List<string> ProcessEnding(Ending ending) {
string[] cc = ending.cc;
string v = ending.prevV;
var phonemes = new List<string>();
if (ending.IsEndingV) {
phonemes.Add($"{v} -");
}
else {
phonemes.Add($"{v} {cc[0]}-");
for (var i = 1; i < cc.Length; i++) {
var cr = $"{cc[i]} -";
phonemes.Add(HasOto(cr, ending.tone) ? cr : cc[i]);
}
}
return phonemes;
}
}
}
| mit | C# | |
646833a059991206691530888626748ce34e7501 | Add test scene | NeoAdonis/osu,UselessToucan/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,peppy/osu | osu.Game.Rulesets.Taiko.Tests/Skinning/TestSceneKiaiHitExplosion.cs | osu.Game.Rulesets.Taiko.Tests/Skinning/TestSceneKiaiHitExplosion.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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.UI;
namespace osu.Game.Rulesets.Taiko.Tests.Skinning
{
[TestFixture]
public class TestSceneKiaiHitExplosion : TaikoSkinnableTestScene
{
[Test]
public void TestKiaiHits()
{
AddStep("rim hit", () => SetContents(() => getContentFor(createHit(HitType.Rim))));
AddStep("centre hit", () => SetContents(() => getContentFor(createHit(HitType.Centre))));
}
private Drawable getContentFor(DrawableTestHit hit)
{
return new Container
{
RelativeSizeAxes = Axes.Both,
Child = new KiaiHitExplosion(hit, hit.HitObject.Type)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
}
};
}
private DrawableTestHit createHit(HitType type) => new DrawableTestHit(new Hit { StartTime = Time.Current, Type = type });
}
}
| mit | C# | |
9c708025b9a828e913aadf33f8cdca4370c69bbc | add IEnumerable extensions | wangkanai/Detection | src/Extensions/IEnumerableExtensions.cs | src/Extensions/IEnumerableExtensions.cs | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Wangkanai.Detection.Extensions
{
public static class IEnumerableExtensions
{
[DebuggerStepThrough]
public static bool IsNullOrEmpty<T>(this IEnumerable<T> list)
{
if (list is null) return true;
if (!list.Any()) return true;
return false;
}
[DebuggerStepThrough]
public static bool HasDuplicates<T, TProp>(this IEnumerable<T> list, Func<T, TProp> selector)
{
var duplicate = new HashSet<TProp>();
foreach (var t in list)
if (!duplicate.Add(selector(t))) return true;
return false;
}
}
}
| apache-2.0 | C# | |
339a89ab9bfaca241514a0e7eaa47d7dd846d93a | Add combine dictionary test. | AxeDotNet/AxePractice.CSharpViaTest | src/CSharpViaTest.Collections/40_CombineCaseInsensitiveDictionarys.cs | src/CSharpViaTest.Collections/40_CombineCaseInsensitiveDictionarys.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace CSharpViaTest.Collections
{
public class CombineCaseInsensitiveDictionarys
{
#region Please modifies the code to pass the test
static IDictionary<string, ISet<T>> Combine<T>(IDictionary<string, ISet<T>> first, IDictionary<string, ISet<T>> second)
{
throw new NotImplementedException();
}
#endregion
[Fact]
public void should_combine_dictionary_case_insensitively()
{
var first = new Dictionary<string, ISet<int>>
{
{"Nancy", new HashSet<int> {1, 2}},
{"nAncy", new HashSet<int> {2, 3, 4}},
{"Rebecca", new HashSet<int> {1, 2}}
};
var second = new Dictionary<string, ISet<int>>
{
{"NANCY", new HashSet<int> {1, 8}},
{"Sofia", new HashSet<int> {2, 9}}
};
IDictionary<string, ISet<int>> result = Combine(first, second);
Assert.Equal(3, result.Count);
Assert.Equal(new [] {1, 2, 3, 4, 8}, result["nancy"].OrderBy(item => item));
Assert.Equal(new [] {1, 2}, result["rebecca"].OrderBy(item => item));
Assert.Equal(new [] {2, 9}, result["sofia"].OrderBy(item => item));
}
}
} | mit | C# | |
4c2640bd23e8dd8ec6e6b42df8c1e4fb10801550 | create ObejctFactory for AutoFac DI | csyntax/BlogSystem | src/BlogSystem.Web/ObjectFactory.cs | src/BlogSystem.Web/ObjectFactory.cs | namespace BlogSystem.Web
{
using Autofac;
public class ObjectFactory
{
private static IContainer container = AutofacConfig.Container;
public static T GetInstance<T>() where T : class
{
using (var con = container.BeginLifetimeScope())
{
return con.Resolve<T>();
}
}
}
} | mit | C# | |
2ed1ab0142f4c6ee1222cba93c3e4b6a933a6565 | Create Program.cs | Zooloo2014/Download-Scheduler | TestApp/Program.cs | TestApp/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace NDM
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| mit | C# | |
07bdc70a188d8eb7afba7d5ed05ff44d02f776f3 | Add test class 'LoadInfoCarrierTest' | azabluda/InfoCarrier.Core | test/InfoCarrier.Core.EFCore.FunctionalTests/LoadInfoCarrierTest.cs | test/InfoCarrier.Core.EFCore.FunctionalTests/LoadInfoCarrierTest.cs | namespace InfoCarrier.Core.EFCore.FunctionalTests
{
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Specification.Tests;
public class LoadInfoCarrierTest
: LoadTestBase<TestStore, LoadInfoCarrierTest.LoadInfoCarrierFixture>
{
public LoadInfoCarrierTest(LoadInfoCarrierFixture fixture)
: base(fixture)
{
}
public class LoadInfoCarrierFixture : LoadFixtureBase
{
private readonly InfoCarrierInMemoryTestHelper<LoadContext> helper;
public LoadInfoCarrierFixture()
{
this.helper = InfoCarrierInMemoryTestHelper.Create(
this.OnModelCreating,
(opt, _) => new LoadContext(opt));
}
public override DbContext CreateContext(TestStore testStore)
=> this.helper.CreateInfoCarrierContext();
public override TestStore CreateTestStore()
=> this.helper.CreateTestStore(this.Seed);
}
}
}
| mit | C# | |
feccf302894df67bae6af2a160477bfd18f68478 | add interface for SupermarketsChain db context | DatabaseApp-Team-Linnaeus/DatabasesApp,DatabaseApp-Team-Linnaeus/DatabasesApp | SupermarketsChain/SupermarketsChain.Data/ISupermarketsChainDbContext.cs | SupermarketsChain/SupermarketsChain.Data/ISupermarketsChainDbContext.cs | namespace SupermarketsChain.Data.Contracts
{
public interface IVotingSystemDbContext
{
IDbSet<Poll> Polls { get; set; }
IDbSet<Vote> Votes { get; set; }
IDbSet<Question> Question { get; set; }
IDbSet<Answer> Answers { get; set; }
IDbSet<Candidate> Candidates { get; set; }
IDbSet<IdentificationCode> IdentificationCodes { get; set; }
IDbSet<TEntity> Set<TEntity>() where TEntity : class;
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
int SaveChanges();
}
} | mit | C# | |
239d468a66e3f37913f7944ee966384cbe975510 | Add test class with other attribute on method | PKRoma/refit | Refit.Tests/IFooWithOtherAttribute.cs | Refit.Tests/IFooWithOtherAttribute.cs | using System.ComponentModel;
using System.Threading.Tasks;
using Refit;
interface IFooWithOtherAttribute
{
[Get("/")]
Task GetRoot();
[DisplayName("/")]
Task PostRoot();
}
| mit | C# | |
e99d8f13c68981b481ed37fc27a8e4973459a72e | Write Kebab Casing Tests | WarpSpideR/SuitCase | SuitCase.Tests/KebabCasingHelpersTest.cs | SuitCase.Tests/KebabCasingHelpersTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace SuitCase.Tests
{
public class KebabCasingHelpersTest
{
public static IEnumerable<object[]> FromData
{
get
{
return new List<object[]>
{
new object[] { "some-simple-test-data", new [] { "some", "simple", "test", "data" } },
new object[] { "single", new [] { "single", } },
new object[] { "st-Ra-Nge-Cas-Ing", new [] { "st", "ra", "nge", "cas", "ing" } }
};
}
}
[Theory]
[MemberData("FromData")]
public void ConvertsFromCorrectly(string input, string[] expected)
{
CasingContext result = input.FromKebabCase();
List<string> terms = result.Terms.ToList();
Assert.Equal(terms.Count, expected.Length);
for (var i = 0; i < terms.Count; i++)
{
Assert.Equal(expected[i], terms[i]);
}
}
public static IEnumerable<object[]> ToData
{
get
{
return new List<object[]>
{
new object[] { new CasingContext(new[] { "some", "simple", "test", "data" }), "some-simple-test-data" },
new object[] { new CasingContext(new[] { "single" }), "single" },
new object[] { new CasingContext(new[] { "st", "ra", "nge", "cas", "ing" }), "st-ra-nge-cas-ing" }
};
}
}
[Theory]
[MemberData("ToData")]
public void ConvertsToCorrectly(CasingContext input, string expected)
{
string result = input.ToKebabCase();
Assert.Equal(expected, result);
}
}
}
| mit | C# | |
867249813eacd18691bdcb1e1d9c2240e27444aa | Create BuffAppliedPopup.cs | prrovoss/THUD | plugins/Prrovoss/BuffAppliedPopup.cs | plugins/Prrovoss/BuffAppliedPopup.cs | using System.Collections.Generic;
using System;
using System.Linq;
using Turbo.Plugins.Default;
namespace Turbo.Plugins.Prrovoss
{
public class BuffApplied : BasePlugin
{
public class Buff
{
public bool Displayed { get; set; }
public uint SNO { get; set; }
public int Icon { get; set; }
public string Name { get; set; }
public Buff(uint sno, int icon, string name)
{
this.SNO = sno;
this.Icon = icon;
this.Displayed = false;
this.Name = name;
}
}
public List<Buff> BuffsToWatch { get; set; }
public override void Load(IController hud)
{
base.Load(hud);
BuffsToWatch = new List<Buff>();
BuffsToWatch.Add(new Buff(402461, 2, "Occulus"));
BuffsToWatch.Add(new Buff(246562, 1, "Flying Dragon"));
}
public override void PaintWorld(WorldLayer layer)
{
foreach (Buff buff in BuffsToWatch)
{
if (Hud.Game.Me.Powers.BuffIsActive(buff.SNO, buff.Icon))
{
if (!buff.Displayed)
{
Hud.RunOnPlugin<PopupNotifications>(plugin =>
{
plugin.Show(buff.Name, "Buff activated", 3000, "So much power");
});
buff.Displayed = true;
}
}
else
{
buff.Displayed = false;
}
}
}
public BuffApplied()
{
Enabled = true;
}
}
}
| mit | C# | |
3bcf9e962c8279cf63ec05e6404ff63cc1507db7 | Test really committed. | FUSEEProjectTeam/JSIL,hach-que/JSIL,FUSEEProjectTeam/JSIL,hach-que/JSIL,iskiselev/JSIL,sq/JSIL,iskiselev/JSIL,FUSEEProjectTeam/JSIL,FUSEEProjectTeam/JSIL,sq/JSIL,sq/JSIL,hach-que/JSIL,hach-que/JSIL,FUSEEProjectTeam/JSIL,iskiselev/JSIL,sq/JSIL,hach-que/JSIL,sq/JSIL,iskiselev/JSIL,iskiselev/JSIL | Tests.DCE/DCETests/StripInterfaceImplementation.cs | Tests.DCE/DCETests/StripInterfaceImplementation.cs | using System;
public static class Program
{
public static void Main(string[] args)
{
ProcessIUsedInterface(new UsedType());
}
public static void ProcessIUsedInterface(IUsedInterface item)
{
item.Run();
}
}
public interface IUnUsedInterface
{ }
public interface IUsedInterface : IUnUsedInterface
{
void Run();
}
public class UsedType : IUsedInterface
{
public void Run()
{
Console.WriteLine("Run");
}
} | mit | C# | |
896601ccbcc1ae5a72ca96a769ce5cfbaef087fb | Annotate the test with ActiveIssue | nbarbettini/corefx,YoupHulsebos/corefx,weltkante/corefx,zhenlan/corefx,stephenmichaelf/corefx,mazong1123/corefx,gkhanna79/corefx,richlander/corefx,dotnet-bot/corefx,rjxby/corefx,fgreinacher/corefx,mmitche/corefx,weltkante/corefx,YoupHulsebos/corefx,tijoytom/corefx,YoupHulsebos/corefx,YoupHulsebos/corefx,jlin177/corefx,nbarbettini/corefx,seanshpark/corefx,nchikanov/corefx,zhenlan/corefx,tijoytom/corefx,cydhaselton/corefx,rjxby/corefx,axelheer/corefx,krk/corefx,twsouthwick/corefx,MaggieTsang/corefx,stephenmichaelf/corefx,lggomez/corefx,yizhang82/corefx,billwert/corefx,Petermarcu/corefx,nbarbettini/corefx,seanshpark/corefx,parjong/corefx,marksmeltzer/corefx,mmitche/corefx,Jiayili1/corefx,shimingsg/corefx,ptoonen/corefx,richlander/corefx,Ermiar/corefx,seanshpark/corefx,dhoehna/corefx,wtgodbe/corefx,MaggieTsang/corefx,stone-li/corefx,krk/corefx,krk/corefx,stephenmichaelf/corefx,richlander/corefx,twsouthwick/corefx,weltkante/corefx,stone-li/corefx,ericstj/corefx,tijoytom/corefx,nbarbettini/corefx,shimingsg/corefx,JosephTremoulet/corefx,lggomez/corefx,krytarowski/corefx,YoupHulsebos/corefx,ericstj/corefx,billwert/corefx,krytarowski/corefx,alexperovich/corefx,BrennanConroy/corefx,rubo/corefx,krytarowski/corefx,weltkante/corefx,ptoonen/corefx,richlander/corefx,stone-li/corefx,alexperovich/corefx,ptoonen/corefx,Jiayili1/corefx,yizhang82/corefx,ericstj/corefx,Ermiar/corefx,cydhaselton/corefx,Ermiar/corefx,dhoehna/corefx,mmitche/corefx,ravimeda/corefx,ViktorHofer/corefx,billwert/corefx,ViktorHofer/corefx,elijah6/corefx,fgreinacher/corefx,stone-li/corefx,zhenlan/corefx,DnlHarvey/corefx,dhoehna/corefx,DnlHarvey/corefx,rahku/corefx,ViktorHofer/corefx,axelheer/corefx,nchikanov/corefx,the-dwyer/corefx,rubo/corefx,lggomez/corefx,ravimeda/corefx,alexperovich/corefx,ravimeda/corefx,rubo/corefx,zhenlan/corefx,cydhaselton/corefx,krytarowski/corefx,rjxby/corefx,rahku/corefx,cydhaselton/corefx,shimingsg/corefx,ravimeda/corefx,nchikanov/corefx,ViktorHofer/corefx,twsouthwick/corefx,DnlHarvey/corefx,gkhanna79/corefx,krk/corefx,lggomez/corefx,zhenlan/corefx,Petermarcu/corefx,alexperovich/corefx,DnlHarvey/corefx,mazong1123/corefx,the-dwyer/corefx,gkhanna79/corefx,ptoonen/corefx,rjxby/corefx,wtgodbe/corefx,tijoytom/corefx,Jiayili1/corefx,krk/corefx,nchikanov/corefx,nchikanov/corefx,jlin177/corefx,rjxby/corefx,weltkante/corefx,Jiayili1/corefx,marksmeltzer/corefx,JosephTremoulet/corefx,richlander/corefx,mazong1123/corefx,dotnet-bot/corefx,Petermarcu/corefx,Ermiar/corefx,MaggieTsang/corefx,wtgodbe/corefx,Petermarcu/corefx,krk/corefx,shimingsg/corefx,the-dwyer/corefx,MaggieTsang/corefx,seanshpark/corefx,yizhang82/corefx,the-dwyer/corefx,parjong/corefx,DnlHarvey/corefx,rahku/corefx,rjxby/corefx,axelheer/corefx,MaggieTsang/corefx,billwert/corefx,wtgodbe/corefx,fgreinacher/corefx,wtgodbe/corefx,YoupHulsebos/corefx,elijah6/corefx,jlin177/corefx,lggomez/corefx,gkhanna79/corefx,BrennanConroy/corefx,parjong/corefx,nbarbettini/corefx,mmitche/corefx,stephenmichaelf/corefx,dotnet-bot/corefx,zhenlan/corefx,rahku/corefx,ravimeda/corefx,krytarowski/corefx,gkhanna79/corefx,shimingsg/corefx,elijah6/corefx,weltkante/corefx,Jiayili1/corefx,billwert/corefx,twsouthwick/corefx,Petermarcu/corefx,tijoytom/corefx,parjong/corefx,jlin177/corefx,stephenmichaelf/corefx,mazong1123/corefx,nbarbettini/corefx,Ermiar/corefx,ericstj/corefx,wtgodbe/corefx,dotnet-bot/corefx,rubo/corefx,dhoehna/corefx,lggomez/corefx,tijoytom/corefx,elijah6/corefx,ericstj/corefx,jlin177/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,stone-li/corefx,dotnet-bot/corefx,mazong1123/corefx,marksmeltzer/corefx,parjong/corefx,the-dwyer/corefx,yizhang82/corefx,JosephTremoulet/corefx,elijah6/corefx,ericstj/corefx,DnlHarvey/corefx,parjong/corefx,dotnet-bot/corefx,stone-li/corefx,krytarowski/corefx,twsouthwick/corefx,seanshpark/corefx,richlander/corefx,ravimeda/corefx,krytarowski/corefx,the-dwyer/corefx,parjong/corefx,gkhanna79/corefx,ViktorHofer/corefx,weltkante/corefx,mazong1123/corefx,cydhaselton/corefx,dhoehna/corefx,twsouthwick/corefx,shimingsg/corefx,rahku/corefx,nchikanov/corefx,gkhanna79/corefx,dhoehna/corefx,JosephTremoulet/corefx,Petermarcu/corefx,marksmeltzer/corefx,Jiayili1/corefx,mmitche/corefx,Petermarcu/corefx,nchikanov/corefx,ericstj/corefx,MaggieTsang/corefx,ptoonen/corefx,stone-li/corefx,rjxby/corefx,alexperovich/corefx,axelheer/corefx,richlander/corefx,alexperovich/corefx,jlin177/corefx,zhenlan/corefx,ravimeda/corefx,Ermiar/corefx,Jiayili1/corefx,rahku/corefx,rahku/corefx,yizhang82/corefx,stephenmichaelf/corefx,stephenmichaelf/corefx,krk/corefx,JosephTremoulet/corefx,yizhang82/corefx,billwert/corefx,rubo/corefx,seanshpark/corefx,ptoonen/corefx,fgreinacher/corefx,jlin177/corefx,mmitche/corefx,dotnet-bot/corefx,lggomez/corefx,nbarbettini/corefx,elijah6/corefx,billwert/corefx,axelheer/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,yizhang82/corefx,seanshpark/corefx,mmitche/corefx,DnlHarvey/corefx,marksmeltzer/corefx,marksmeltzer/corefx,MaggieTsang/corefx,ViktorHofer/corefx,BrennanConroy/corefx,cydhaselton/corefx,axelheer/corefx,elijah6/corefx,dhoehna/corefx,Ermiar/corefx,wtgodbe/corefx,tijoytom/corefx,shimingsg/corefx,alexperovich/corefx,ptoonen/corefx,cydhaselton/corefx,marksmeltzer/corefx,twsouthwick/corefx,the-dwyer/corefx,mazong1123/corefx | src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.cs | src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionTest.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 Xunit;
namespace System.Data.SqlClient.Tests
{
public class SqlConnectionBasicTests
{
[Fact]
[ActiveIssue(14017)]
public void ConnectionTest()
{
Exception e = null;
using (TestTdsServer server = TestTdsServer.StartTestServer())
{
try
{
SqlConnection connection = new SqlConnection(server.ConnectionString);
connection.Open();
}
catch (Exception ce)
{
e = ce;
}
}
Assert.Null(e);
}
}
}
| // 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 Xunit;
namespace System.Data.SqlClient.Tests
{
public class SqlConnectionBasicTests
{
[Fact]
public void ConnectionTest()
{
Exception e = null;
using (TestTdsServer server = TestTdsServer.StartTestServer())
{
try
{
SqlConnection connection = new SqlConnection(server.ConnectionString);
connection.Open();
}
catch (Exception ce)
{
e = ce;
}
}
Assert.Null(e);
}
}
}
| mit | C# |
b873c4e49614f6cbde69d3f7fd65bca50ddb1a61 | add BuildEmscripten task | lriki/Lumino,lriki/Lumino,lriki/Lumino,lriki/Lumino,lriki/Lumino,lriki/Lumino,lriki/Lumino | tools/LuminoBuild/Tasks/BuildEmscripten.cs | tools/LuminoBuild/Tasks/BuildEmscripten.cs | using System;
using System.Collections.Generic;
using System.IO;
namespace LuminoBuild.Tasks
{
class BuildEmscripten : BuildTask
{
public override string CommandName { get { return "BuildEmscripten"; } }
public override string Description { get { return "Build Emscripten"; } }
public override void Build(Builder builder)
{
string emRootDir = Environment.GetEnvironmentVariable("EMSCRIPTEN");
string emInstallDir = Path.GetDirectoryName(Path.GetDirectoryName(emRootDir));
string bundlePythonDir = Path.Combine(emInstallDir, "python", "2.7.5.3_64bit");
string emcmake = Path.Combine(emRootDir, Utils.IsWin32 ? "emcmake.bat" : "emcmake");
string path = Environment.GetEnvironmentVariable("PATH");
path = bundlePythonDir + ";" + path;
var environmentVariables = new Dictionary<string, string>()
{
{ "PATH", path }
};
string buildDir = Path.Combine(builder.LuminoBuildDir, "Emscripten");
Directory.CreateDirectory(buildDir);
Directory.SetCurrentDirectory(buildDir);
Utils.CallProcess(emcmake, $"cmake {builder.LuminoRootDir} -G \"MinGW Makefiles\"", environmentVariables);
Utils.CallProcess("cmake", $"--build {buildDir}", environmentVariables);
}
}
}
| mit | C# | |
c6a7f48382a07ea58af2349e7dc8f4d79dd91efd | Add class to load client in private load context. | sharpjs/PSql,sharpjs/PSql | PSql/_Utilities/PSqlClient.cs | PSql/_Utilities/PSqlClient.cs | /*
Copyright 2020 Jeffrey Sharp
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System;
using System.Reflection;
using System.Runtime.Loader;
using Path = System.IO.Path;
#nullable enable
namespace PSql
{
internal static class PSqlClient
{
private const string
AssemblyPath = "PSql.Client.dll";
private static string LoadPath { get; }
private static AssemblyLoadContext LoadContext { get; }
private static Assembly Assembly { get; }
static PSqlClient()
{
LoadPath
= Path.GetDirectoryName(typeof(PSqlClient).Assembly.Location)
?? Environment.CurrentDirectory;
LoadContext = new AssemblyLoadContext(nameof(PSqlClient));
LoadContext.Resolving += OnResolving;
Assembly = LoadAssembly(AssemblyPath);
}
internal static dynamic CreateObject(string typeName, params object?[]? arguments)
{
// NULLS: CreateInstance returns null only for valueless instances
// of Nullable<T>, which cannot happen here.
return Activator.CreateInstance(GetType(typeName), arguments)!;
}
internal static Type GetType(string name)
{
// NULLS: Does not return null when trowOnError is true.
return Assembly.GetType(nameof(PSql) + "." + name, throwOnError: true)!;
}
private static Assembly? OnResolving(AssemblyLoadContext context, AssemblyName name)
{
var path = name.Name;
if (string.IsNullOrEmpty(path))
return null;
if (!HasAssemblyExtension(path))
path += ".dll";
return LoadAssembly(context, path);
}
private static Assembly LoadAssembly(string path)
{
return LoadAssembly(LoadContext, path);
}
private static Assembly LoadAssembly(AssemblyLoadContext context, string path)
{
path = Path.Combine(LoadPath, path);
return context.LoadFromAssemblyPath(path);
}
private static bool HasAssemblyExtension(string path)
{
return path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
|| path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase);
}
}
}
| isc | C# | |
3007a59eeca4041473e98fe4abcd53b2effebd49 | Update TODO | llytvynenko/Orleankka,pkese/Orleankka,yevhen/Orleankka,yevhen/Orleankka,OrleansContrib/Orleankka,mhertis/Orleankka,AntyaDev/Orleankka,mhertis/Orleankka,llytvynenko/Orleankka,ElanHasson/Orleankka,OrleansContrib/Orleankka,pkese/Orleankka,AntyaDev/Orleankka,ElanHasson/Orleankka | Source/Orleankka.Tests/TODO.cs | Source/Orleankka.Tests/TODO.cs | using System;
using System.Linq;
using NUnit.Framework;
namespace Orleankka
{
[TestFixture]
public class TodoFixture
{
[Test, Ignore]
public void Envelopes()
{
// - Envelope and Body attributte
// - Proper selection of Receive channel based on Body type
// - Proper dispatching based on Body type
}
[Test, Ignore]
public void Serialization()
{
// - Add support for native Orleans serializer
}
[Test, Ignore]
public void AutomaticDeactivation()
{
// - Add support for per-type idle deactivation timeouts
}
[Test, Ignore]
public void AzureSystem()
{
// - Finish actor system configuration
}
[Test, Ignore]
public void ActorPrototype()
{
// - Allow to override automatic handler wire-up
// - Prototype extensibility?
}
[Test, Ignore]
public void Samples()
{
// - Add DI container sample (Unity)
// - Add ProtoBuf/Bond serialization sample
// - Add Azure CloudService sample
}
[Test, Ignore]
public void Messages()
{
// - Add support (deep-copy) for mutable (yay) messages
// - Support weak (naming convention) attribute definition,
// to remove dependency on Orleankka from message contract lib ???
}
}
}
| using System;
using System.Linq;
using NUnit.Framework;
namespace Orleankka
{
[TestFixture]
public class TodoFixture
{
[Test, Ignore]
public void Envelopes()
{
// - Envelope and Body attributte
// - Proper selection of Receive channel based on Body type
// - Proper dispatching in TypeActor based on Body type
}
[Test, Ignore]
public void Serialization()
{
// - Add support for native Orleans serializer
}
[Test, Ignore]
public void AutomaticDeactivation()
{
// - Add support for per-type idle deactivation timeouts
}
[Test, Ignore]
public void AzureSystem()
{
// - Finish actor system configuration
}
[Test, Ignore]
public void ActorPrototype()
{
// - Allow to override automatic handler wire-up
// - Allow to specify reentrant message types, via lambda
// - Prototype extensibility?
}
[Test, Ignore]
public void Samples()
{
// - Add DI container sample (Unity)
// - Add ProtoBuf/Bond serialization sample
// - Add Azure CloudService sample
}
[Test, Ignore]
public void Messages()
{
// - Add support (deep-copy) for mutable (yay) messages
// - Support weak (naming convention) attribute definition,
// to remove dependency on Orleankka from message contract lib ???
}
}
}
| apache-2.0 | C# |
ae08d00e80f1e1e8c13c05873282f3d2aaf3c22c | Fix test mock | karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS | src/Host/Client/Test/Mocks/RSessionProviderMock.cs | src/Host/Client/Test/Mocks/RSessionProviderMock.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.R.Host.Client.Host;
using Microsoft.R.Host.Client.Test.Mocks;
namespace Microsoft.R.Host.Client.Mocks {
public sealed class RSessionProviderMock : IRSessionProvider {
private readonly Dictionary<Guid, IRSession> _sessions = new Dictionary<Guid, IRSession>();
public void Dispose() { }
public event EventHandler BrokerChanging;
public event EventHandler BrokerChangeFailed;
public event EventHandler BrokerChanged;
public IBrokerClient Broker { get; } = new NullBrokerClient();
public IRSession GetOrCreate(Guid guid) {
IRSession session;
if (!_sessions.TryGetValue(guid, out session)) {
session = new RSessionMock();
_sessions[guid] = session;
}
return session;
}
public IEnumerable<IRSession> GetSessions() {
return _sessions.Values;
}
public Task<IRSessionEvaluation> BeginEvaluationAsync(RHostStartupInfo startupInfo, CancellationToken cancellationToken = new CancellationToken())
=> new RSessionMock().BeginEvaluationAsync(cancellationToken);
public Task<bool> TestBrokerConnectionAsync(string name, string path) => Task.FromResult(true);
public Task<bool> TrySwitchBrokerAsync(string name, string path = null) {
return Task.FromResult(true);
}
public void DisplayBrokerInformation() { }
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.R.Host.Client.Host;
using Microsoft.R.Host.Client.Test.Mocks;
namespace Microsoft.R.Host.Client.Mocks {
public sealed class RSessionProviderMock : IRSessionProvider {
private readonly Dictionary<Guid, IRSession> _sessions = new Dictionary<Guid, IRSession>();
public void Dispose() { }
public event EventHandler BrokerChanged;
public IBrokerClient Broker { get; } = new NullBrokerClient();
public IRSession GetOrCreate(Guid guid) {
IRSession session;
if (!_sessions.TryGetValue(guid, out session)) {
session = new RSessionMock();
_sessions[guid] = session;
}
return session;
}
public IEnumerable<IRSession> GetSessions() {
return _sessions.Values;
}
public Task<IRSessionEvaluation> BeginEvaluationAsync(RHostStartupInfo startupInfo, CancellationToken cancellationToken = new CancellationToken())
=> new RSessionMock().BeginEvaluationAsync(cancellationToken);
public Task<bool> TestBrokerConnectionAsync(string name, string path) => Task.FromResult(true);
public Task<bool> TrySwitchBrokerAsync(string name, string path = null) {
return Task.FromResult(true);
}
public void DisplayBrokerInformation() { }
}
}
| mit | C# |
c582b47de1c98d4302874182813ea948f397550f | Add user service | Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife | PhotoLife/PhotoLife.Services/UserService.cs | PhotoLife/PhotoLife.Services/UserService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PhotoLife.Data.Contracts;
using PhotoLife.Models;
using PhotoLife.Services.Contracts;
namespace PhotoLife.Services
{
public class UserService : IUserService
{
private readonly IRepository<User> userRepository;
private readonly IUnitOfWork unitOfWork;
public UserService(
IRepository<User> userRepository,
IUnitOfWork unitOfWork)
{
if (userRepository == null)
{
throw new ArgumentNullException(nameof(userRepository));
}
if (unitOfWork == null)
{
throw new ArgumentNullException(nameof(userRepository));
}
this.userRepository = userRepository;
this.unitOfWork = unitOfWork;
}
public User GetUserById(string id)
{
return this.userRepository.GetById(id);
}
public User GetUserByUsername(string username)
{
return this.userRepository
.GetAll(u => u.UserName.Equals(username))
.FirstOrDefault();
}
public void EditUser(string id, string username, string name, string description, string profilePicUrl)
{
var user = this.userRepository.GetById(id);
if (user != null)
{
user.UserName = username;
user.Name = name;
user.Description = description;
user.ProfilePicUrl = profilePicUrl;
this.userRepository.Update(user);
this.unitOfWork.Commit();
}
}
}
}
| mit | C# | |
5e04efc886bfc7c302c7848063ea8ac9554e9fb4 | Fix SymbolicReference debugger display | whoisj/libgit2sharp,jorgeamado/libgit2sharp,Zoxive/libgit2sharp,ethomson/libgit2sharp,libgit2/libgit2sharp,psawey/libgit2sharp,github/libgit2sharp,mono/libgit2sharp,dlsteuer/libgit2sharp,xoofx/libgit2sharp,Skybladev2/libgit2sharp,nulltoken/libgit2sharp,vivekpradhanC/libgit2sharp,red-gate/libgit2sharp,Zoxive/libgit2sharp,GeertvanHorrik/libgit2sharp,sushihangover/libgit2sharp,red-gate/libgit2sharp,jeffhostetler/public_libgit2sharp,PKRoma/libgit2sharp,AArnott/libgit2sharp,shana/libgit2sharp,vorou/libgit2sharp,dlsteuer/libgit2sharp,AMSadek/libgit2sharp,jamill/libgit2sharp,OidaTiftla/libgit2sharp,ethomson/libgit2sharp,oliver-feng/libgit2sharp,jeffhostetler/public_libgit2sharp,rcorre/libgit2sharp,vivekpradhanC/libgit2sharp,rcorre/libgit2sharp,jorgeamado/libgit2sharp,psawey/libgit2sharp,mono/libgit2sharp,Skybladev2/libgit2sharp,OidaTiftla/libgit2sharp,sushihangover/libgit2sharp,github/libgit2sharp,AMSadek/libgit2sharp,AArnott/libgit2sharp,xoofx/libgit2sharp,oliver-feng/libgit2sharp,nulltoken/libgit2sharp,vorou/libgit2sharp,whoisj/libgit2sharp,jamill/libgit2sharp,shana/libgit2sharp,GeertvanHorrik/libgit2sharp | LibGit2Sharp/SymbolicReference.cs | LibGit2Sharp/SymbolicReference.cs | using System.Diagnostics;
using System.Globalization;
namespace LibGit2Sharp
{
/// <summary>
/// A SymbolicReference is a reference that points to another reference
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class SymbolicReference : Reference
{
private readonly Reference target;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected SymbolicReference()
{ }
internal SymbolicReference(string canonicalName, string targetIdentifier, Reference target)
: base(canonicalName, targetIdentifier)
{
this.target = target;
}
/// <summary>
/// Gets the target of this <see cref="SymbolicReference"/>
/// </summary>
public virtual Reference Target
{
get { return target; }
}
/// <summary>
/// Recursively peels the target of the reference until a direct reference is encountered.
/// </summary>
/// <returns>The <see cref="DirectReference"/> this <see cref="SymbolicReference"/> points to.</returns>
public override DirectReference ResolveToDirectReference()
{
return (Target == null) ? null : Target.ResolveToDirectReference();
}
private string DebuggerDisplay
{
get
{
return string.Format(CultureInfo.InvariantCulture,
"{0} => {1} => \"{2}\"",
CanonicalName, TargetIdentifier,
(Target != null) ? Target.TargetIdentifier : "?");
}
}
}
}
| using System.Diagnostics;
using System.Globalization;
namespace LibGit2Sharp
{
/// <summary>
/// A SymbolicReference is a reference that points to another reference
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class SymbolicReference : Reference
{
private readonly Reference target;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected SymbolicReference()
{ }
internal SymbolicReference(string canonicalName, string targetIdentifier, Reference target)
: base(canonicalName, targetIdentifier)
{
this.target = target;
}
/// <summary>
/// Gets the target of this <see cref="SymbolicReference"/>
/// </summary>
public virtual Reference Target
{
get { return target; }
}
/// <summary>
/// Recursively peels the target of the reference until a direct reference is encountered.
/// </summary>
/// <returns>The <see cref="DirectReference"/> this <see cref="SymbolicReference"/> points to.</returns>
public override DirectReference ResolveToDirectReference()
{
return (Target == null) ? null : Target.ResolveToDirectReference();
}
private string DebuggerDisplay
{
get
{
var directReference = ResolveToDirectReference();
return string.Format(CultureInfo.InvariantCulture,
"{0} => {1} => \"{2}\"",
CanonicalName, TargetIdentifier,
(directReference != null) ? directReference.TargetIdentifier : "?");
}
}
}
}
| mit | C# |
e17d053fa6b6d95284a629cca4d60034c78e3426 | Create AccessControlModule.cs | liamning/BlueCrossStaffPortal | AccessControlModule.cs | AccessControlModule.cs | using System;
using System.Collections.Generic;
using System.Web;
/// <summary>
/// Summary description for AccessControl
/// </summary>
public class AccessControl
{
public AccessControl()
{
//
// TODO: Add constructor logic here
//
}
public static Dictionary<string, string> getDisabledFunctionDict()
{
Dictionary<string, string> result = new Dictionary<string, string>();
string sql = "select FunctionName, AccessRole from AccessControl where Enable = 0 ";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.open();
try
{
System.Data.DataTable dt = dbAccess.select(sql);
foreach (System.Data.DataRow row in dt.Rows)
{
result.Add(row["FunctionName"].ToString().ToUpper(), row["AccessRole"].ToString().ToUpper());
}
}
catch
{
throw;
}
finally
{
dbAccess.close();
}
return result;
}
public static Dictionary<string, string> getAdminFunctionDict()
{
Dictionary<string, string> result = new Dictionary<string, string>();
string sql = "select FunctionName, AccessRole from AccessControl where Enable = 1 and AccessRole = '" + GlobalSetting.SystemRoles.Admin + "' ";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.open();
try
{
System.Data.DataTable dt = dbAccess.select(sql);
foreach (System.Data.DataRow row in dt.Rows)
{
result.Add(row["FunctionName"].ToString().ToUpper(), row["AccessRole"].ToString().ToUpper());
}
}
catch
{
throw;
}
finally
{
dbAccess.close();
}
return result;
}
public static Dictionary<string, string> getSuperFunctionDict()
{
Dictionary<string, string> result = new Dictionary<string, string>();
string sql = "select FunctionName, AccessRole from AccessControl where Enable = 1 and AccessRole in ('" + GlobalSetting.SystemRoles.Super + "') ";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.open();
try
{
System.Data.DataTable dt = dbAccess.select(sql);
foreach (System.Data.DataRow row in dt.Rows)
{
result.Add(row["FunctionName"].ToString().ToUpper(), row["AccessRole"].ToString().ToUpper());
}
}
catch
{
throw;
}
finally
{
dbAccess.close();
}
return result;
}
}
| bsd-2-clause | C# | |
5b8155be1fab7a47d560bc3ac442d6d129853ca6 | add average-points grader | ruarai/Trigrad,ruarai/Trigrad | Trigrad/ColorGraders/AverageGrader.cs | Trigrad/ColorGraders/AverageGrader.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trigrad.ColorGraders
{
public class AverageGrader : IGrader
{
public Color Grade(Color cU, Color cV, Color cW, double u, double v, double w, int x, int y)
{
int R = cU.R + cV.R + cW.R;
int G = cU.G + cV.G + cW.G;
int B = cU.B + cV.B + cW.B;
return Color.FromArgb((byte) (R/3), (byte) (G/3), (byte) (B/3));
}
}
}
| mit | C# | |
baa8e837e54267becb1ea50e65fecc49c9bc7e23 | Add FlagsHelper class | bartlomiejwolk/FileLogger | Include/FlagsHelper.cs | Include/FlagsHelper.cs | namespace ATP.LoggingTools {
/// <summary>
/// Helper class for logical bitwise combination setting of Enums with the Flag attribute.
/// This allows code as below where Names is an enum containing a number of names.
/// </summary>
/// <remarks>https://github.com/Maxii/CodeEnv.Master/blob/master/CodeEnv.Master.Common/ThirdParty/FlagsHelper.cs</remarks>
public static class FlagsHelper {
public static bool IsSet<T>(T flags, T flag) where T : struct {
var flagsValue = (int)(object)flags;
var flagValue = (int)(object)flag;
return (flagsValue & flagValue) != 0;
}
public static void Set<T>(ref T flags, T flag) where T : struct {
var flagsValue = (int)(object)flags;
var flagValue = (int)(object)flag;
flags = (T)(object)(flagsValue | flagValue);
}
public static void Unset<T>(ref T flags, T flag) where T : struct {
var flagsValue = (int)(object)flags;
var flagValue = (int)(object)flag;
flags = (T)(object)(flagsValue & (~flagValue));
}
}
} | mit | C# | |
05efba8b1ad84fe354bcba8b239e01f38459fac9 | Set AssemblyConfiguration attribute to a simple/default value. | hlltbrk/autofac,neoe1984/autofac,satish860/autofac,neoe1984/autofac,hlltbrk/autofac,hlltbrk/autofac,neoe1984/autofac,satish860/autofac,satish860/autofac,satish860/autofac,neoe1984/autofac,hlltbrk/autofac | VersionAssemblyInfo.cs | VersionAssemblyInfo.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Reflection;
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyConfiguration("Debug built on 2012-01-01 00:00")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.239
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Reflection;
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2012-03-05 11:24")]
| mit | C# |
1659b11b40069a2abb7121b34bbc270f27bdf1f8 | Add failing test | nunit/nunit-console,nunit/nunit-console,nunit/nunit-console | src/NUnitEngine/nunit.engine.tests/Acceptance/InstantiateEngineInsideTest.cs | src/NUnitEngine/nunit.engine.tests/Acceptance/InstantiateEngineInsideTest.cs | // Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System.IO;
using NUnit.Framework;
namespace NUnit.Engine.Tests.Acceptance
{
class InstantiateEngineInsideTest
{
/// <summary>
/// Historically it wasn't possible to instantiate a full engine inside
/// a running NUnit test due to issues with URI collisions for
/// inter-process communication.
///
/// This is a useful feature to maintain, to allow runners to create full
/// end-to-end acceptance-style tests in NUnit.
/// </summary>
[Test, Platform("Net")] //TODO: Make test work on .NET Core. Tracked as https://github.com/nunit/nunit-console/issues/946
public void CanInstantiateEngineInsideTest()
{
Assert.DoesNotThrow(() =>
{
using (var engine = TestEngineActivator.CreateInstance())
{
var mockAssemblyPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "mock-assembly.dll");
var package = new TestPackage(mockAssemblyPath);
engine.GetRunner(package).Run(new NullListener(), TestFilter.Empty);
}
});
}
private class NullListener : ITestEventListener
{
public void OnTestEvent(string testEvent)
{
// No action
}
}
}
}
| mit | C# | |
0e1a59d152c61f5a5c15742caf21a945c06b0987 | Create NumberExtension.cs | lzinga/ComLib | ComLib.Extensions/NumberExtensions.cs | ComLib.Extensions/NumberExtensions.cs | using System;
using System.IO;
namespace ComLib.Extension
{
public static class NumberExtensions
{
/// <summary>
/// Turns the size into a human readable file size.
/// </summary>
public static string FileSizeToString(this long size)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB", "PB" };
double len = size;
int order = 0;
while (len >= 1024 && order + 1 < sizes.Length)
{
order++;
len = len / 1024;
}
return string.Format("{0:0.##} {1}", len, sizes[order]);
}
}
}
| mit | C# | |
2defb5d666816775e57bc65f625abb2e70c04d04 | Test coverage | Grinderofl/FluentModelBuilder,Grinderofl/FluentModelBuilder | test/FluentModelBuilder.Tests/AssemblyTests/AddingEntitiesFromConventions.cs | test/FluentModelBuilder.Tests/AssemblyTests/AddingEntitiesFromConventions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentModelBuilder.Conventions.Core.Options.Extensions;
using FluentModelBuilder.Conventions.EntityConvention.Options.Extensions;
using FluentModelBuilder.Extensions;
using FluentModelBuilder.Options;
using FluentModelBuilder.TestTarget;
using Xunit;
namespace FluentModelBuilder.Tests.AssemblyTests
{
public class AddingEntitiesFromConventions : ClassFixture<AddingEntitiesFromConventions.Fixture>
{
[Fact]
public void ContainsCorrectEntities()
{
Assert.Equal(2, Model.EntityTypes.Count);
Assert.Equal(typeof(EntityOne), Model.EntityTypes[0].ClrType);
Assert.Equal(typeof(EntityTwo), Model.EntityTypes[1].ClrType);
}
[Fact]
public void EntityOneContainsCorrectProperties()
{
var properties = Model.EntityTypes[0].GetProperties().OrderBy(x => x.Name).ToArray();
Assert.Equal(3, properties.Length);
Assert.Equal("Id", properties[0].Name);
Assert.Equal(typeof(int), properties[0].ClrType);
Assert.Equal("IgnoredInOverride", properties[1].Name);
Assert.Equal(typeof(string), properties[1].ClrType);
Assert.Equal("NotIgnored", properties[2].Name);
Assert.Equal(typeof(string), properties[2].ClrType);
}
[Fact]
public void EntityTwoContainsCorrectProperties()
{
var properties = Model.EntityTypes[1].GetProperties().OrderBy(x => x.Name).ToArray();
Assert.Equal(1, properties.Length);
Assert.Equal("Id", properties[0].Name);
Assert.Equal(typeof(int), properties[0].ClrType);
}
[Fact]
public void DoesNotAddBaseType()
{
Assert.False(Model.EntityTypes.Any(x => x.ClrType == typeof(EntityBase)));
}
public class Fixture : ModelFixtureBase
{
protected override void ConfigureOptions(FluentModelBuilderOptions options)
{
options.Assemblies(d => d.AddAssemblyContaining<EntityOne>());
options.DiscoverEntitiesFromCommonAssemblies(x => x.WithBaseType<EntityBase>());
}
}
public AddingEntitiesFromConventions(Fixture fixture) : base(fixture)
{
}
}
}
| mit | C# | |
18800c6066245814f6b8cbe99f96b6e43abe7789 | Drop in a Content file on install to disable WPF's scaling | minhthuanit/PerMonitorDpi,paulcbetts/PerMonitorDpi,CrimsonArc/PerMonitorDpi | Content/DisableSystemDpiAwareness.cs | Content/DisableSystemDpiAwareness.cs | using System.Windows.Media;
// Disable WPF's built-in scaling, we're doing it ourselves
[assembly:DisableDpiAwareness]; | mit | C# | |
7d4200d0a430c5d0bfb06575c42eb9fa58d17c11 | Add unit tests to validate the value of properties set in ISecurityCapabilities. | mconnew/wcf,mconnew/wcf,StephenBonikowsky/wcf,StephenBonikowsky/wcf,imcarolwang/wcf,dotnet/wcf,dotnet/wcf,dotnet/wcf,imcarolwang/wcf,imcarolwang/wcf,mconnew/wcf | src/System.ServiceModel.Security/tests/ServiceModel/ISecurityCapabilitiesTest.cs | src/System.ServiceModel.Security/tests/ServiceModel/ISecurityCapabilitiesTest.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;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Infrastructure.Common;
using Xunit;
public static class ISecurityCapabilitiesTest
{
[WcfFact]
public static void SecurityCapabilities_HttpsTransportBindingElement()
{
ISecurityCapabilities capability = CreateISecurityCapabilities(new HttpsTransportBindingElement());
Assert.Equal("EncryptAndSign", capability.SupportedRequestProtectionLevel.ToString());
Assert.Equal("EncryptAndSign", capability.SupportedResponseProtectionLevel.ToString());
Assert.Equal("False", capability.SupportsClientAuthentication.ToString());
Assert.Equal("False", capability.SupportsClientWindowsIdentity.ToString());
Assert.Equal("True", capability.SupportsServerAuthentication.ToString());
}
[WcfFact]
public static void SecurityCapabilities_HttpTransportBindingElement()
{
ISecurityCapabilities capability = CreateISecurityCapabilities(new HttpTransportBindingElement());
Assert.Equal("None", capability.SupportedRequestProtectionLevel.ToString());
Assert.Equal("None", capability.SupportedResponseProtectionLevel.ToString());
Assert.Equal("False", capability.SupportsClientAuthentication.ToString());
Assert.Equal("False", capability.SupportsClientWindowsIdentity.ToString());
Assert.Equal("False", capability.SupportsServerAuthentication.ToString());
}
[WcfFact]
public static void SecurityCapabilities_TransportSecurityBindingElement()
{
ISecurityCapabilities capability = CreateISecurityCapabilities(new TransportSecurityBindingElement());
Assert.Equal("None", capability.SupportedRequestProtectionLevel.ToString());
Assert.Equal("None", capability.SupportedResponseProtectionLevel.ToString());
Assert.Equal("False", capability.SupportsClientAuthentication.ToString());
Assert.Equal("False", capability.SupportsClientWindowsIdentity.ToString());
Assert.Equal("False", capability.SupportsServerAuthentication.ToString());
}
[WcfFact]
public static void SecurityCapabilities_SslStreamSecurityBindingElement()
{
ISecurityCapabilities capability = CreateISecurityCapabilities(new SslStreamSecurityBindingElement());
Assert.Equal("EncryptAndSign", capability.SupportedRequestProtectionLevel.ToString());
Assert.Equal("EncryptAndSign", capability.SupportedResponseProtectionLevel.ToString());
Assert.Equal("False", capability.SupportsClientAuthentication.ToString());
Assert.Equal("False", capability.SupportsClientWindowsIdentity.ToString());
Assert.Equal("True", capability.SupportsServerAuthentication.ToString());
}
[WcfFact]
public static void SecurityCapabilities_WindowsStreamSecurityBindingElement()
{
ISecurityCapabilities capability = CreateISecurityCapabilities(new WindowsStreamSecurityBindingElement());
Assert.Equal("EncryptAndSign", capability.SupportedRequestProtectionLevel.ToString());
Assert.Equal("EncryptAndSign", capability.SupportedResponseProtectionLevel.ToString());
Assert.Equal("True", capability.SupportsClientAuthentication.ToString());
Assert.Equal("True", capability.SupportsClientWindowsIdentity.ToString());
Assert.Equal("True", capability.SupportsServerAuthentication.ToString());
}
public static ISecurityCapabilities CreateISecurityCapabilities(BindingElement bindingElement)
{
CustomBinding binding = new CustomBinding(bindingElement);
BindingParameterCollection collection = new BindingParameterCollection();
BindingContext context = new BindingContext(binding, collection);
ISecurityCapabilities capability = binding.GetProperty<ISecurityCapabilities>(collection);
return capability;
}
}
| mit | C# | |
1fcda808caca25276319d6aab6e1d616368b7dfc | Add comment. | gafter/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,pdelvo/roslyn,genlu/roslyn,MattWindsor91/roslyn,MichalStrehovsky/roslyn,mmitche/roslyn,diryboy/roslyn,mavasani/roslyn,gafter/roslyn,stephentoub/roslyn,OmarTawfik/roslyn,vslsnap/roslyn,bkoelman/roslyn,CaptainHayashi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ErikSchierboom/roslyn,brettfo/roslyn,panopticoncentral/roslyn,nguerrera/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,Hosch250/roslyn,AlekseyTs/roslyn,stephentoub/roslyn,Giftednewt/roslyn,jcouv/roslyn,aelij/roslyn,bkoelman/roslyn,KirillOsenkov/roslyn,yeaicc/roslyn,AmadeusW/roslyn,tvand7093/roslyn,Pvlerick/roslyn,lorcanmooney/roslyn,akrisiun/roslyn,AlekseyTs/roslyn,paulvanbrenk/roslyn,TyOverby/roslyn,drognanar/roslyn,xoofx/roslyn,bbarry/roslyn,orthoxerox/roslyn,MattWindsor91/roslyn,agocke/roslyn,jamesqo/roslyn,Hosch250/roslyn,abock/roslyn,tannergooding/roslyn,KevinH-MS/roslyn,swaroop-sridhar/roslyn,jkotas/roslyn,MattWindsor91/roslyn,stephentoub/roslyn,weltkante/roslyn,mavasani/roslyn,swaroop-sridhar/roslyn,Giftednewt/roslyn,paulvanbrenk/roslyn,bartdesmet/roslyn,zooba/roslyn,mmitche/roslyn,genlu/roslyn,panopticoncentral/roslyn,tmat/roslyn,bkoelman/roslyn,jmarolf/roslyn,brettfo/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,AnthonyDGreen/roslyn,bartdesmet/roslyn,a-ctor/roslyn,diryboy/roslyn,orthoxerox/roslyn,jkotas/roslyn,jmarolf/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,jcouv/roslyn,xoofx/roslyn,weltkante/roslyn,Hosch250/roslyn,MichalStrehovsky/roslyn,physhi/roslyn,jasonmalinowski/roslyn,paulvanbrenk/roslyn,sharwell/roslyn,tmat/roslyn,mattscheffer/roslyn,AlekseyTs/roslyn,mattscheffer/roslyn,DustinCampbell/roslyn,abock/roslyn,eriawan/roslyn,robinsedlaczek/roslyn,aelij/roslyn,kelltrick/roslyn,eriawan/roslyn,robinsedlaczek/roslyn,drognanar/roslyn,heejaechang/roslyn,AnthonyDGreen/roslyn,genlu/roslyn,agocke/roslyn,Giftednewt/roslyn,dotnet/roslyn,jamesqo/roslyn,Pvlerick/roslyn,physhi/roslyn,sharwell/roslyn,brettfo/roslyn,tvand7093/roslyn,srivatsn/roslyn,wvdd007/roslyn,a-ctor/roslyn,vslsnap/roslyn,zooba/roslyn,CyrusNajmabadi/roslyn,mattwar/roslyn,srivatsn/roslyn,amcasey/roslyn,KevinRansom/roslyn,tmeschter/roslyn,bbarry/roslyn,ErikSchierboom/roslyn,pdelvo/roslyn,gafter/roslyn,agocke/roslyn,robinsedlaczek/roslyn,kelltrick/roslyn,davkean/roslyn,bartdesmet/roslyn,tmat/roslyn,vslsnap/roslyn,physhi/roslyn,dotnet/roslyn,a-ctor/roslyn,yeaicc/roslyn,aelij/roslyn,jcouv/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,xasx/roslyn,abock/roslyn,VSadov/roslyn,sharwell/roslyn,amcasey/roslyn,heejaechang/roslyn,cston/roslyn,zooba/roslyn,Pvlerick/roslyn,MattWindsor91/roslyn,eriawan/roslyn,TyOverby/roslyn,AArnott/roslyn,reaction1989/roslyn,tmeschter/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,lorcanmooney/roslyn,davkean/roslyn,wvdd007/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,srivatsn/roslyn,AArnott/roslyn,lorcanmooney/roslyn,dpoeschl/roslyn,akrisiun/roslyn,DustinCampbell/roslyn,dpoeschl/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,jeffanders/roslyn,mattwar/roslyn,nguerrera/roslyn,dotnet/roslyn,jeffanders/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,xoofx/roslyn,shyamnamboodiripad/roslyn,mattwar/roslyn,xasx/roslyn,orthoxerox/roslyn,khyperia/roslyn,panopticoncentral/roslyn,amcasey/roslyn,kelltrick/roslyn,drognanar/roslyn,mavasani/roslyn,OmarTawfik/roslyn,dpoeschl/roslyn,jeffanders/roslyn,AArnott/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KevinRansom/roslyn,DustinCampbell/roslyn,tvand7093/roslyn,CaptainHayashi/roslyn,KirillOsenkov/roslyn,xasx/roslyn,reaction1989/roslyn,pdelvo/roslyn,jkotas/roslyn,mattscheffer/roslyn,jamesqo/roslyn,wvdd007/roslyn,akrisiun/roslyn,CaptainHayashi/roslyn,KevinH-MS/roslyn,KevinH-MS/roslyn,mmitche/roslyn,khyperia/roslyn,swaroop-sridhar/roslyn,tmeschter/roslyn,diryboy/roslyn,TyOverby/roslyn,heejaechang/roslyn,khyperia/roslyn,cston/roslyn,AnthonyDGreen/roslyn,yeaicc/roslyn,CyrusNajmabadi/roslyn,bbarry/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,cston/roslyn,nguerrera/roslyn,jasonmalinowski/roslyn | src/Workspaces/Remote/Core/Storage/RemotePersistentStorageLocationService.cs | src/Workspaces/Remote/Core/Storage/RemotePersistentStorageLocationService.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Composition;
using System.IO;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Remote.Storage
{
[ExportWorkspaceService(typeof(IPersistentStorageLocationService), layer: SolutionService.WorkspaceKind_RemoteWorkspace), Shared]
internal class RemotePersistentStorageLocationService : IPersistentStorageLocationService
{
private static readonly object _gate = new object();
private static readonly Dictionary<SolutionId, string> _idToStorageLocation = new Dictionary<SolutionId, string>();
public string GetStorageLocation(Solution solution)
{
string result;
_idToStorageLocation.TryGetValue(solution.Id, out result);
return result;
}
public bool IsSupported(Workspace workspace)
{
lock (_gate)
{
return _idToStorageLocation.ContainsKey(workspace.CurrentSolution.Id);
}
}
public static void UpdateStorageLocation(SolutionId id, string storageLocation)
{
lock (_gate)
{
// We can get null when the solution has no corresponding file location
// in the host process. This is not abnormal and can come around for
// many reasons. In that case, we simply do not store a storage location
// for this solution, indicating to all remote consumers that persistent
// storage is not available for this solution.
if (storageLocation == null)
{
_idToStorageLocation.Remove(id);
}
else
{
// Store the esent database in a different location for the out of proc server.
_idToStorageLocation[id] = Path.Combine(storageLocation, "Server");
}
}
}
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Composition;
using System.IO;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Remote.Storage
{
[ExportWorkspaceService(typeof(IPersistentStorageLocationService), layer: SolutionService.WorkspaceKind_RemoteWorkspace), Shared]
internal class RemotePersistentStorageLocationService : IPersistentStorageLocationService
{
private static readonly object _gate = new object();
private static readonly Dictionary<SolutionId, string> _idToStorageLocation = new Dictionary<SolutionId, string>();
public string GetStorageLocation(Solution solution)
{
string result;
_idToStorageLocation.TryGetValue(solution.Id, out result);
return result;
}
public bool IsSupported(Workspace workspace)
{
lock (_gate)
{
return _idToStorageLocation.ContainsKey(workspace.CurrentSolution.Id);
}
}
public static void UpdateStorageLocation(SolutionId id, string storageLocation)
{
lock (_gate)
{
if (storageLocation == null)
{
_idToStorageLocation.Remove(id);
}
else
{
// Store the esent database in a different location for the out of proc server.
_idToStorageLocation[id] = Path.Combine(storageLocation, "Server");
}
}
}
}
} | apache-2.0 | C# |
468f2ee9bb066041f56dbe96d675dfca758db03d | Add file | dkschlos/PVM.NET | src/PVM.Core/Plan/Operations/DynamicOperation.cs | src/PVM.Core/Plan/Operations/DynamicOperation.cs | using System;
using PVM.Core.Data;
using PVM.Core.Runtime;
namespace PVM.Core.Plan.Operations
{
public class DynamicOperation<T> : IOperation<T> where T : ICopyable<T>
{
private readonly Action<IExecution<T>> action;
public DynamicOperation(Action<IExecution<T>> action)
{
this.action = action;
}
public void Execute(IExecution<T> execution)
{
action(execution);
}
}
} | apache-2.0 | C# | |
530a90695fb7fd2e78ce856a16f8d80c26184361 | Create Problem27.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem27.cs | Problems/Problem27.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler
{
class Problem27
{
public void Run()
{
int x = 1000;
Sieve s = new Sieve(x*x + x*x + x); // n^2 + a*n + b @ n,a,b = 1000
List<int> primes = new List<int>();
for (int i = 0; i < x; i++)
{
if (s.prime[i])
{
primes.Add(i);
primes.Add(i * -1);
}
}
//primes.Sort();
int max = 0;
int maxA = 0;
int maxB = 0;
foreach (int a in primes)
{
foreach (int b in primes)
{
int counter = 0;
for (int n = 0; n < Math.Abs(b); n++)
{
int number = n * n + a * n + b;
if (number > 0 && number < s.prime.Length)
{
if (s.prime[number])
{
counter++;
if (counter > max)
{
max = counter;
maxA = a;
maxB = b;
}
}
else
{
counter = 0;
}
}
else
{
counter = 0;
}
}
}
}
Console.WriteLine("" + maxA.ToString() + ", " + maxB.ToString() + ": " + max.ToString());
Console.WriteLine((maxA * maxB).ToString());
Console.ReadLine();
}
}
}
| mit | C# | |
6677e509cc1fb398437f89d6a9f08d129d15b185 | Implement GameCreateViewModel and GameEditViewModel | lucasdavid/Gamedalf,lucasdavid/Gamedalf | Gamedalf/ViewModels/GameViewModels.cs | Gamedalf/ViewModels/GameViewModels.cs | using System.ComponentModel.DataAnnotations;
namespace Gamedalf.ViewModels
{
public class GameCreateViewModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
[Display(Name = "Price")]
public decimal? Price { get; set; }
}
public class GameEditViewModel
{
[Required]
public int Id { get; set; }
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
}
}
| mit | C# | |
15792bd9c95f57852e2a6883d244437d80a9808a | Test for GoogleOptimizeRouteService | forestcheng/allReady,forestcheng/allReady,forestcheng/allReady,forestcheng/allReady | AllReadyApp/Web-App/AllReady.UnitTest/Services/GoogleOptimizeRouteServiceTest.cs | AllReadyApp/Web-App/AllReady.UnitTest/Services/GoogleOptimizeRouteServiceTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AllReady.UnitTest.Services
{
public class GoogleOptimizeRouteServiceTest : InMemoryContextTest
{
private const string EncodedStartAddress = "252 Dundas St, London, ON N6A 1H3";
private const string EncodedEndAddress = "1750 Crumlin Road, London, ON N5V 3B6";
}
}
| mit | C# | |
d4a6f3cf93731a2aaecc5395ce084e6b823d1448 | Create SinglyLinkedList.cs | vishipayyallore/CSharp-DotNet-Core-Samples | LearningDesignPatterns/Source/Alogithms/LogicPrograms/Common/SinglyLinkedList.cs | LearningDesignPatterns/Source/Alogithms/LogicPrograms/Common/SinglyLinkedList.cs | namespace LogicPrograms.Common
{
public class SinglyLinkedList
{
public SinglyLinkedListNode Head;
public SinglyLinkedListNode Tail;
public SinglyLinkedList()
{
Head = null;
Tail = null;
}
public void InsertNode(int nodeData)
{
SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);
if (Head == null)
{
Head = node;
}
else
{
Tail.Next = node;
}
Tail = node;
}
}
}
| apache-2.0 | C# | |
22e3d0d64c189b4744b7a5da337b82aa54423510 | Add LinkElement. | x335/scriptsharp,nikhilk/scriptsharp,x335/scriptsharp,x335/scriptsharp,nikhilk/scriptsharp,nikhilk/scriptsharp | src/Libraries/Web/Html/LinkElement.cs | src/Libraries/Web/Html/LinkElement.cs | // LinkElement.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace System.Html {
[ScriptIgnoreNamespace]
[ScriptImport]
public sealed class LinkElement : Element {
private LinkElement() {
}
[ScriptField]
public string Rel {
get {
return null;
}
set {
}
}
[ScriptField]
public string Media {
get {
return null;
}
set {
}
}
[ScriptField]
public string Href {
get {
return null;
}
set {
}
}
}
}
| apache-2.0 | C# | |
38d3d3aa549dc81ea7ec6342601a2c7be93f1577 | Create _Layout.cshtml | CarmelSoftware/Generic-Data-Repository-With-Caching | Views/Shared/_Layout.cshtml | Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
@RenderBody()
</div>
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# | |
7ed5c418b0e7bb9226b18ae3f959645da6c67503 | Create CompDir.cs | etormadiv/njRAT_0.7d_Stub_ReverseEngineering | j_csharp/OK/CompDir.cs | j_csharp/OK/CompDir.cs | //Reversed by Etor Madiv
private static bool CompDir(System.IO.FileInfo F1, System.IO.FileInfo F2)
{
if ( Microsoft.VisualBasic.CompilerServices.Operators.CompareString(
F1.Name.ToLower(),
F2.Name.ToLower(),
false
) != 0
)
return false;
System.IO.DirectoryInfo leftDir = F1.Directory;
System.IO.DirectoryInfo rightDir = F2.Directory;
while(true)
{
if ( Microsoft.VisualBasic.CompilerServices.Operators.CompareString(
leftDir.Name.ToLower(),
rightDir.Name.ToLower(),
false
) != 0
)
return false;
leftDir = leftDir.Parent;
rightDir = rightDir.Parent;
if(leftDir == null && rightDir == null)
return true;
if(leftDir == null || rightDir == null)
return false;
}
}
| unlicense | C# | |
859572931a3f1e2bdc2f39d25774a10406b4b807 | Create ConditionalRequiredAttribute.cs | karaxuna/ConditionalRequiredAttribute,karaxuna/ConditionalRequiredAttribute | ConditionalRequiredAttribute.cs | ConditionalRequiredAttribute.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Mvc;
namespace CustomAttributes
{
public class ConditionalRequiredAttribute : RequiredAttribute, IClientValidatable
{
private readonly string _expression;
private readonly ExpressionParser _expressionParser = new ExpressionParser();
public ConditionalRequiredAttribute(string expression)
{
_expression = expression;
}
public ConditionalRequiredAttribute(string expressionTemplate, params object[] values)
{
_expression = string.Format(expressionTemplate, values);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var result = _expressionParser.Parse(validationContext.ObjectInstance, _expression);
if(result)
return base.IsValid(value, validationContext);
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "conditionalrequired",
};
var viewContext = (ViewContext)context;
var andExpressions = _expressionParser.GetEqualityExpressions(_expression);
foreach (var orExpressions in andExpressions)
{
foreach (var orExpression in orExpressions)
{
orExpression.Property = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(orExpression.Property);
}
}
rule.ValidationParameters.Add("expression", Serializer.Serialize(andExpressions));
yield return rule;
}
}
public class Serializer
{
public static string Serialize(object obj)
{
using (var memoryStream = new MemoryStream())
using (var reader = new StreamReader(memoryStream))
{
var serializer = new DataContractJsonSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
return reader.ReadToEnd();
}
}
public static object Deserialize(string xml, Type toType)
{
using (Stream stream = new MemoryStream())
{
byte[] data = Encoding.UTF8.GetBytes(xml);
stream.Write(data, 0, data.Length);
stream.Position = 0;
var deserializer = new DataContractJsonSerializer(toType);
return deserializer.ReadObject(stream);
}
}
}
}
| mit | C# | |
21772997283247156b6a144fe1a1d672fa91c89f | Add Status tests | jasonracey/iTunesAssistant | iTunesAssistantLibTest/StatusTests.cs | iTunesAssistantLibTest/StatusTests.cs | using FluentAssertions;
using iTunesAssistantLib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace iTunesAssistantLibTest
{
[TestClass]
public class StatusTests
{
private readonly Random _random = new Random();
[TestMethod]
public void ItemsTotal_MustBeGreaterThanOrEqualToZero()
{
// arrange
var itemsTotal = _random.Next(-100, -1);
// act/assert
Assert.ThrowsException<ArgumentOutOfRangeException>(() => Status.Create(itemsTotal));
}
[TestMethod]
public void Create_WithoutMessage()
{
// arrange
var itemsTotal = _random.Next(1, 100);
// act
var status = Status.Create(itemsTotal);
// assert
status.ItemsProcessed.Should().Be(0);
status.ItemsTotal.Should().Be(itemsTotal);
status.Message.Should().Be(string.Empty);
}
[TestMethod]
public void Create_WithMessage()
{
// arrange
var itemsTotal = _random.Next(1, 100);
var message = Guid.NewGuid().ToString();
// act
var status = Status.Create(itemsTotal, message);
// assert
status.ItemsProcessed.Should().Be(0);
status.ItemsTotal.Should().Be(itemsTotal);
status.Message.Should().Be(message);
}
[TestMethod]
public void ItemsProcessed()
{
// arrange
var iterations = _random.Next(1, 100);
var status = Status.Create(default);
// act
for (var i = 0; i < iterations; i++) status.ItemProcessed();
// assert
status.ItemsProcessed.Should().Be(iterations);
}
}
}
| mit | C# | |
a2b9dc3aada6c45c9285ad9873b8494ccdc1fc7e | Add ISerializer impl. that uses JSON.NET | smarts/log4net.Ext.Json.Serializers | shared/JsonDotNetSerializer.cs | shared/JsonDotNetSerializer.cs | using System.IO;
using System.Text;
using log4net.ObjectRenderer;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace log4net.Util.Serializer
{
public class JsonDotNetSerializer : ISerializer
{
public RendererMap Map { get; set; }
public object Serialize(object obj)
{
object result;
if (obj != null)
{
using (var writer = new StringWriter(new StringBuilder()))
using (var jsonWriter = new RendererMapJsonTextWriter(Map, writer) { CloseOutput = false })
{
jsonWriter.WriteValue(obj);
result = writer.GetStringBuilder().ToString();
}
}
else
{
result = JsonConvert.SerializeObject(obj);
}
return result;
}
}
}
| mit | C# | |
b928b1b52972c6d42735ae3649a2855fe43d66d8 | Add MaskingTests | Carbon/Css | src/Carbon.Css.Tests/Modules/MaskingTests.cs | src/Carbon.Css.Tests/Modules/MaskingTests.cs | using Xunit;
namespace Carbon.Css.Tests
{
public class MaskingTests
{
[Fact]
public void A()
{
var text = @"
//= support Safari >= 5
div {
mask-image: url('mask.svg');
}
";
Assert.Equal(@"
div {
-webkit-mask-image: url('mask.svg');
mask-image: url('mask.svg');
}
".Trim(), StyleSheet.Parse(text).ToString());
}
}
}
| mit | C# | |
602a9ff3cd675fc4f2dee8b477cdff6ab565a0d8 | Revert "Delete SlackIntegration.cs" | Sankra/DIPSbot,Sankra/DIPSbot | src/Hjerpbakk.DIPSbot/SlackIntegration.cs | src/Hjerpbakk.DIPSbot/SlackIntegration.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Hjerpbakk.DIPSbot.Extensions;
using Hjerpbakk.DIPSBot;
using Hjerpbakk.DIPSBot.Configuration;
using SlackConnector;
using SlackConnector.EventHandlers;
using SlackConnector.Models;
namespace Hjerpbakk.DIPSbot
{
/// <summary>
/// Wrapps the Slack APIs needed for Profilebot.
/// </summary>
public sealed class SlackIntegration : ISlackIntegration
{
readonly ISlackConnector connector;
readonly string slackKey;
ISlackConnection connection;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="connector">The Slack connector to use.</param>
/// <param name="configuration">The Slack configuration.</param>
public SlackIntegration(ISlackConnector connector, IReadOnlyAppConfiguration configuration)
{
this.connector = connector ?? throw new ArgumentNullException(nameof(connector));
// TODO: sjekk configuration mot null
if (string.IsNullOrEmpty(configuration.SlackAPIToken))
{
throw new ArgumentException(nameof(configuration.SlackAPIToken));
}
slackKey = configuration.SlackAPIToken;
}
/// <summary>
/// Raised everytime the bot gets a DM.
/// </summary>
public event MessageReceivedEventHandler MessageReceived
{
add => connection.OnMessageReceived += value;
remove => connection.OnMessageReceived -= value;
}
/// <summary>
/// Connects the bot to Slack.
/// </summary>
/// <returns>No object or value is returned by this method when it completes.</returns>
public async Task Connect()
{
connection = await connector.Connect(slackKey);
if (connection == null) {
throw new ArgumentException("Could not connect to Slack.");
}
}
// TODO: Abonner på flere events og track feil bedre
// TODO: Less typing notifications...
public async Task Close()
{
await connection.Close();
}
/// <summary>
/// Gets all the users in the Slack team.
/// </summary>
/// <returns>All users.</returns>
public async Task<IEnumerable<SlackUser>> GetAllUsers()
{
return await connection.GetUsers();
}
/// <summary>
/// Gets the user with the given Id.
/// </summary>
/// <param name="userId">The id of the user to be found.</param>
/// <returns>The wanted user or null if not found.</returns>
public async Task<SlackUser> GetUser(string userId)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentException(nameof(userId));
}
return connection.UserCache.ContainsKey(userId)
? connection.UserCache[userId]
: (await GetAllUsers()).SingleOrDefault(u => u.Id == userId);
}
/// <summary>
/// Sends a DM to the given user.
/// </summary>
/// <param name="user">The recipient of the DM.</param>
/// <param name="text">The message itself.</param>
/// <returns>No object or value is returned by this method when it completes.</returns>
public async Task SendDirectMessage(SlackUser user, string text)
{
user.Guard();
if (string.IsNullOrEmpty(text))
{
throw new ArgumentException(nameof(text));
}
var channel = await connection.JoinDirectMessageChannel(user.Id);
var message = new BotMessage { ChatHub = channel, Text = text };
await connection.Say(message);
}
public async Task SendMessageToChannel(SlackChatHub channel, string text, params SlackAttachment[] attachments) {
var message = new BotMessage { ChatHub = channel, Text = text };
if (attachments.Length > 0) {
message.Attachments = attachments;
}
await connection.Say(message);
}
public async Task AddUsersToChannel(IEnumerable<SlackUser> users, string channelName)
{
// TODO: nullsjekker
var channels = await connection.GetChannels();
var devChannel = channels.Single(c => c.Name == channelName);
}
}
} | mit | C# | |
63087379529da64b902dc139db8b9f80172a0a42 | Add employee and manager as user roles | alexandraholcombe/PetAdoptionCRM,alexandraholcombe/PetAdoptionCRM,alexandraholcombe/PetAdoptionCRM | src/PetAdoptionCRM/Models/EmployeeRole.cs | src/PetAdoptionCRM/Models/EmployeeRole.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PetAdoptionCRM.Models
{
public class EmployeeRole : IdentityRole
{
}
}
| mit | C# | |
243538a6fd9b5f187f1d4a97f0bbd6a9f018cb3b | Create effect profile | Ziggeo/ZiggeoCSharpSDK,Ziggeo/ZiggeoCSharpSDK | demos/ADD_Effect_Profile.cs | demos/ADD_Effect_Profile.cs | using System;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace Add_effect_Profile
{
public class ADD_Effect_Profile
{
public static void Main(string[] args)
{
Ziggeo ziggeo = new Ziggeo("APP_TOKEN", "PRIVATE_KEY", "ENCRYPTION_KEY");
Dictionary<string, string> profile = new Dictionary<string, string>()
{
{"key","YOUR_EFFECT_PROFILE_KEY"},
{"title","YOUR_EFFECT_PROFILE_TITLE" },
};
ziggeo.effectProfiles().create(profile);
System.Console.WriteLine("Effect Profile has been created!!");
}
}
} | apache-2.0 | C# | |
37726f403a777e567f2f580ea3ed84ab19ffe787 | Add unit test for GetSymmetricAlgorithm. | StephenBonikowsky/wcf,mconnew/wcf,dotnet/wcf,mconnew/wcf,imcarolwang/wcf,StephenBonikowsky/wcf,dotnet/wcf,imcarolwang/wcf,dotnet/wcf,imcarolwang/wcf,mconnew/wcf | src/System.ServiceModel.Primitives/tests/IdentityModel/SymmetricSecurityKeyTest.cs | src/System.ServiceModel.Primitives/tests/IdentityModel/SymmetricSecurityKeyTest.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.IdentityModel.Tokens;
using System.Security.Cryptography;
using Infrastructure.Common;
using Xunit;
public static class SymmetricSecurityKeyTest
{
[WcfFact]
public static void method_GetSymmetricKey()
{
byte[] gsk = new byte[] { 0x02, 0x01, 0x04, 0x03 };
MockGetSymmetricAlgorithm mgsakey = new MockGetSymmetricAlgorithm();
Assert.NotNull(mgsakey.GetSymmetricKey());
Assert.Equal(gsk, mgsakey.GetSymmetricKey());
}
[WcfFact]
public static void method_GetSymmetricAlgorithm()
{
string algorit = "DES";
MockGetSymmetricAlgorithm mgsaalg = new MockGetSymmetricAlgorithm();
Assert.NotNull(mgsaalg.GetSymmetricAlgorithm(algorit));
Assert.IsType<DESCryptoServiceProvider>(mgsaalg.GetSymmetricAlgorithm(algorit));
}
}
public class MockGetSymmetricAlgorithm : SymmetricSecurityKey
{
public override int KeySize => throw new System.NotImplementedException();
public override byte[] DecryptKey(string algorithm, byte[] keyData)
{
throw new System.NotImplementedException();
}
public override byte[] EncryptKey(string algorithm, byte[] keyData)
{
throw new System.NotImplementedException();
}
public override byte[] GenerateDerivedKey(string algorithm, byte[] label, byte[] nonce, int derivedKeyLength, int offset)
{
throw new System.NotImplementedException();
}
public override ICryptoTransform GetDecryptionTransform(string algorithm, byte[] iv)
{
throw new System.NotImplementedException();
}
public override ICryptoTransform GetEncryptionTransform(string algorithm, byte[] iv)
{
throw new System.NotImplementedException();
}
public override int GetIVSize(string algorithm)
{
throw new System.NotImplementedException();
}
public override KeyedHashAlgorithm GetKeyedHashAlgorithm(string algorithm)
{
throw new System.NotImplementedException();
}
public override SymmetricAlgorithm GetSymmetricAlgorithm(string algorithm)
{
return new DESCryptoServiceProvider();
}
public override byte[] GetSymmetricKey()
{
byte[] gsk = new byte[] { 0x02, 0x01, 0x04, 0x03 };
return gsk;
}
public override bool IsAsymmetricAlgorithm(string algorithm)
{
throw new System.NotImplementedException();
}
public override bool IsSupportedAlgorithm(string algorithm)
{
throw new System.NotImplementedException();
}
public override bool IsSymmetricAlgorithm(string algorithm)
{
throw new System.NotImplementedException();
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.