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
cb7bc5aa69591711d3d11fb69e83a9e4de5815a5
Use var initialization instead of explicitly declaring the type.
SonyaSa/CppSharp,u255436/CppSharp,mydogisbox/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,mydogisbox/CppSharp,ddobrev/CppSharp,SonyaSa/CppSharp,Samana/CppSharp,zillemarco/CppSharp,mohtamohit/CppSharp,imazen/CppSharp,KonajuGames/CppSharp,nalkaro/CppSharp,txdv/CppSharp,mohtamohit/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp,Samana/CppSharp,imazen/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,mydogisbox/CppSharp,inordertotest/CppSharp,Samana/CppSharp,mohtamohit/CppSharp,mydogisbox/CppSharp,xistoso/CppSharp,Samana/CppSharp,inordertotest/CppSharp,KonajuGames/CppSharp,Samana/CppSharp,KonajuGames/CppSharp,mydogisbox/CppSharp,imazen/CppSharp,ddobrev/CppSharp,mono/CppSharp,mono/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,zillemarco/CppSharp,SonyaSa/CppSharp,xistoso/CppSharp,u255436/CppSharp,txdv/CppSharp,xistoso/CppSharp,xistoso/CppSharp,imazen/CppSharp,nalkaro/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,nalkaro/CppSharp,txdv/CppSharp,imazen/CppSharp,mono/CppSharp,u255436/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,ktopouzi/CppSharp,SonyaSa/CppSharp,genuinelucifer/CppSharp,u255436/CppSharp,inordertotest/CppSharp,zillemarco/CppSharp,txdv/CppSharp,mono/CppSharp,mono/CppSharp,nalkaro/CppSharp,zillemarco/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,KonajuGames/CppSharp,ktopouzi/CppSharp,ddobrev/CppSharp,txdv/CppSharp,mohtamohit/CppSharp,inordertotest/CppSharp
src/Generator/Generators/Template.cs
src/Generator/Generators/Template.cs
namespace Cxxi.Generators { public abstract class TextTemplate : TextGenerator { private const uint DefaultIndent = 4; private const uint MaxIndent = 80; public Driver Driver { get; set; } public DriverOptions Options { get; set; } public Library Library { get; set; } public ILibrary Transform; public TranslationUnit TranslationUnit { get; set; } public abstract string FileExtension { get; } public abstract void Generate(); protected TextTemplate(Driver driver, TranslationUnit unit) { Driver = driver; Options = driver.Options; Library = driver.Library; Transform = driver.Transform; TranslationUnit = unit; } public static bool CheckIgnoreFunction(Class @class, Function function) { if (function.Ignore) return true; if (function is Method) return CheckIgnoreMethod(@class, function as Method); return false; } public static bool CheckIgnoreMethod(Class @class, Method method) { if (method.Ignore) return true; var isEmptyCtor = method.IsConstructor && method.Parameters.Count == 0; if (@class.IsValueType && isEmptyCtor) return true; if (method.IsCopyConstructor || method.IsMoveConstructor) return true; if (method.IsDestructor) return true; if (method.OperatorKind == CXXOperatorKind.Equal) return true; if (method.Kind == CXXMethodKind.Conversion) return true; if (method.Access != AccessSpecifier.Public) return true; return false; } public static bool CheckIgnoreField(Class @class, Field field) { if (field.Ignore) return true; if (field.Access != AccessSpecifier.Public) return true; return false; } } }
namespace Cxxi.Generators { public abstract class TextTemplate : TextGenerator { private const uint DefaultIndent = 4; private const uint MaxIndent = 80; public Driver Driver { get; set; } public DriverOptions Options { get; set; } public Library Library { get; set; } public ILibrary Transform; public TranslationUnit TranslationUnit { get; set; } public abstract string FileExtension { get; } public abstract void Generate(); protected TextTemplate(Driver driver, TranslationUnit unit) { Driver = driver; Options = driver.Options; Library = driver.Library; Transform = driver.Transform; TranslationUnit = unit; } public static bool CheckIgnoreFunction(Class @class, Function function) { if (function.Ignore) return true; if (function is Method) return CheckIgnoreMethod(@class, function as Method); return false; } public static bool CheckIgnoreMethod(Class @class, Method method) { if (method.Ignore) return true; bool isEmptyCtor = method.IsConstructor && method.Parameters.Count == 0; if (@class.IsValueType && isEmptyCtor) return true; if (method.IsCopyConstructor || method.IsMoveConstructor) return true; if (method.IsDestructor) return true; if (method.OperatorKind == CXXOperatorKind.Equal) return true; if (method.Kind == CXXMethodKind.Conversion) return true; if (method.Access != AccessSpecifier.Public) return true; return false; } public static bool CheckIgnoreField(Class @class, Field field) { if (field.Ignore) return true; if (field.Access != AccessSpecifier.Public) return true; return false; } } }
mit
C#
100f8e4fb7e51349c8a48e2b52632053028cedc8
Add reflection exception log function
caronyan/CSharpRecipe
CSharpRecipe/Recipe.DebugAndException/ReflectException.cs
CSharpRecipe/Recipe.DebugAndException/ReflectException.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace Recipe.DebugAndException { public static class ReflectException { public static void ReflectionException() { Type reflectedClass = typeof(ReflectException); try { MethodInfo methodToInvoke = reflectedClass.GetMethod("TestInvoke"); methodToInvoke?.Invoke(null, null); } catch (Exception ex) { Console.WriteLine(ex.ToShortDisplayString()); } } public static void TestInvoke() { throw new Exception("Thrown from invoked method."); } } public static class ExceptionDisplayExtention { public static string ToShortDisplayString(this Exception ex) { StringBuilder displayText = new StringBuilder(); WriteExceptionShortDetail(displayText, ex); foreach (Exception inner in ex.GetNestedExceptionList()) { displayText.AppendFormat("**** INNEREXCEPTION START ****{0}", Environment.NewLine); WriteExceptionShortDetail(displayText, inner); displayText.AppendFormat("**** INNEREXCEPTION END ****{0}{0}", Environment.NewLine); } return displayText.ToString(); } public static IEnumerable<Exception> GetNestedExceptionList(this Exception ex) { Exception current = ex; do { current = current.InnerException; if (current != null) { yield return current; } } while (current != null); } public static void WriteExceptionShortDetail(StringBuilder builder, Exception ex) { builder.AppendFormat("Message:{0}{1}", ex.Message, Environment.NewLine); builder.AppendFormat("Type:{0}{1}", ex.GetType(), Environment.NewLine); builder.AppendFormat("Source:{0}{1}", ex.Source, Environment.NewLine); builder.AppendFormat("TargetSite:{0}{1}", ex.TargetSite, Environment.NewLine); } } }
mit
C#
1679051662d8999e5597ef52c98056fbd95f452b
Create Form.cs
CitrusCurse/PrintScreenAlternative
Form.cs
Form.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace PrintScreenAlternative { public partial class Screenshot : Form { #region Notification Icon Icon logoIcon; NotifyIcon theIcon; #endregion public Screenshot() { InitializeComponent(); #region Icon logoIcon = new Icon("prntscrnicn.ico"); theIcon = new NotifyIcon(); theIcon.Icon = logoIcon; theIcon.Visible = true; #endregion #region Context Menu & Hiding Form ContextMenu contextMenu = new ContextMenu(); theIcon.ContextMenu = contextMenu; theIcon.MouseClick += theIcon_MouseClick; this.WindowState = FormWindowState.Minimized; this.ShowInTaskbar = false; #endregion #region Popup Dialog Box //Goal: Configure this to only appear the first time the user uses the application until shut down MessageBox.Show( "Welcome to PrintScreen Alternative!\nLeft click the icon in the task tray to copy to the clipboard.\nRight click the icon to copy to clipboard and to save the image.", "PrintScreen Alternative: Coded by Kristina Powell", MessageBoxButtons.OK, MessageBoxIcon.None); #endregion } #region Hidden: exitMenuItem_Click Archived Values /*void exitMenuItem_Click(object sender, EventArgs e) { this.Close(); Application.Exit(); }*/ #endregion void theIcon_MouseClick(object sender, MouseEventArgs e) { #region Variable Declaration & Get Initial Clipboard Image SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Images|*.png;*.bmp;*.jpg"; ImageFormat format = ImageFormat.Png; Bitmap img; SendKeys.Send("{PRTSC}"); img = (Bitmap)Clipboard.GetImage(); Thread.Sleep(500); #endregion #region Right Click: Print Screen & Save File if (e.Button == MouseButtons.Right) { SendKeys.Send("{PRTSC}"); Thread.Sleep(500); img = (Bitmap)Clipboard.GetImage(); if (sfd.ShowDialog() == DialogResult.OK) { string ext = Path.GetExtension(sfd.FileName); switch (ext) { case ".jpg": format = ImageFormat.Jpeg; break; case ".bmp": format = ImageFormat.Bmp; break; case ".png": format = ImageFormat.Png; break; } img.Save(sfd.FileName, format); } theIcon.Dispose(); this.Close(); Application.Exit(); } #endregion #region Left Click: Print Screen if (e.Button == MouseButtons.Left) { Thread.Sleep(50); SendKeys.Send("{PRTSC}"); theIcon.Dispose(); this.Close(); Application.Exit(); } #endregion } } }
mit
C#
972857a3d40d606659c78e46e599de497416e2f7
Add ThereIsNoSpoon.cs
ReddwarfCro/CodingGame
ThereIsNoSpoon.cs
ThereIsNoSpoon.cs
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; /** * Don't let the machines win. You are humanity's last hope... **/ public class Dot { public int dotX { get; set; } public int dotY { get; set; } public int rightX { get; set; } public int rightY { get; set; } public int bottomX { get; set; } public int bottomY { get; set; } public Dot(int x, int y) { dotX = x; dotY = y; } } public class Player { public static void Main(string[] args) { int width = int.Parse(Console.ReadLine()); // the number of cells on the X axis int height = int.Parse(Console.ReadLine()); // the number of cells on the Y axis List<Dot> dot = new List<Dot>(); for (int i = 0; i < height; i++) { string line = Console.ReadLine(); // width characters, each either 0 or . int x = GetNextDot(line, 0); while (x != -1) { x = GetNextDot(line, x); dot.Add(new Dot(x, i)); x = GetNextDot(line, x + 1); }; } dot.ForEach( d => { var rightNeighbour = dot.Where(w => w.dotX > d.dotX && w.dotY == d.dotY).OrderBy(o => o.dotX).FirstOrDefault(); d.rightX = rightNeighbour == null ? -1 : rightNeighbour.dotX; d.rightY = rightNeighbour == null ? -1 : rightNeighbour.dotY; var bottomNeighbour = dot.Where(w => w.dotY > d.dotY && w.dotX== d.dotX).OrderBy(o => o.dotY).FirstOrDefault(); d.bottomX = bottomNeighbour == null ? -1 : bottomNeighbour.dotX; d.bottomY = bottomNeighbour == null ? -1 : bottomNeighbour.dotY; } ); dot.ForEach(d => Console.WriteLine(d.dotX + " " + d.dotY + " " + d.rightX + " " + d.rightY + " " + d.bottomX + " " + d.bottomY)); // Write an action using Console.WriteLine() // To debug: Console.Error.WriteLine("Debug messages..."); } public static int GetNextDot(string line, int start) { int retval = line.IndexOf('0',start); return retval; } }
mit
C#
5dc0383b768921505ea426bd20a9e725e21c3f87
Create PreventSkippingETAS.cs
Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder
PathfinderAPI/BaseGameFixes/PreventSkippingETAS.cs
PathfinderAPI/BaseGameFixes/PreventSkippingETAS.cs
using System; using Hacknet; using Hacknet.Effects; using HarmonyLib; namespace Pathfinder.BaseGameFixes { [HarmonyPatch] internal static class PreventSkippingETAS { [HarmonyPrefix] [HarmonyPatch(typeof(Programs), nameof(Programs.reboot))] internal static bool RebootPrefix(string[] args, OS os) { if (os.TraceDangerSequence.IsActive && (os.connectedComp == null || os.connectedComp == os.thisComputer)) { os.write("REBOOT ERROR: OS reports critical action already in progress."); return false; } return true; } [HarmonyPostfix] [HarmonyPatch(typeof(OS), nameof(OS.thisComputerCrashed))] [HarmonyPatch(typeof(OS), nameof(OS.rebootThisComputer))] internal static void ETASGameover(OS __instance) { if (__instance.TraceDangerSequence.IsActive) { __instance.TraceDangerSequence.timeThisState = 0f; __instance.TraceDangerSequence.state = TraceDangerSequence.TraceDangerState.Gameover; __instance.TraceDangerSequence.CancelTraceDangerSequence(); Game1.getSingleton().Exit(); } } } }
mit
C#
293fafe0ec015b371f40c02b6d17703b76592b81
Add Message tests
RichLogan/CiscoSpark-UnityProject,RichLogan/CiscoSpark-UnityProject
SparkUnity/Assets/Cisco/Spark/Tests/TestMessage.cs
SparkUnity/Assets/Cisco/Spark/Tests/TestMessage.cs
using UnityEngine; using Cisco.Spark; /// <summary> /// Class to test the <see cref="Cisco.Spark.Message"/> functionality. /// </summary> public class TestMessage : MonoBehaviour { // Run all tests void Start () { int errorCount = 0; Debug.Log ("Running Message tests"); // Create a room for tests var testRoom = new Room ("Test Room (CiscoSpark-UnitySDK", null); StartCoroutine (testRoom.Commit (error => { // Failed to create test room if (error != null) { errorCount++; Debug.LogError("Couldn't create target Room"); } }, room => { // Test Room successful testRoom = room; if (testRoom.Id == null) { errorCount++; Debug.LogError ("Could not create target Room"); } // Create a new Message var newMessage = new Message (); newMessage.RoomId = testRoom.Id; newMessage.Text = "Test message"; // Commit Message StartCoroutine (newMessage.Commit (error => { if (error != null) { errorCount++; Debug.LogError("Couldn't commit Message: " + error.Message); } }, message => { newMessage = message; // List Messages From Room StartCoroutine (Message.ListMessages (testRoom.Id, error => { if (error != null) { errorCount++; Debug.LogError("Couldn't list Messages: " + error.Message); } }, messages => { // Check Message was successful if (messages [messages.Count - 1].Text != "Test message") { Debug.LogError ("Create Message Failed!"); errorCount++; } else { Debug.Log ("Create Message Passed!"); } // Delete the message StartCoroutine (newMessage.Delete (error => { if (error != null) { errorCount++; Debug.LogError("Couldn't delete message: " + error.Message); } }, result => StartCoroutine (Message.GetMessageDetails (newMessage.Id, error => { // This should error as the message has been deleted Debug.Log ("Successfully failed to get delete message details"); // Clean up test Room StartCoroutine (testRoom.Delete (deleteError => { if (deleteError != null) { errorCount++; Debug.LogError ("Couldn't delete Test Room: " + deleteError.Message); } }, delete => { // Finish and Report Debug.Log ("Finished Running Message Tests"); if (errorCount == 0) { Debug.Log ("All tests passed!"); } else { Debug.LogError (errorCount + " tests failed!"); } })); }, success => { if (success != null) { errorCount++; Debug.Log ("Shouldn't be able to get details for deleted message"); } })))); })); })); })); } }
apache-2.0
C#
0d5a006adadcba216c42d969fe6972cd31a283dc
Remove testing message in PackageNodeImpl
tcNickolas/reef,dougmsft/reef,markusweimer/incubator-reef,afchung/incubator-reef,apache/incubator-reef,afchung/reef,yunseong/incubator-reef,dongjoon-hyun/reef,yunseong/incubator-reef,zerg-junior/incubator-reef,anupam128/reef,dkm2110/veyor,zerg-junior/incubator-reef,anupam128/reef,shravanmn/reef,shulmanb/reef,jwang98052/incubator-reef,tcNickolas/reef,apache/reef,markusweimer/incubator-reef,afchung/reef,singlis/reef,tcNickolas/incubator-reef,markusweimer/reef,jwang98052/incubator-reef,dkm2110/veyor,jwang98052/incubator-reef,tcNickolas/incubator-reef,nachocano/incubator-reef,jwang98052/incubator-reef,zerg-junior/incubator-reef,dafrista/incubator-reef,yunseong/reef,gyeongin/reef,dafrista/incubator-reef,jsjason/incubator-reef,dkm2110/veyor,yunseong/reef,jsjason/incubator-reef,markusweimer/incubator-reef,tcNickolas/reef,shravanmn/reef,dafrista/incubator-reef,shulmanb/reef,apache/reef,afchung/reef,jwang98052/reef,shravanmn/reef,jwang98052/reef,gyeongin/reef,afchung/incubator-reef,dougmsft/reef,yunseong/reef,apache/incubator-reef,nachocano/incubator-reef,shulmanb/reef,dougmsft/reef,nachocano/incubator-reef,dongjoon-hyun/incubator-reef,jwang98052/reef,shravanmn/reef,dkm2110/veyor,afchung/reef,markusweimer/reef,dongjoon-hyun/reef,yunseong/incubator-reef,dongjoon-hyun/reef,yunseong/reef,tcNickolas/incubator-reef,jwang98052/incubator-reef,singlis/reef,dkm2110/veyor,apache/reef,dougmsft/reef,shravanmn/reef,yunseong/reef,nachocano/incubator-reef,yunseong/incubator-reef,jsjason/incubator-reef,apache/incubator-reef,nachocano/incubator-reef,apache/reef,tcNickolas/reef,anupam128/reef,gyeongin/reef,markusweimer/incubator-reef,motus/reef,dongjoon-hyun/reef,dongjoon-hyun/incubator-reef,dougmsft/reef,anupam128/reef,markusweimer/reef,zerg-junior/incubator-reef,singlis/reef,afchung/incubator-reef,afchung/reef,yunseong/reef,apache/reef,shravanmn/reef,dougmsft/reef,gyeongin/reef,gyeongin/reef,gyeongin/reef,gyeongin/reef,dkm2110/Microsoft-cisl,dongjoon-hyun/incubator-reef,tcNickolas/reef,singlis/reef,apache/incubator-reef,afchung/reef,dafrista/incubator-reef,markusweimer/incubator-reef,zerg-junior/incubator-reef,tcNickolas/reef,markusweimer/incubator-reef,jsjason/incubator-reef,dkm2110/veyor,markusweimer/reef,afchung/incubator-reef,afchung/incubator-reef,jwang98052/reef,jsjason/incubator-reef,yunseong/incubator-reef,shulmanb/reef,yunseong/reef,dafrista/incubator-reef,dongjoon-hyun/incubator-reef,dkm2110/Microsoft-cisl,singlis/reef,anupam128/reef,tcNickolas/incubator-reef,motus/reef,dongjoon-hyun/incubator-reef,singlis/reef,afchung/reef,dafrista/incubator-reef,motus/reef,apache/incubator-reef,dkm2110/Microsoft-cisl,shravanmn/reef,anupam128/reef,tcNickolas/incubator-reef,afchung/incubator-reef,dkm2110/veyor,nachocano/incubator-reef,jwang98052/incubator-reef,dkm2110/Microsoft-cisl,shulmanb/reef,dougmsft/reef,dongjoon-hyun/reef,tcNickolas/incubator-reef,shulmanb/reef,motus/reef,apache/incubator-reef,dongjoon-hyun/reef,tcNickolas/reef,yunseong/incubator-reef,dongjoon-hyun/incubator-reef,markusweimer/reef,dkm2110/Microsoft-cisl,yunseong/incubator-reef,singlis/reef,nachocano/incubator-reef,dongjoon-hyun/incubator-reef,afchung/incubator-reef,jwang98052/reef,motus/reef,jwang98052/reef,motus/reef,apache/reef,dafrista/incubator-reef,jwang98052/incubator-reef,dkm2110/Microsoft-cisl,apache/incubator-reef,jwang98052/reef,zerg-junior/incubator-reef,jsjason/incubator-reef,dkm2110/Microsoft-cisl,tcNickolas/incubator-reef,markusweimer/reef,apache/reef,jsjason/incubator-reef,shulmanb/reef,anupam128/reef,zerg-junior/incubator-reef,dongjoon-hyun/reef,motus/reef,markusweimer/incubator-reef,markusweimer/reef
lang/cs/Org.Apache.REEF.Tang/Implementations/ClassHierarchy/PackageNodeImpl.cs
lang/cs/Org.Apache.REEF.Tang/Implementations/ClassHierarchy/PackageNodeImpl.cs
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using Org.Apache.REEF.Tang.Types; namespace Org.Apache.REEF.Tang.Implementations.ClassHierarchy { public class PackageNodeImpl : AbstractNode, IPackageNode { public PackageNodeImpl(INode parent, String name, String fullName) : base(parent, name, fullName) { } public PackageNodeImpl() : base(null, "", "[root node]") { } /** * Unlike normal nodes, the root node needs to take the package name of its * children into account. Therefore, we use the full name as the key when * we insert nodes into the root. */ public override void Add(INode n) { children.Add(n.GetFullName(), n); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using Org.Apache.REEF.Tang.Types; namespace Org.Apache.REEF.Tang.Implementations.ClassHierarchy { public class PackageNodeImpl : AbstractNode, IPackageNode { public PackageNodeImpl(INode parent, String name, String fullName) : base(parent, name, fullName) { } public PackageNodeImpl() : base(null, "", "[root node]") { } /** * Unlike normal nodes, the root node needs to take the package name of its * children into account. Therefore, we use the full name as the key when * we insert nodes into the root. */ public override void Add(INode n) { if (children.Count == 289) { Console.WriteLine("Test"); } children.Add(n.GetFullName(), n); } } }
apache-2.0
C#
918a174be5c494bedd75bce3ffcc688ea8ee4532
Create Global Supressions for CA warnings on THNETII.CommandLine.Hosting
thnetii/dotnet-common
src/THNETII.CommandLine.Hosting/GlobalSuppressions.cs
src/THNETII.CommandLine.Hosting/GlobalSuppressions.cs
 // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Reliability", "CA2007: Consider calling ConfigureAwait on the awaited task")] [assembly: SuppressMessage("Design", "CA1062: Validate arguments of public methods")] [assembly: SuppressMessage("Globalization", "CA1303: Do not pass literals as localized parameters")]
mit
C#
e49d8d0878c9efc5faebad745171cf02e43a6152
Add test coverage of login dialog
peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu
osu.Game.Tests/Visual/Menus/TestSceneLoginPanel.cs
osu.Game.Tests/Visual/Menus/TestSceneLoginPanel.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; using osu.Framework.Testing; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays.Login; namespace osu.Game.Tests.Visual.Menus { [TestFixture] public class TestSceneLoginPanel : OsuManualInputManagerTestScene { private LoginPanel loginPanel; [SetUpSteps] public void SetUpSteps() { AddStep("create login dialog", () => { Add(loginPanel = new LoginPanel { Anchor = Anchor.Centre, Origin = Anchor.Centre, Width = 0.5f, }); }); } [Test] public void TestBasicLogin() { AddStep("logout", () => API.Logout()); AddStep("enter password", () => loginPanel.ChildrenOfType<OsuPasswordTextBox>().First().Text = "password"); AddStep("submit", () => loginPanel.ChildrenOfType<OsuButton>().First(b => b.Text.ToString() == "Sign in").TriggerClick()); } } }
mit
C#
3ea4be029e1cf01a02c90c901e8e13adcf410ffa
Add .net 4.5 compatibility shim classes
fake-organization/octokit.net,hitesh97/octokit.net,ivandrofly/octokit.net,gabrielweyer/octokit.net,Red-Folder/octokit.net,devkhan/octokit.net,shiftkey/octokit.net,ChrisMissal/octokit.net,ivandrofly/octokit.net,SmithAndr/octokit.net,Sarmad93/octokit.net,cH40z-Lord/octokit.net,nsrnnnnn/octokit.net,geek0r/octokit.net,octokit-net-test-org/octokit.net,mminns/octokit.net,dlsteuer/octokit.net,shana/octokit.net,shana/octokit.net,chunkychode/octokit.net,forki/octokit.net,octokit-net-test/octokit.net,nsnnnnrn/octokit.net,chunkychode/octokit.net,bslliw/octokit.net,gabrielweyer/octokit.net,Sarmad93/octokit.net,TattsGroup/octokit.net,eriawan/octokit.net,editor-tools/octokit.net,thedillonb/octokit.net,devkhan/octokit.net,octokit-net-test-org/octokit.net,TattsGroup/octokit.net,octokit/octokit.net,thedillonb/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shiftkey/octokit.net,khellang/octokit.net,editor-tools/octokit.net,alfhenrik/octokit.net,khellang/octokit.net,SamTheDev/octokit.net,darrelmiller/octokit.net,shiftkey-tester/octokit.net,gdziadkiewicz/octokit.net,gdziadkiewicz/octokit.net,SLdragon1989/octokit.net,mminns/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,brramos/octokit.net,adamralph/octokit.net,yonglehou/octokit.net,yonglehou/octokit.net,alfhenrik/octokit.net,hahmed/octokit.net,magoswiat/octokit.net,rlugojr/octokit.net,shiftkey-tester/octokit.net,daukantas/octokit.net,hahmed/octokit.net,fffej/octokit.net,SamTheDev/octokit.net,SmithAndr/octokit.net,eriawan/octokit.net,kolbasov/octokit.net,michaKFromParis/octokit.net,takumikub/octokit.net,rlugojr/octokit.net,M-Zuber/octokit.net,kdolan/octokit.net,dampir/octokit.net,M-Zuber/octokit.net,octokit/octokit.net,naveensrinivasan/octokit.net,dampir/octokit.net
Octokit/Helpers/Net45CompatibilityShim.cs
Octokit/Helpers/Net45CompatibilityShim.cs
// ---------------------------------------------------- // THIS WHOLE File CAN GO AWAY WHEN WE TARGET 4.5 ONLY // ---------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Octokit { [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public interface IReadOnlyDictionary<TKey, TValue> : IReadOnlyCollection<KeyValuePair<TKey, TValue>> { bool ContainsKey(TKey key); bool TryGetValue(TKey key, out TValue value); TValue this[TKey key] { get; } IEnumerable<TKey> Keys { get; } IEnumerable<TValue> Values { get; } } public interface IReadOnlyCollection<out T> : IEnumerable<T> { int Count { get; } } public class ReadOnlyCollection<TItem> : IReadOnlyCollection<TItem> { readonly List<TItem> _source; public ReadOnlyCollection(IEnumerable<TItem> source) { _source = new List<TItem>(source); } public IEnumerator<TItem> GetEnumerator() { return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return _source.Count; } } } [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public class ReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue> { readonly IDictionary<TKey, TValue> _source; public ReadOnlyDictionary(IDictionary<TKey, TValue> source) { _source = new Dictionary<TKey, TValue>(source); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _source.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return _source.Count; } } public bool ContainsKey(TKey key) { return _source.ContainsKey(key); } public bool TryGetValue(TKey key, out TValue value) { return _source.TryGetValue(key, out value); } public TValue this[TKey key] { get { return _source[key]; } } public IEnumerable<TKey> Keys { get { return _source.Keys; } } public IEnumerable<TValue> Values { get { return _source.Values; } } } }
mit
C#
7c02e29017f66491ab529c63f552643f60958493
Add iOS callback classes
one-signal/OneSignal-Xamarin-SDK,one-signal/OneSignal-Xamarin-SDK
Com.OneSignal.iOS/OneSignalCallbacks.cs
Com.OneSignal.iOS/OneSignalCallbacks.cs
using System.Collections.Generic; using Laters; namespace Com.OneSignal { public partial class OneSignalImplementation { private delegate void BooleanResponseDelegate(bool response); private delegate void StringResponseDelegate(string response); private delegate void DictionaryResponseDelegate(string response); private interface ICallbackProxy<in TReturn> { void OnResponse(TReturn response); } private abstract class CallbackProxy<TReturn> : BaseLater<TReturn>, ICallbackProxy<TReturn> { public abstract void OnResponse(TReturn response); } private sealed class BooleanCallbackProxy : CallbackProxy<bool> { public override void OnResponse(bool response) => _complete(response); } private sealed class StringCallbackProxy : CallbackProxy<string> { public override void OnResponse(string response) => _complete(response); } private sealed class DictionaryCallbackProxy : CallbackProxy<Dictionary<string, object>> { public override void OnResponse(Dictionary<string, object> response) => _complete(response); } } }
mit
C#
ba4169309f202d6dfb1c92e6cdeb5b466fefd4fd
add unit tests for Plot (forgot to include in rev 874)
GeertvanHorrik/oxyplot,Jofta/oxyplot,lynxkor/oxyplot,ze-pequeno/oxyplot,Sbosanquet/oxyplot,bbqchickenrobot/oxyplot,GeertvanHorrik/oxyplot,Rustemt/oxyplot,shoelzer/oxyplot,br111an/oxyplot,objorke/oxyplot,HermanEldering/oxyplot,Sbosanquet/oxyplot,olegtarasov/oxyplot,svendu/oxyplot,sevoku/oxyplot,mattleibow/oxyplot,BRER-TECH/oxyplot,jeremyiverson/oxyplot,freudenthal/oxyplot,mattleibow/oxyplot,Kaplas80/oxyplot,HermanEldering/oxyplot,sevoku/oxyplot,TheAlmightyBob/oxyplot,lynxkor/oxyplot,as-zhuravlev/oxyplot_wpf_fork,as-zhuravlev/oxyplot_wpf_fork,zur003/oxyplot,bbqchickenrobot/oxyplot,Mitch-Connor/oxyplot,TheAlmightyBob/oxyplot,shoelzer/oxyplot,lynxkor/oxyplot,TheAlmightyBob/oxyplot,DotNetDoctor/oxyplot,br111an/oxyplot,Mitch-Connor/oxyplot,Rustemt/oxyplot,Isolocis/oxyplot,Sbosanquet/oxyplot,olegtarasov/oxyplot,freudenthal/oxyplot,Kaplas80/oxyplot,jeremyiverson/oxyplot,bbqchickenrobot/oxyplot,GeertvanHorrik/oxyplot,NilesDavis/oxyplot,svendu/oxyplot,objorke/oxyplot,Mitch-Connor/oxyplot,H2ONaCl/oxyplot,BRER-TECH/oxyplot,as-zhuravlev/oxyplot_wpf_fork,H2ONaCl/oxyplot,Jonarw/oxyplot,freudenthal/oxyplot,oxyplot/oxyplot,svendu/oxyplot,H2ONaCl/oxyplot,shoelzer/oxyplot,DotNetDoctor/oxyplot,Rustemt/oxyplot,jeremyiverson/oxyplot,br111an/oxyplot,objorke/oxyplot
Source/OxyPlot.Wpf.Tests/PlotTests.cs
Source/OxyPlot.Wpf.Tests/PlotTests.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PlotTests.cs" company="OxyPlot"> // The MIT License (MIT) // // Copyright (c) 2012 Oystein Bjorke // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <summary> // Provides unit tests for the <see cref="Plot" /> class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.Wpf.Tests { using System.Threading.Tasks; using NUnit.Framework; /// <summary> /// Provides unit tests for the <see cref="Plot"/> class. /// </summary> [TestFixture] public class PlotTests { /// <summary> /// Provides unit tests for the <see cref="Plot.ActualModel"/> property. /// </summary> public class ActualModel { /// <summary> /// Gets the actual model from the same thread as created the <see cref="Plot"/>. /// </summary> [Test] public void GetFromSameThread() { var model = new PlotModel(); var plot = new Plot { Model = model }; Assert.AreEqual(model, plot.ActualModel); } /// <summary> /// Gets the actual model from a thread different from the one that created the <see cref="Plot"/>. /// </summary> [Test] public void GetFromOtherThread() { var model = new PlotModel(); var plot = new Plot { Model = model }; PlotModel actualModel = null; Task.Factory.StartNew(() => actualModel = plot.ActualModel).Wait(); Assert.AreEqual(model, actualModel); } } } }
mit
C#
387e2ba91f08f020740fa79d8d00df8956797f3b
Add view model factory interface
Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife
PhotoLife/PhotoLife.Web/Factories/IViewModelFactory.cs
PhotoLife/PhotoLife.Web/Factories/IViewModelFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PhotoLife.Factories { interface IViewModelFactory { } }
mit
C#
0f21e881cf869d752e8a08996264656888a5c0da
Create ModelNameAttribute.cs
MingLu8/Nancy.WebApi.HelpPages
src/Nancy.WebApi.HelpPages.Demo/HelpPage/ModelDescriptions/ModelNameAttribute.cs
src/Nancy.WebApi.HelpPages.Demo/HelpPage/ModelDescriptions/ModelNameAttribute.cs
using System; namespace WebApplication1.Areas.HelpPage.ModelDescriptions { /// <summary> /// Use this attribute to change the name of the <see cref="ModelDescription"/> generated for a type. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] public sealed class ModelNameAttribute : Attribute { public ModelNameAttribute(string name) { Name = name; } public string Name { get; private set; } } }
mit
C#
928bd0df08b06139d57162675ccf2896966868d1
Add an expression interpretation bug test
EamonNerbonne/ExpressionToCode
ExpressionToCodeTest/ExpressionInterpretationBug.cs
ExpressionToCodeTest/ExpressionInterpretationBug.cs
using System; using System.Linq.Expressions; using Xunit; namespace ExpressionToCodeTest { public class ExpressionInterpretationBug { struct AStruct { public int AValue; } class SomethingMutable { public AStruct AStructField; } static Expression<Func<T>> Expr<T>(Expression<Func<T>> e) => e; [Fact] public void DotNetCoreIsNotBuggy() { var expr_compiled = Expr(() => new SomethingMutable { AStructField = { AValue = 2 } }).Compile(false)(); Assert.Equal(2, expr_compiled.AStructField.AValue); var expr_interpreted = Expr(() => new SomethingMutable { AStructField = { AValue = 2 } }).Compile(true)(); Assert.Equal(2, expr_interpreted.AStructField.AValue); } } }
apache-2.0
C#
da700f6839455e91fecd12e38efbf9dc0391e42b
Add Question Model
kphillpotts/TrueOrFalse
TrueOrFalse/TrueOrFalse/TrueOrFalse/Models/Question.cs
TrueOrFalse/TrueOrFalse/TrueOrFalse/Models/Question.cs
using System; namespace TrueOrFalse { public class Question { public enum Category { None = 0, Nature = 1, Sport = 2, People = 3, ManMade = 4 } public Question (string text, bool answer, Category category) { QuestionText = text; QuestionAnswer = answer; QuestionCategory = category; } public string QuestionText {get; private set;} public bool QuestionAnswer {get; private set;} public Category QuestionCategory {get; private set;} } }
mit
C#
fd73dd9470f05416d9720e2fb841f9438534383f
Add benchmarks for bindable binding
peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework
osu.Framework.Benchmarks/BenchmarkBindableInstantiation.cs
osu.Framework.Benchmarks/BenchmarkBindableInstantiation.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 BenchmarkDotNet.Attributes; using osu.Framework.Bindables; namespace osu.Framework.Benchmarks { public class BenchmarkBindableInstantiation { private Bindable<int> bindable; [GlobalSetup] public void GlobalSetup() => bindable = new Bindable<int>(); /// <summary> /// Creates an instance of the bindable directly by construction. /// </summary> [Benchmark(Baseline = true)] public Bindable<int> CreateInstanceViaConstruction() => new Bindable<int>(); /// <summary> /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type, object[])"/>. /// This used to be how <see cref="Bindable{T}.GetBoundCopy"/> creates an instance before binding, which has turned out to be inefficient in performance. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaActivatorWithParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), 0); /// <summary> /// Creates an instance of the bindable via <see cref="Activator.CreateInstance(Type)"/>. /// More performant than <see cref="CreateInstanceViaActivatorWithParams"/>, due to not passing parameters to <see cref="Activator"/> during instance creation. /// </summary> [Benchmark] public Bindable<int> CreateInstanceViaActivatorWithoutParams() => (Bindable<int>)Activator.CreateInstance(typeof(Bindable<int>), true); } }
mit
C#
83b6e0f30c674b19607cac50b79d899e036721a5
Implement grouped difficulty icon
UselessToucan/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,johnneijzen/osu,peppy/osu,2yangk23/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,ppy/osu,peppy/osu-new,smoogipooo/osu,UselessToucan/osu,ZLima12/osu,EVAST9919/osu
osu.Game/Beatmaps/Drawables/GroupedDifficultyIcon.cs
osu.Game/Beatmaps/Drawables/GroupedDifficultyIcon.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.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets; using osuTK.Graphics; namespace osu.Game.Beatmaps.Drawables { public class GroupedDifficultyIcon : DifficultyIcon { private readonly OsuSpriteText counter; private List<BeatmapInfo> beatmaps; protected List<BeatmapInfo> Beatmaps { get => beatmaps; set { beatmaps = value; updateDisplay(); } } public GroupedDifficultyIcon(List<BeatmapInfo> beatmaps, RulesetInfo ruleset, Color4 counterColour) : base(null, ruleset, false) { this.beatmaps = beatmaps; AddInternal(counter = new OsuSpriteText { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Padding = new MarginPadding { Left = Size.X }, Margin = new MarginPadding { Left = 2, Right = 5 }, Font = OsuFont.GetFont(size: 14, weight: FontWeight.SemiBold), Colour = counterColour, }); updateDisplay(); } private void updateDisplay() { if (beatmaps == null || beatmaps.Count == 0) return; Beatmap = beatmaps.OrderBy(b => b.StarDifficulty).Last(); counter.Text = beatmaps.Count.ToString(); } } }
mit
C#
33e808f9bae7279057164e50a25bf6d68414db8e
Replace missing file lost during merge
planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS
src/Orchard.Web/Modules/Orchard.Alias/Implementation/Updater/AliasHolderUpdater.cs
src/Orchard.Web/Modules/Orchard.Alias/Implementation/Updater/AliasHolderUpdater.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Orchard.Alias.Implementation.Holder; using Orchard.Alias.Implementation.Storage; namespace Orchard.Alias.Implementation.Updater { public interface IAliasHolderUpdater : IDependency { void Refresh(); } public class AliasHolderUpdater : IAliasHolderUpdater { private readonly IAliasHolder _aliasHolder; private readonly IAliasStorage _storage; private readonly IAliasUpdateCursor _cursor; public AliasHolderUpdater(IAliasHolder aliasHolder, IAliasStorage storage, IAliasUpdateCursor cursor) { _aliasHolder = aliasHolder; _storage = storage; _cursor = cursor; } public void Refresh() { // only retreive aliases which have not been processed yet var aliases = _storage.List(x => x.Id > _cursor.Cursor).ToArray(); // update the last processed id if (aliases.Any()) { _cursor.Cursor = aliases.Last().Item5; _aliasHolder.SetAliases(aliases.Select(alias => new AliasInfo { Path = alias.Item1, Area = alias.Item2, RouteValues = alias.Item3 })); } } } }
bsd-3-clause
C#
49fe40164ae91e8007247c32870bb855c05c9710
Add a static resources library
It423/enigma-simulator,wrightg42/enigma-simulator
Enigma/EnigmaUtilities/Resources.cs
Enigma/EnigmaUtilities/Resources.cs
// Resources.cs // <copyright file="Resources.cs"> This code is protected under the MIT License. </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EnigmaUtilities { /// <summary> /// A static class with commonly used functions throughout multiple classes. /// </summary> public static class Resources { /// <summary> /// Gets the alphabet as a string. /// </summary> public static string Alphabet { get { return "abcdefghijkmnopqrstuvwxyz"; } } /// <summary> /// Performs modulus operations on an integer. /// </summary> /// <param name="i"> The integer to modulus. </param> /// <param name="j"> The integer to modulus by. </param> /// <returns> The integer after modulus operations. </returns> /// <remarks> Performs negative modulus python style. </remarks> public static int Mod(int i, int j) { return ((i % j) + j) % j; } /// <summary> /// Gets the character value of an integer. /// </summary> /// <param name="i"> The integer to convert to a character. </param> /// <returns> The character value of the integer. </returns> public static char ToChar(this int i) { return Alphabet[Mod(i, 26)]; } /// <summary> /// Gets the index in the alphabet of a character. /// </summary> /// <param name="c"> The character to convert to an integer. </param> /// <returns> The integer value of the character. </returns> /// <remarks> Will return -1 if not in the alphabet. </remarks> public static int ToInt(this char c) { return Alphabet.Contains(c) ? Alphabet.IndexOf(c) : -1; } } }
mit
C#
200723b8043a3cd4243ac6f2980da08ab23a186a
Create TowerBuildZone.cs
highnet/Java-101,highnet/Java-101
TowerTDAlpha/TowerBuildZone.cs
TowerTDAlpha/TowerBuildZone.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TowerBuildZone : MonoBehaviour { // Use this for initialization void Start () { } private void OnMouseUp() { BuildingManager bm = GameObject.FindObjectOfType<BuildingManager>(); if (this.transform.childCount == 1 && bm.selectedShopTower != null) // childcount limits creating more than 1 turret per spot. a tower build zone has 1 object child to indicate its location and 1 possible turret attached to it. { ScoreManager sm = GameObject.FindObjectOfType<ScoreManager>(); if (sm.money >= bm.selectedShopTower.GetComponent<Tower>().cost) { Instantiate(bm.selectedShopTower, transform.position, transform.rotation, this.transform); sm.money -= bm.selectedShopTower.GetComponent<Tower>().cost; this.transform.GetChild(0).GetComponent<MeshRenderer>().enabled = false; } } } // Update is called once per frame void Update () { } }
mit
C#
15859860fbe3d320197ba48e1142b9ba2f53a43c
Add namespace & type for experimental work
fsateler/MoreLINQ,fsateler/MoreLINQ,morelinq/MoreLINQ,morelinq/MoreLINQ,ddpruitt/morelinq,ddpruitt/morelinq
MoreLinq/Experimental/ExperimentalEnumerable.cs
MoreLinq/Experimental/ExperimentalEnumerable.cs
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2018 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq.Experimental { using System.Collections.Generic; /// <summary> /// Provides a set of static methods for querying objects that /// implement <see cref="IEnumerable{T}" />. THE METHODS ARE EXPERIMENTAL. /// THEY MAY BE UNSTABLE AND UNTESTED. THEY MAY BE REMOVED FROM A FUTURE /// MAJOR OR MINOR RELEASE AND POSSIBLY WITHOUT NOTICE. USE THEM AT YOUR /// OWN RISK. THE METHODS ARE PUBLISHED FOR FIELD EXPERIMENTATION TO /// SOLICIT FEEDBACK ON THEIR UTILITY AND DESIGN/IMPLEMENTATION DEFECTS. /// </summary> public static partial class ExperimentalEnumerable { } }
apache-2.0
C#
21d6d785b18418e52c884da2a3341e8e37588ba9
Add IntroDisasm
PerfDotNet/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Ky7m/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,adamsitnik/BenchmarkDotNet
samples/BenchmarkDotNet.Samples/Intro/IntroDisasm.cs
samples/BenchmarkDotNet.Samples/Intro/IntroDisasm.cs
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; using BenchmarkDotNet.Environments; namespace BenchmarkDotNet.Samples.Intro { [DryCoreJob, DryMonoJob, DryClrJob(Platform.X86)] [DisassemblyDiagnoser] public class IntroDisasm { [Benchmark] public double Sum() { double res = 0; for (int i = 0; i < 64; i++) res += i; return res; } } }
mit
C#
c2f1f5e57c2025467c1dc1139698dcdecb276f10
Add failing test for compiled queries with Includes
ericgreenmix/marten,mysticmind/marten,ericgreenmix/marten,JasperFx/Marten,ericgreenmix/marten,mysticmind/marten,mdissel/Marten,ericgreenmix/marten,mdissel/Marten,mysticmind/marten,JasperFx/Marten,JasperFx/Marten,mysticmind/marten
src/Marten.Testing/Bugs/compiled_query_problem_with_includes_and_ICompiledQuery_reuse.cs
src/Marten.Testing/Bugs/compiled_query_problem_with_includes_and_ICompiledQuery_reuse.cs
using Marten.Linq; using Marten.Services; using Marten.Services.Includes; using Marten.Testing.Documents; using Shouldly; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Xunit; namespace Marten.Testing.Bugs { public class compiled_query_problem_with_includes_and_ICompiledQuery_reuse : DocumentSessionFixture<IdentityMap> { public class IssueWithUsers : ICompiledListQuery<Issue> { public List<User> Users { get; set; } // Can also work like that: //public List<User> Users => new List<User>(); public Expression<Func<IQueryable<Issue>, IEnumerable<Issue>>> QueryIs() { return query => query.Include<Issue, IssueWithUsers>(x => x.AssigneeId, x => x.Users, JoinType.Inner); } } [Fact] public void can_get_includes_with_compiled_queries() { var user1 = new User(); var user2 = new User(); var issue1 = new Issue { AssigneeId = user1.Id, Title = "Garage Door is busted" }; var issue2 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" }; var issue3 = new Issue { AssigneeId = user2.Id, Title = "Garage Door is busted" }; theSession.Store(user1, user2); theSession.Store(issue1, issue2, issue3); theSession.SaveChanges(); // Issue first query using (var session = theStore.QuerySession()) { var query = new IssueWithUsers(); var issues = session.Query(query).ToArray(); query.Users.Count.ShouldBe(2); issues.Count().ShouldBe(3); query.Users.Any(x => x.Id == user1.Id); query.Users.Any(x => x.Id == user2.Id); } // Issue second query using (var session = theStore.QuerySession()) { var query = new IssueWithUsers(); var issues = session.Query(query).ToArray(); // Should populate this instance of IssueWithUsers query.Users.ShouldNotBeNull(); // Should not re-use a previous instance of IssueWithUsers, which would make the count 4 query.Users.Count.ShouldBe(2); issues.Count().ShouldBe(3); query.Users.Any(x => x.Id == user1.Id); query.Users.Any(x => x.Id == user2.Id); } } } }
mit
C#
037184c5d230dbd5ef12cddca65702a4d9f04020
fix example
stormsw/ladm.rrr
Example1/Program.cs
Example1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Ladm.DataModel; namespace Example1 { class Program { static void Main(string[] args) { using (var ctx = new Ladm.DataModel.LadmDbContext()) { /*Transaction transaction = new Transaction() { Id = 1, TransactionType = new TransactionMetaData() { Id = 1 } }; ctx.Transactions.Add(transaction); ctx.SaveChanges();*/ } } } }
mit
C#
a42e24785d73f312b5a2f3d1b6c4e0510868bdb4
Make test specify UI thread rather than assume
karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS
src/Languages/Editor/Test/Shell/TestShellBase.cs
src/Languages/Editor/Test/Shell/TestShellBase.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.ComponentModel.Design; using System.Threading; using System.Windows.Threading; using Microsoft.Common.Core.Shell; using Microsoft.UnitTests.Core.Threading; namespace Microsoft.Languages.Editor.Test.Shell { public class TestShellBase { public Thread MainThread { get; set; } public int LocaleId => 1033; public TestShellBase() { MainThread = Thread.CurrentThread; } public void ShowErrorMessage(string msg) { } public MessageButtons ShowMessage(string message, MessageButtons buttons) { return MessageButtons.OK; } public void ShowContextMenu(CommandID commandId, int x, int y) { } public string SaveFileIfDirty(string fullPath) => fullPath; public void DoIdle() { Idle?.Invoke(null, EventArgs.Empty); DoEvents(); } public void DispatchOnUIThread(Action action) { UIThreadHelper.Instance.Invoke(action); } public void DoEvents() { var disp = GetDispatcher(); if (disp != null) { DispatcherFrame frame = new DispatcherFrame(); disp.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame); Dispatcher.PushFrame(frame); } } public object ExitFrame(object f) { ((DispatcherFrame)f).Continue = false; return null; } private Dispatcher GetDispatcher() { if (MainThread != null && MainThread.ManagedThreadId == UIThreadHelper.Instance.Thread.ManagedThreadId) { return Dispatcher.FromThread(MainThread); } return null; } public event EventHandler<EventArgs> Idle; #pragma warning disable 0067 public event EventHandler<EventArgs> Terminating; #pragma warning restore 0067 } }
// 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.ComponentModel.Design; using System.Threading; using System.Windows.Threading; using Microsoft.Common.Core.Shell; using Microsoft.UnitTests.Core.Threading; namespace Microsoft.Languages.Editor.Test.Shell { public class TestShellBase { public Thread MainThread { get; set; } public int LocaleId => 1033; public TestShellBase() { MainThread = Thread.CurrentThread; } public void ShowErrorMessage(string msg) { } public MessageButtons ShowMessage(string message, MessageButtons buttons) { return MessageButtons.OK; } public void ShowContextMenu(CommandID commandId, int x, int y) { } public string SaveFileIfDirty(string fullPath) => fullPath; public void DoIdle() { UIThreadHelper.Instance.Invoke(() => { Idle?.Invoke(null, EventArgs.Empty); DoEvents(); }); } public void DispatchOnUIThread(Action action) { UIThreadHelper.Instance.Invoke(action); } public void DoEvents() { var disp = GetDispatcher(); if (disp != null) { DispatcherFrame frame = new DispatcherFrame(); disp.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame); Dispatcher.PushFrame(frame); } } public object ExitFrame(object f) { ((DispatcherFrame)f).Continue = false; return null; } private Dispatcher GetDispatcher() { if (MainThread != null && MainThread.ManagedThreadId == UIThreadHelper.Instance.Thread.ManagedThreadId) { return Dispatcher.FromThread(MainThread); } return null; } public event EventHandler<EventArgs> Idle; #pragma warning disable 0067 public event EventHandler<EventArgs> Terminating; #pragma warning restore 0067 } }
mit
C#
2d605f94b7c7179cc5c63dd9d2290c2dbc966567
Revert "del"
davetimmins/ArcGIS.PCL,davetimmins/ArcGIS.PCL
samples/ArcGIS.PCL.iOS/ArcGIS_PCL_iOSViewController.cs
samples/ArcGIS.PCL.iOS/ArcGIS_PCL_iOSViewController.cs
using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace ArcGIS.PCL.iOS { public partial class ArcGIS_PCL_iOSViewController : UIViewController { public ArcGIS_PCL_iOSViewController () : base ("ArcGIS_PCL_iOSViewController", null) { } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. var gateway = new ArcGISGateway(new JsonDotNetSerializer()); var site = gateway.DescribeSite().Result; } } }
mit
C#
97920eba18079b6ab65764c56d3cb4d67885916b
Create Form1.cs
codedecay/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,RocketSoftware/multivalue-lab,codedecay/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,RocketSoftware/multivalue-lab,RocketSoftware/multivalue-lab,RocketSoftware/multivalue-lab,RocketSoftware/multivalue-lab,RocketSoftware/multivalue-lab,nkesic/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,codedecay/multivalue-lab,RocketSoftware/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,nkesic/multivalue-lab,codedecay/multivalue-lab,RocketSoftware/multivalue-lab,RocketSoftware/multivalue-lab,nkesic/multivalue-lab,nkesic/multivalue-lab
U2-Toolkit/DataAdapter/Form1.cs
U2-Toolkit/DataAdapter/Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using U2.Data.Client; namespace DataAdapter { public partial class Form1 : Form { private U2DataAdapter m_da; private U2CommandBuilder m_U2CommandBuilder; public Form1() { InitializeComponent(); } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void button1_Click(object sender, EventArgs e) { try { this.textBox1.Clear(); var connection_str = System.Configuration.ConfigurationManager.ConnectionStrings["DEMO_UV"]; string s = connection_str.ConnectionString; U2Connection con = new U2Connection(); con.ConnectionString = s; con.Open(); this.textBox1.AppendText("Connected.........................(UniVerse Account)" + Environment.NewLine); U2Command cmd = con.CreateCommand(); cmd.CommandText = "SELECT CUSTID, FNAME,LNAME FROM CUSTOMER"; DataSet ds = new DataSet(); m_da = new U2DataAdapter(cmd); m_da.Fill(ds); m_U2CommandBuilder = new U2CommandBuilder(m_da); this.dataGridView1.DataSource = ds.Tables[0].DefaultView; this.textBox1.AppendText("Done........................." + Environment.NewLine); } catch (Exception e3) { this.textBox1.AppendText(e3.Message); MessageBox.Show(e3.Message); } } private void button2_Click(object sender, EventArgs e) { try { this.textBox1.Clear(); var connection_str = System.Configuration.ConfigurationManager.ConnectionStrings["DEMO_UD"]; string s = connection_str.ConnectionString; U2Connection con = new U2Connection(); con.ConnectionString = s; con.Open(); this.textBox1.AppendText("Connected.........................(UniData Account)" + Environment.NewLine); U2Command cmd = con.CreateCommand(); cmd.CommandText = "SELECT ID, FNAME,LNAME FROM STUDENT_NF_SUB"; DataSet ds = new DataSet(); m_da = new U2DataAdapter(cmd); m_da.Fill(ds); m_U2CommandBuilder = new U2CommandBuilder(m_da); this.dataGridView1.DataSource = ds.Tables[0].DefaultView; this.textBox1.AppendText("Done........................." + Environment.NewLine); } catch (Exception e3) { this.textBox1.AppendText(e3.Message); MessageBox.Show(e3.Message); } } } }
mit
C#
aeb27c1746940c7e79dec21ffaa42c4eb2dc7c79
deploy and TransformerAddColumnExpressionByTableTest
ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins
stankinsv2/solution/StankinsV2/StankinsTestXUnit/TransformerAddColumnExpressionByTable.cs
stankinsv2/solution/StankinsV2/StankinsTestXUnit/TransformerAddColumnExpressionByTable.cs
using FluentAssertions; using Stankins.File; using Stankins.Interfaces; using StankinsObjects; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Xbehave; using Xunit; using static System.Environment; namespace StankinsTestXUnit { [Trait("TransformTrim", "")] [Trait("ExternalDependency", "0")] public class TransformerAddColumnExpressionByTableTest { [Scenario] [Example("Car,Year{NewLine}Ford,2000","Car","'a'+Car","Ford","aFord")] public void TestSimpleCSV(string fileContents,string columnExisting, string newCol, string existingValue, string newValue) { IReceive receiver = null; IDataToSent data=null; var nl = Environment.NewLine; fileContents = fileContents.Replace("{NewLine}", nl); $"When I create the receiver csv for the content {fileContents}".w(() => receiver = new ReceiverCSVText(fileContents)); $"And I read the data".w(async () =>data= await receiver.TransformData(null)); $"Then should be a data".w(() => data.Should().NotBeNull()); $"With a table".w(() => { data.DataToBeSentFurther.Should().NotBeNull(); data.DataToBeSentFurther.Count.Should().Be(1); }); $"and I transform from {columnExisting} to {newCol}".w(async () => data= await new TransformerAddColumnExpressionByTable(data.Metadata.Tables[0].Name,newCol,columnExisting+"_New" ).TransformData(data)); $"The first row should have the values {existingValue} and {newValue}".w(() => { data.DataToBeSentFurther[0].Rows[0][columnExisting].Should().Be(existingValue); data.DataToBeSentFurther[0].Rows[0][columnExisting + "_New"].Should().Be(newValue); }); } } }
mit
C#
24f7f07db7ffb98174008a937de22efdc03ac6e6
Set up timer so that it can't start reducing while previous reduction is still in progress.
modulexcite/ZocMon,ZocDoc/ZocMon,ZocDoc/ZocMon,ZocDoc/ZocMon,modulexcite/ZocMon,modulexcite/ZocMon
source/ZocMonLib.Service.Reduce/ReduceServiceRunner.cs
source/ZocMonLib.Service.Reduce/ReduceServiceRunner.cs
using System; namespace ZocMonLib.Service.Reduce { public class ReduceServiceRunner { private readonly ISystemLogger _logger; private System.Timers.Timer _timer; private readonly ISettings _settings; public ReduceServiceRunner(ISettings settings) { _logger = settings.LoggerProvider.CreateLogger(typeof(ReduceServiceRunner)); _settings = settings; } public void Start() { Log("ReduceServiceRunner - Starting"); if (_settings.Enabled) { Log("ReduceServiceRunner - Timing setup"); _timer = new System.Timers.Timer(_settings.AutoReduceInterval) { AutoReset = false }; _timer.Elapsed += (sender, eventArgs) => { Log(String.Format(" - Executing Reduce Start: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now)); _settings.RecordReduce.ReduceAll(false); Log(String.Format(" - Executing Reduce Finish: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now)); _timer.Start(); }; _timer.Start(); } } public void Stop() { Log("ReduceServiceRunner - Finished"); if (_timer != null) _timer.Stop(); } private void Log(string info) { _logger.Info(info); Console.WriteLine(info); } } }
using System; namespace ZocMonLib.Service.Reduce { public class ReduceServiceRunner { private readonly ISystemLogger _logger; private System.Timers.Timer _timer; private readonly ISettings _settings; public ReduceServiceRunner(ISettings settings) { _logger = settings.LoggerProvider.CreateLogger(typeof(ReduceServiceRunner)); _settings = settings; } public void Start() { Log("ReduceServiceRunner - Starting"); if (_settings.Enabled) { Log("ReduceServiceRunner - Timing setup"); _timer = new System.Timers.Timer(_settings.AutoReduceInterval) { AutoReset = true }; _timer.Elapsed += (sender, eventArgs) => { Log(String.Format(" - Executing Reduce Start: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now)); _settings.RecordReduce.ReduceAll(false); Log(String.Format(" - Executing Reduce Finish: {0:yyyy/MM/dd_HH:mm:ss-fff}", DateTime.Now)); }; _timer.Start(); } } public void Stop() { Log("ReduceServiceRunner - Finished"); if (_timer != null) _timer.Stop(); } private void Log(string info) { _logger.Info(info); Console.WriteLine(info); } } }
apache-2.0
C#
692afd46e2d9d56597d7c16a1051c8004a3ed797
Create radix_sort.cs
iiitv/algos,iiitv/algos,iiitv/algos,iiitv/algos,iiitv/algos,iiitv/algos,iiitv/algos,iiitv/algos
radix_sort/radix_sort.cs
radix_sort/radix_sort.cs
//radix sort algorithm in c# uploaded by elliot37 using System; class radix { static void Main(string[] args) { int[] arr = new int[] { 23,4,2234,3253,46,43,1,23,45,67}; Console.WriteLine("\ngiven array : "); foreach (var num in arr) { Console.Write(" " + num); } sorting(arr); Console.WriteLine("\nafter sorting : "); foreach (var num in arr) { Console.Write(" " + num); } Console.WriteLine("\n"); } static void sorting(int[] arr) { int i, j; int[] temp = new int[arr.Length]; for (int k = 31; k > -1; --k) { j = 0; for (i = 0; i < arr.Length; ++i) { bool t = (arr[i] << k) >= 0; if (k == 0 ? !t : t) arr[i-j] = arr[i]; else temp[j++] = arr[i]; } Array.Copy(temp, 0, arr, arr.Length-j, j); } } }
mit
C#
dbf7e831a6be9a2f304bb2ecfda9bf3cdcef718b
add class VideoEncodingDriver to drive ffmpeg components, and implement CheckVideoForEncoding()
kingsamchen/Eureka,kingsamchen/Eureka,kingsamchen/Eureka,kingsamchen/Eureka,kingsamchen/Eureka,kingsamchen/Eureka,kingsamchen/Eureka,kingsamchen/Eureka
SimpleVideoEncoder/SimpleVideoEncoder/VideoEncodingDriver.cs
SimpleVideoEncoder/SimpleVideoEncoder/VideoEncodingDriver.cs
/* @ 0xCCCCCCCC */ using System; using System.CodeDom; using System.Diagnostics; using System.IO; using System.Reflection; using System.Security.Policy; using Newtonsoft.Json.Linq; namespace SimpleVideoEncoder { public static class VideoEncodingDriver { private static readonly string FFmpegComponentsDir; static VideoEncodingDriver() { var appDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Debug.Assert(appDir != null, "Failed to acquire executable path"); FFmpegComponentsDir = Path.Combine(appDir, "ffmpeg"); } private static VideoMetaInfo CheckVideoForEncoding(string videoPath) { var process = new Process { StartInfo = new ProcessStartInfo { FileName = ProberPath, Arguments = $"-show_streams -show_format -of json {videoPath}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); var probeResult = process.StandardOutput.ReadToEnd(); process.WaitForExit(); var resultData = JObject.Parse(probeResult); var streamData = resultData["stream"].Value<JArray>(); if (streamData.Count < 2) { throw new InvalidVideoMetaInfo("Video is lack of video track or audio track!"); } var videoMetaInfo = new VideoMetaInfo(); foreach (var trackData in streamData) { if (trackData["codec_type"].Value<string>() == "video") { videoMetaInfo.FrameNum = int.Parse(trackData["nb_frames"].Value<string>()); videoMetaInfo.Duration = (int)double.Parse(trackData["duration"].Value<string>()); break; } } if (!videoMetaInfo) { throw new InvalidVideoMetaInfo("Video meta info is incomplete!"); } return videoMetaInfo; } public static void EncodeVideo(string videoPath) {} private static string ProberPath => Path.Combine(FFmpegComponentsDir, "ffprobe.exe"); private static string EncoderPath => Path.Combine(FFmpegComponentsDir, "ffmpeg.exe"); private struct VideoMetaInfo { public int FrameNum { get; set; } public int Duration { get; set; } public static implicit operator bool(VideoMetaInfo info) { return info.FrameNum != 0 && info.Duration != 0; } } } [Serializable] public class InvalidVideoMetaInfo : Exception { public InvalidVideoMetaInfo(string message) : base(message) {} public InvalidVideoMetaInfo(string message, Exception innerException) : base(message, innerException) {} } }
mit
C#
6aab7325742e6fa2f24adcf220a37a93a4f010f3
Create Test1.cs
hueneburg/GitIncludeTest
dir1/dir2/dir1/Test1.cs
dir1/dir2/dir1/Test1.cs
This is a test
bsd-3-clause
C#
5a2121fc7dc75137849ef5c4d28fb50fd0bfe701
Add C# 7.0 Out variables on the fly example
devlights/try-csharp
TryCSharp.Samples/CSharp7/OutVariablesOnTheFly.cs
TryCSharp.Samples/CSharp7/OutVariablesOnTheFly.cs
using TryCSharp.Common; namespace TryCSharp.Samples.CSharp7 { /// <summary> /// C# 7.0 の新機能についてのサンプルです。 /// </summary> /// <remarks> /// Out variables on the fly について /// </remarks> [Sample] public class OutVariablesOnTheFly : IExecutable { public void Execute() { // C# 7.0 にて out 変数の取扱いが楽になった // その場で宣言して利用できるようになった // C# 7.0 まで // ReSharper disable once InlineOutVariableDeclaration int beforeCs7; if (int.TryParse("100", out beforeCs7)) { Output.WriteLine($"Before C# 7.0: {beforeCs7}"); } // C# 7.0 から if (int.TryParse("100", out var afterCs7)) { Output.WriteLine($"After C# 7.0: {afterCs7}"); } } } }
mit
C#
26f44111b1014725ff0cec24c49f8bd89c09eb0d
Add test to cover `RegisterBlockHelper` readme example
rexm/Handlebars.Net,rexm/Handlebars.Net
source/Handlebars.Test/ReadmeTests.cs
source/Handlebars.Test/ReadmeTests.cs
using System.Collections.Generic; using Xunit; namespace HandlebarsDotNet.Test { public class ReadmeTests { [Fact] public void RegisterBlockHelper() { var handlebars = Handlebars.Create(); handlebars.RegisterHelper("StringEqualityBlockHelper", (output, options, context, arguments) => { if (arguments.Length != 2) { throw new HandlebarsException("{{#StringEqualityBlockHelper}} helper must have exactly two arguments"); } var left = arguments.At<string>(0); var right = arguments[1] as string; if (left == right) options.Template(output, context); else options.Inverse(output, context); }); var animals = new Dictionary<string, string> { {"Fluffy", "cat" }, {"Fido", "dog" }, {"Chewy", "hamster" } }; var template = "{{#each this}}The animal, {{@key}}, {{#StringEqualityBlockHelper @value 'dog'}}is a dog{{else}}is not a dog{{/StringEqualityBlockHelper}}.\r\n{{/each}}"; var compiledTemplate = handlebars.Compile(template); string templateOutput = compiledTemplate(animals); Assert.Equal( "The animal, Fluffy, is not a dog.\r\n" + "The animal, Fido, is a dog.\r\n" + "The animal, Chewy, is not a dog.\r\n", templateOutput ); } } }
mit
C#
56d6cb5764f49eb2aaa98aef0b2ca97b3b88cbd6
Add "spotlight" beatmap badge
NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu
osu.Game/Overlays/BeatmapSet/SpotlightBeatmapPill.cs
osu.Game/Overlays/BeatmapSet/SpotlightBeatmapPill.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Resources.Localisation.Web; #nullable enable namespace osu.Game.Overlays.BeatmapSet { public class SpotlightBeatmapPill : BeatmapBadgePill { public override LocalisableString BadgeText => BeatmapsetsStrings.SpotlightBadgeLabel; public override Colour4 BadgeColour => Colours.Pink1; } }
mit
C#
ece80bdce924ae9dfbc8b3e17d1733c41350b62d
Add usage examples for double-checking doc examples.
StephenCleary/ConnectedProperties
test/UnitTests/UsageExamples.cs
test/UnitTests/UsageExamples.cs
using System; using System.Collections.Generic; using System.Text; using Xunit; using static Nito.ConnectedProperties.ConnectedProperty; namespace UnitTests { class UsageExamples { [Fact] public void SimpleUsage() { var obj = new object(); var nameProperty = GetConnectedProperty(obj, "Name"); nameProperty.Set("Bob"); Assert.Equal("Bob", ReadName(obj)); } private static string ReadName(object obj) { var nameProperty = GetConnectedProperty(obj, "Name"); return nameProperty.Get(); } } }
mit
C#
f34ce1e3fb3b34ffe2f85ef050e7a7c0378bd4bf
Create Program.cs
phretaddin/Hash-Array-Mapped-Trie
Program.cs
Program.cs
using System; using System.IO; using System.Collections.Generic; using System.Diagnostics; namespace HAMT { class Program { static void Main(string[] args) { List<string> items = new List<string>(); Hamt<string, string> hamt = new Hamt<string, string>(); Dictionary<string, string> dict = new Dictionary<string, string>(); StreamReader file = new StreamReader("dictionary.txt"); string line; while ((line = file.ReadLine()) != null) { items.Add(line); } file.Close(); long memoryBefore = GC.GetTotalMemory(true); Stopwatch sw = Stopwatch.StartNew(); foreach (var s in items) { hamt.Add(s, s + "a"); } sw.Stop(); long memoryAfter = GC.GetTotalMemory(true); Console.WriteLine("Time in ms taken to add all nodes: {0}", sw.ElapsedMilliseconds); Console.WriteLine("Item Count: " + hamt.ItemCount); Stopwatch sw2 = Stopwatch.StartNew(); int missCount = 0; foreach (string s in items) { if (!hamt.Contains(s)) { missCount++; } } sw2.Stop(); Console.WriteLine("Failed finding this many items: " + missCount); Console.WriteLine("Time in ticks to check contains: " + sw2.ElapsedMilliseconds); Console.WriteLine("Total memory used: " + (memoryAfter - memoryBefore).ToString("#,##0")); Console.Read(); } } }
mit
C#
7f7ca601083456623bdf2a61d348597ca1439225
Create Program.cs
MercedeX/StrangeStateMachineExample
Program.cs
Program.cs
using System; using Domain; namespace ConsoleApp { class Program { static void Main(string[] args) { // Create a Device Device device = new Device("Strange device"); Console.WriteLine("A {0} in action with door is in {1} state", device.Name, device.Door.CurrentState.Name); var ch = new Char(); do{ ch = GetChoice(); switch(char.ToLower(ch)){ case 'o': device.Door.Open(); break; case 'c': device.Door.Close(); break; case 'l': device.Door.Lock(); break; case 'u': device.Door.Unlock(); break; } Console.WriteLine("Current State of Door {0}", device.Door.CurrentState.Name); }while(ch!='e'); } private static char GetChoice() { Console.Write("Enter a choice (O)pen, (C)lose, (L)ock, (U)nlock, (E)xit:"); return Console.ReadLine().ToCharArray()[0]; } } }
apache-2.0
C#
0f87f68b77380b12ab392fe0be99268556a84377
Normalize and Cleanup
gOOvaUY/Plexo.Models,gOOvaUY/Goova.Plexo.Models
Session.cs
Session.cs
using System.Runtime.Serialization; namespace Plexo { [DataContract] public class Session { [DataMember] public string Id { get; set; } [DataMember] public string Uri { get; set; } [DataMember] public long ExpirationUTC { get; set; } } }
agpl-3.0
C#
72da7aefeff9787e51ed6761531888d5c2e69b59
Add tests
NJsonSchema/NJsonSchema,RSuter/NJsonSchema
src/NJsonSchema.CodeGeneration.CSharp.Tests/UriTests.cs
src/NJsonSchema.CodeGeneration.CSharp.Tests/UriTests.cs
using System; using System.Threading.Tasks; using Newtonsoft.Json; using Xunit; namespace NJsonSchema.CodeGeneration.CSharp.Tests { public class UriTests { public class ClassWithUri { public Uri MyUri { get; set; } } [Fact] public async Task When_property_is_uri_then_csharp_output_is_also_uri() { //// Arrange var schema = await JsonSchema4.FromTypeAsync<ClassWithUri>(); var json = schema.ToJson(); var generator = new CSharpGenerator(schema); //// Act var code = generator.GenerateFile("MyClass"); //// Assert Assert.Contains("public System.Uri MyUri", code); } [Fact] public void When_uri_is_relative_then_it_is_serialized_and_deserialized_correctly() { //// Arrange var obj = new ClassWithUri { MyUri = new Uri("abc/def", UriKind.Relative) }; //// Act var json = JsonConvert.SerializeObject(obj); var obj2 = JsonConvert.DeserializeObject<ClassWithUri>(json); //// Assert Assert.Equal("{\"MyUri\":\"abc/def\"}", json); Assert.Equal(obj.MyUri, obj2.MyUri); } [Fact] public void When_uri_is_absolute_then_it_is_serialized_and_deserialized_correctly() { //// Arrange var obj = new ClassWithUri { MyUri = new Uri("https://abc/def", UriKind.Absolute) }; //// Act var json = JsonConvert.SerializeObject(obj); var obj2 = JsonConvert.DeserializeObject<ClassWithUri>(json); //// Assert Assert.Equal("{\"MyUri\":\"https://abc/def\"}", json); Assert.Equal(obj.MyUri, obj2.MyUri); } } }
mit
C#
8d581685200e3a687899fdc5833c457dfd65a48d
Create Program.cs
Onastick/SightByte
Program.cs
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace SightByte { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
cc0-1.0
C#
a0eeb16270814f5a441c6d7c773b06181d4f811b
Add 'Interpreter' class
whampson/cascara,whampson/bft-spec
Cascara/Src/Interpreter/Interpreter.cs
Cascara/Src/Interpreter/Interpreter.cs
#region License /* Copyright (c) 2017 Wes Hampson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Text; namespace WHampson.Cascara.Interpreter { internal sealed class Interpreter { private static readonly HashSet<Version> SupportedVersions = new HashSet<Version>(new Version[] { new Version("1.0.0") }); public enum Directive { Align, Echo, Include } } }
mit
C#
7210b5581f4cbee7212ec29ce22b465569841942
Add path.cs to source control
bsstahl/DPDemo
Chutes.Optimization/Entities/Path.cs
Chutes.Optimization/Entities/Path.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chutes.Optimization.Entities { public class Path { LinkedList<Gamespace> _path = new LinkedList<Gamespace>(); public Path() { _path.Clear(); } public Gamespace Add(Gamespace space) { if (_path.Any()) _path.AddAfter(_path.Last, space); else _path.AddFirst(space); return space; } public int Length { get { return _path.Count; } } public int RollCount { get { return _path.Where(s => !s.PathTo.HasValue).Count(); } } public override string ToString() { var sb = new StringBuilder(); foreach (var item in _path) sb.Append(item.Index.ToString("00") + " "); return sb.ToString(); } public IEnumerable<Gamespace> Reverse() { throw new NotImplementedException(); } } }
mit
C#
12a0bebd4e254d280606ac9c7dc99afa335e50c4
Add Jump node tests
exodrifter/unity-rumor
Editor/Tests/JumpTest.cs
Editor/Tests/JumpTest.cs
using Exodrifter.Rumor.Nodes; using Exodrifter.Rumor.Engine; using NUnit.Framework; using System; using System.Collections.Generic; namespace Exodrifter.Rumor.Test { /// <summary> /// Makes sure that jump nodes operate as expected. /// </summary> public class JumpTest { /// <summary> /// Makes sure jumps to undefined labels throw an exception. /// </summary> [Test] public void JumpUndefined() { var rumor = new Engine.Rumor(new List<Node>() { new Jump("start"), }); var yield = rumor.Run(); Assert.Throws<InvalidOperationException>(() => yield.MoveNext()); } /// <summary> /// Makes sure jumps to defined labels operate as expected. /// </summary> [Test] public void JumpDefined() { var rumor = new Engine.Rumor(new List<Node>() { new Jump("a"), new Label("b", null), new Dialog("b"), new Label("a", null), new Dialog("a"), new Jump("b"), }); var yield = rumor.Run(); yield.MoveNext(); Assert.AreEqual("a", (rumor.Current as Dialog).text); rumor.Advance(); yield.MoveNext(); Assert.AreEqual("b", (rumor.Current as Dialog).text); } /// <summary> /// Makes sure jumps go to the first defined label when the same /// label is defined multiple times in the same scope. /// </summary> [Test] public void JumpMultipleDefinedSameScope() { var rumor = new Engine.Rumor(new List<Node>() { new Jump ("start"), new Label("a", new List<Node>() { new Dialog("aa"), }), new Label("a", new List<Node>() { new Dialog("ab"), }), new Label("a", new List<Node>() { new Dialog("ac"), }), new Label("start", null), new Jump("a"), }); var yield = rumor.Run(); yield.MoveNext(); Assert.AreEqual("aa", (rumor.Current as Dialog).text); } /// <summary> /// Makes sure jumps go to the closest defined label when the same /// label is defined multiple times in different scopes. /// </summary> [Test] public void JumpMultipleDefinedDifferentScope() { var rumor = new Engine.Rumor(new List<Node>() { new Label("a", new List<Node>() { new Dialog("a"), new Label("a", new List<Node>() { new Dialog("aa"), new Jump("b"), }), new Label("b", new List<Node>() { new Dialog("ab"), new Jump("a"), }), }), }); var yield = rumor.Run(); yield.MoveNext(); Assert.AreEqual("a", (rumor.Current as Dialog).text); rumor.Advance(); yield.MoveNext(); Assert.AreEqual("aa", (rumor.Current as Dialog).text); rumor.Advance(); yield.MoveNext(); Assert.AreEqual("ab", (rumor.Current as Dialog).text); rumor.Advance(); yield.MoveNext(); Assert.AreEqual("aa", (rumor.Current as Dialog).text); } } }
mit
C#
76f1e9c06e4ec8cfa1ccdb56fe7519449e2ba593
Fix tabs/spaces.
AkshayHarshe/arcgis-runtime-samples-dotnet,Arc3D/arcgis-runtime-samples-dotnet,sharifulgeo/arcgis-runtime-samples-dotnet,Esri/arcgis-runtime-samples-dotnet,Esri/arcgis-runtime-samples-dotnet,Esri/arcgis-runtime-samples-dotnet
src/Desktop/ArcGISRuntimeSamplesDesktop/Samples/Scene/FeatureLayerFromLocalGeodatabase3d.xaml.cs
src/Desktop/ArcGISRuntimeSamplesDesktop/Samples/Scene/FeatureLayerFromLocalGeodatabase3d.xaml.cs
using Esri.ArcGISRuntime.Controls; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Layers; using System; using System.Windows; using System.Windows.Controls; namespace ArcGISRuntime.Samples.Desktop { /// <summary> /// This sample shows how to add a FeatureLayer from a local .geodatabase file to the scene. /// </summary> /// <title>3D Feature Layer from Local Geodatabase</title> /// <category>Scene</category> /// <subcategory>Feature Layers</subcategory> public partial class FeatureLayerFromLocalGeodatabase3d : UserControl { private const string GDB_PATH = @"..\..\..\samples-data\maps\usa.geodatabase"; /// <summary>Construct FeatureLayerFromLocalGeodatabase sample control</summary> public FeatureLayerFromLocalGeodatabase3d() { InitializeComponent(); CreateFeatureLayers(); } private async void CreateFeatureLayers() { try { var gdb = await Geodatabase.OpenAsync(GDB_PATH); Envelope extent = null; foreach (var table in gdb.FeatureTables) { var flayer = new FeatureLayer() { ID = table.Name, DisplayName = table.Name, FeatureTable = table }; if (!Geometry.IsNullOrEmpty(table.ServiceInfo.Extent)) { if (Geometry.IsNullOrEmpty(extent)) extent = table.ServiceInfo.Extent; else extent = extent.Union(table.ServiceInfo.Extent); } MySceneView.Scene.Layers.Add(flayer); } await MySceneView.SetViewAsync(new Camera(new MapPoint(-99.343, 26.143, 5881928.401), 2.377, 10.982)); } catch (Exception ex) { MessageBox.Show("Error creating feature layer: " + ex.Message, "Samples"); } } } }
using Esri.ArcGISRuntime.Controls; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Layers; using System; using System.Windows; using System.Windows.Controls; namespace ArcGISRuntime.Samples.Desktop { /// <summary> /// This sample shows how to add a FeatureLayer from a local .geodatabase file to the scene. /// </summary> /// <title>3D Feature Layer from Local Geodatabase</title> /// <category>Scene</category> /// <subcategory>Feature Layers</subcategory> public partial class FeatureLayerFromLocalGeodatabase3d : UserControl { private const string GDB_PATH = @"..\..\..\samples-data\maps\usa.geodatabase"; /// <summary>Construct FeatureLayerFromLocalGeodatabase sample control</summary> public FeatureLayerFromLocalGeodatabase3d() { InitializeComponent(); CreateFeatureLayers(); } private async void CreateFeatureLayers() { try { var gdb = await Geodatabase.OpenAsync(GDB_PATH); Envelope extent = null; foreach (var table in gdb.FeatureTables) { var flayer = new FeatureLayer() { ID = table.Name, DisplayName = table.Name, FeatureTable = table }; if (!Geometry.IsNullOrEmpty(table.ServiceInfo.Extent)) { if (Geometry.IsNullOrEmpty(extent)) extent = table.ServiceInfo.Extent; else extent = extent.Union(table.ServiceInfo.Extent); } MySceneView.Scene.Layers.Add(flayer); } await MySceneView.SetViewAsync(new Camera(new MapPoint(-99.343, 26.143, 5881928.401), 2.377,10.982)); } catch (Exception ex) { MessageBox.Show("Error creating feature layer: " + ex.Message, "Samples"); } } } }
apache-2.0
C#
98062611c2aea30531bbe0334c092aeb09245cf0
Add SpaceParser
StevenLiekens/Txt,StevenLiekens/TextFx
src/Txt.ABNF/Core/SP/SpaceParser.cs
src/Txt.ABNF/Core/SP/SpaceParser.cs
using Txt.Core; namespace Txt.ABNF.Core.SP { public class SpaceParser : Parser<Space, char> { protected override char ParseImpl(Space value) { return value.Text[0]; } } }
mit
C#
9ca8f0cddaa29297070e59aa4843cdc37bc8539d
Create Carnage.cs
jon-lad/Battlefleet-Gothic
Ships/Chaos/Cruiser/Carnage.cs
Ships/Chaos/Cruiser/Carnage.cs
using UnityEngine; using System.Collections; public class Carnage : Ship { // Use this for initialization public override void Start () { base.Start (); stand = (GameObject)Instantiate(GameData.instance.SmallStandPrefab, transform.position, Quaternion.Euler(new Vector3())); hits = 8; speed = 25; minMove = speed / 2; turns = 45; shields = 2; armour = 5; turrets = 2; minTurnDistance = 10; maxMove = speed; baseMinTurnDistance = 10; stand.transform.parent = transform; shipType = 1; remainingHits = hits; activeShields = shields; Weapon portWeaponBattery = new Weapon(); weapons.Add (portWeaponBattery); Weapon starboardWeaponBattery = new Weapon(); weapons.Add (starboardWeaponBattery); Weapon portWeaponBattery1 = new Weapon(); weapons.Add (portWeaponBattery1); Weapon starboardWeaponBattery1 = new Weapon(); weapons.Add (starboardWeaponBattery1); Weapon prowWeaponBattery = new Weapon(); weapons.Add (prowWeaponBattery); portWeaponBattery.type = 1; portWeaponBattery.range = 45; portWeaponBattery.strength = 6; portWeaponBattery.maxFireArc = -45; portWeaponBattery.minFireArc = -135; portWeaponBattery.weaponName = "Port Weapon Batt. (6)"; starboardWeaponBattery.type = 1; starboardWeaponBattery.range = 45; starboardWeaponBattery.strength = 6; starboardWeaponBattery.maxFireArc = 135; starboardWeaponBattery.minFireArc = 45; starboardWeaponBattery.weaponName = "Strbd Weapon Batt. (6)"; portWeaponBattery1.type = 1; portWeaponBattery1.range = 60; portWeaponBattery1.strength = 4; portWeaponBattery1.maxFireArc = -45; portWeaponBattery1.minFireArc = -135; portWeaponBattery1.weaponName = "Port Weapon Batt. (4)"; starboardWeaponBattery1.type = 1; starboardWeaponBattery1.range = 60; starboardWeaponBattery1.strength = 4; starboardWeaponBattery1.maxFireArc = 135; starboardWeaponBattery1.minFireArc = 45; starboardWeaponBattery1.weaponName = "Strbd Weapon Batt. (4)"; prowWeaponBattery.type = 1; prowWeaponBattery.range = 60; prowWeaponBattery.strength = 6; prowWeaponBattery.maxFireArc = 135; prowWeaponBattery.minFireArc = -135; prowWeaponBattery.weaponName = "Prow Weapon Batt."; } // Update is called once per frame public override void Update () { base.Update (); } }
mit
C#
de18ee1a937001e326cbe88639db2d9a99a59867
Create CollectionOfGames.cs
cwesnow/Net_Fiddle
2017Aug/CollectionOfGames.cs
2017Aug/CollectionOfGames.cs
using System; public class Program { public static void Main() { // Loop until user doesn't want to play anymore while (true) { GamesList.selectGame(); if (!newGame()) break; } Console.WriteLine("Thanks for playing, Good bye!"); } // Returns T/F if a user wants another game static bool newGame() { Console.WriteLine("\n\nPlay another game?"); return Console.ReadLine().ToUpper() == "Y" ? true : false; } } // Shared base class, so I can have an array of common objects with a common method public abstract class Game { public String Title = "title"; public abstract void Start(); } // Game 1 - Inherit from Game for shared attributes and behavior public class NumberGuess : Game { // Constructor uses base to set inherited attributes public NumberGuess() { base.Title = "Number Guess"; } // Rewriting the Start() method for our custom classes needs public override void Start() { int tries = 3, guessed = -1; int correct = new Random().Next(0, 10); Console.WriteLine("Welcome to Number Guess! {0}", correct); for (int i = tries; tries > 0; tries--) { Console.Write("{0} guesses left\nNext Guess: ", tries); while (!int.TryParse(Console.ReadLine(), out guessed)) { Console.WriteLine("Invalid Number! Try again"); } if (guessed == correct) { Console.WriteLine("You Win!"); break; } else if (guessed < correct) { Console.WriteLine("You guessed too low!"); } else { Console.WriteLine("You guessed too high!"); } } } } // Game 2 public class TicTacToe : Game { public TicTacToe() { base.Title = "Tic Tac Toe"; } public override void Start() { Console.WriteLine("Start a game of Tic Tac Toe"); } } // Game 3 public class Hangman : Game { public Hangman() { base.Title = "Hangman"; } public override void Start() { Console.WriteLine("Start a game of Hangman"); } } // Stores every Game, Displays them, and let's user play one public class GamesList { static Game[] games = {new NumberGuess(), new TicTacToe(), new Hangman()}; // Displays Games Array starting at 1 for Users static void displayGames() { for (int i = 0; i < games.Length; i++) { Console.WriteLine("{0,2}. {1}", i, games[i].Title); } } // Gets User input, Checks that it's a number, number is below number of games and above 0 static int chooseGame() { int x = 0; while (!int.TryParse(Console.ReadLine(), out x) || x >= games.Length || x < 0) { Console.WriteLine("Invalid Number!"); } return x; } // Combines Menu Display with Picking Game and Playing it public static void selectGame() { Console.WriteLine("Select a Game:"); displayGames(); games[chooseGame()].Start(); } }
mit
C#
b8b6d0e861bd0269b841ceacfaab3c361128bc3b
Add tests for `ClosestBeatDivisor`
peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu
osu.Game.Tests/NonVisual/ClosestBeatDivisorTest.cs
osu.Game.Tests/NonVisual/ClosestBeatDivisorTest.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.Collections.Generic; using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Objects; namespace osu.Game.Tests.NonVisual { public class ClosestBeatDivisorTest { [Test] public void TestExactDivisors() { var cpi = new ControlPointInfo(); cpi.Add(-1000, new TimingControlPoint { BeatLength = 1000 }); double[] divisors = { 3, 1, 16, 12, 8, 6, 4, 3, 2, 1 }; assertClosestDivisors(divisors, divisors, cpi); } [Test] public void TestExactDivisorWithTempoChanges() { int offset = 0; int[] beatLengths = { 1000, 200, 100, 50 }; var cpi = new ControlPointInfo(); foreach (int beatLength in beatLengths) { cpi.Add(offset, new TimingControlPoint { BeatLength = beatLength }); offset += beatLength * 2; } double[] divisors = { 3, 1, 16, 12, 8, 6, 4, 3 }; assertClosestDivisors(divisors, divisors, cpi); } [Test] public void TestExactDivisorsHighBPMStream() { var cpi = new ControlPointInfo(); cpi.Add(-50, new TimingControlPoint { BeatLength = 50 }); // 1200 BPM 1/4 (limit testing) // A 1/4 stream should land on 1/1, 1/2 and 1/4 divisors. double[] divisors = { 4, 4, 4, 4, 4, 4, 4, 4 }; double[] closestDivisors = { 4, 2, 4, 1, 4, 2, 4, 1 }; assertClosestDivisors(divisors, closestDivisors, cpi, step: 1 / 4d); } [Test] public void TestApproximateDivisors() { var cpi = new ControlPointInfo(); cpi.Add(-1000, new TimingControlPoint { BeatLength = 1000 }); double[] divisors = { 3.03d, 0.97d, 14, 13, 7.94d, 6.08d, 3.93d, 2.96d, 2.02d, 64 }; double[] closestDivisors = { 3, 1, 16, 12, 8, 6, 4, 3, 2, 1 }; assertClosestDivisors(divisors, closestDivisors, cpi); } private void assertClosestDivisors(IReadOnlyList<double> divisors, IReadOnlyList<double> closestDivisors, ControlPointInfo cpi, double step = 1) { List<HitObject> hitobjects = new List<HitObject>(); double offset = cpi.TimingPoints[0].Time; for (int i = 0; i < divisors.Count; ++i) { double beatLength = cpi.TimingPointAt(offset).BeatLength; hitobjects.Add(new HitObject { StartTime = offset + beatLength / divisors[i] }); offset += beatLength * step; } var beatmap = new Beatmap { HitObjects = hitobjects, ControlPointInfo = cpi }; for (int i = 0; i < divisors.Count; ++i) Assert.AreEqual(closestDivisors[i], beatmap.ClosestBeatDivisor(beatmap.HitObjects[i].StartTime), $"at index {i}"); } } }
mit
C#
ad940dd18b02cc6e66623aab3ff6217bab73d941
Copy IsAjax rewquest attribute
rgonek/Ilaro.Admin,rgonek/Ilaro.Admin,tassyo1/Ilaro.Admin,tassyo1/Ilaro.Admin
src/Ilaro.Admin/Ilaro.Admin/Infrastructure/CopyIsAjaxRequestFromRequestToViewBagAttribute.cs
src/Ilaro.Admin/Ilaro.Admin/Infrastructure/CopyIsAjaxRequestFromRequestToViewBagAttribute.cs
using System.Web.Mvc; namespace Ilaro.Admin.Infrastructure { public class CopyIsAjaxRequestFromRequestToViewBagAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { var view = filterContext.Result as ViewResult; if (view != null) { view.ViewBag.IsAjaxRequest = filterContext.RequestContext.HttpContext.Request.IsAjaxRequest(); } } } }
mit
C#
370716b9171fffe3bc58e64cd0ad780dc4a28002
add common utilities
ceee/UptimeSharp
UptimeSharp/Utilities.cs
UptimeSharp/Utilities.cs
using RestSharp; using System; using System.Collections.Generic; namespace UptimeSharp { /// <summary> /// General utilities /// </summary> internal class Utilities { /// <summary> /// converts DateTime to an UNIX timestamp /// </summary> /// <param name="dateTime">The date.</param> /// <returns>UNIX timestamp</returns> public static int? GetUnixTimestamp(DateTime? dateTime) { if (dateTime == null) { return null; } return (int)((DateTime)dateTime - new DateTime(1970, 1, 1)).TotalSeconds; } /// <summary> /// Creates a Parameter object. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <returns></returns> public static Parameter CreateParam(string name, object value, ParameterType type = ParameterType.GetOrPost) { return new Parameter() { Name = name, Value = value, Type = type }; } /// <summary> /// Creates a Parameter object within a list. /// </summary> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <returns></returns> public static List<Parameter> CreateParamInList(string name, object value, ParameterType type = ParameterType.GetOrPost) { return new List<Parameter>() { CreateParam(name, value, type) }; } /// <summary> /// Convert a dictionary to a list /// </summary> /// <typeparam name="T"></typeparam> /// <param name="items">The items.</param> /// <returns></returns> public static List<T> DictionaryToList<T>(Dictionary<string, T> items) where T : new() { if (items == null) { return null; } var itemEnumerator = items.GetEnumerator(); List<T> list = new List<T>(); while (itemEnumerator.MoveNext()) { list.Add(itemEnumerator.Current.Value); } return list; } } }
mit
C#
44d51a64da2f38535013da9243650185f0cebd35
Add coin flipping command. Sometimes lands on it's side. No idea why!
mikaelssen/FruitBowlBot
JefBot/Commands/CoinPluginCommand.cs
JefBot/Commands/CoinPluginCommand.cs
using System; using System.Collections.Generic; using System.IO; using TwitchLib; using TwitchLib.TwitchClientClasses; using System.Net; namespace JefBot.Commands { internal class CoinPluginCommand : IPluginCommand { public string PluginName => "Coin"; public string Command => "coin"; public IEnumerable<string> Aliases => new[] { "c", "flip" }; public bool Loaded { get; set; } = true; Random rng = new Random(); public void Execute(ChatCommand command, TwitchClient client) { if (rng.Next(1000) > 1) { var result = rng.Next(0, 1) == 1 ? "heads" : "tails"; client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it was {result}"); } else { client.SendMessage(command.ChatMessage.Channel, $"{command.ChatMessage.Username} flipped a coin, it landed on it's side..."); } } } }
mit
C#
13c67f13c78f3f8fdede4b7dbacbaa9c76d8c842
Add missing file.
jeongroseok/magecrawl,AndrewBaker/magecrawl
Trunk/GameUI/Utilities/ColorCache.cs
Trunk/GameUI/Utilities/ColorCache.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using libtcod; namespace Magecrawl.GameUI.Utilities { // Sometimes we use a large number of colors in tight loops. This class caching the instances // so we don't recalculate or P/Invoke them again public class ColorCache { public static ColorCache Instance = new ColorCache(); private Dictionary<string, TCODColor> m_cache; private ColorCache() { m_cache = new Dictionary<string,TCODColor>(); } public TCODColor this[string i] { get { return m_cache[i]; } set { m_cache[i] = value; } } } }
bsd-2-clause
C#
7c2a9fbf6f2841ee2e94318b99a9fb074e21dee2
Create ArrayExtensions.cs
AOmelaienko/Camila.ArrayUtils
ArrayExtensions.cs
ArrayExtensions.cs
using System; using System.Threading.Tasks; namespace Camila { public static class ArrayExtensions { public static T[] Flatten<T> ( this Array Array ) { if ( !Array.GetType ().GetElementType ().Equals ( typeof ( T ) ) ) throw new ArrayTypeMismatchException (); if ( Array.Rank == 1 ) return (T[]) Array; T[] result = new T[Array.GetLengths ().Product ()]; int[] lengths = Array.GetLengths (); Parallel.For ( 0, result.Length, i => result[i] = (T) Array.GetValue ( Utils.Array.GetIndices ( lengths, i ) ) ); return result; } public static Array Restore<T> ( this T[] FlatArray, int[] Lengths ) { Array result = Array.CreateInstance ( typeof ( T ), Lengths ); Parallel.For ( 0, FlatArray.Length, i => result.SetValue ( FlatArray[i], Utils.Array.GetIndices ( Lengths, i ) ) ); return result; } public static int[] GetLengths ( this Array Array ) { int[] result = new int[Array.Rank]; Parallel.For ( 0, Array.Rank, i => result[i] = Array.GetLength ( i ) ); return result; } } }
mit
C#
64f0d62cbae024c65de1a783d389ddb039617cad
Add MicrosoftDataSqliteDriver unit test
lecaillon/Evolve
test/Evolve.Test/Driver/MicrosoftDataSqliteDriverTest.cs
test/Evolve.Test/Driver/MicrosoftDataSqliteDriverTest.cs
using Evolve.Driver; using Xunit; namespace Evolve.Test.Driver { public class MicrosoftDataSqliteDriverTest { [Fact(DisplayName = "Load_ConnectionType_from_an_already_loaded_assembly")] public void Load_ConnectionType_from_an_already_loaded_assembly() { var driver = new MicrosoftDataSqliteDriver(); Assert.NotNull(driver.ConnectionType); } } } // http://stackoverflow.com/questions/37895278/how-to-load-assemblies-located-in-a-folder-in-net-core-console-app // http://www.michael-whelan.net/replacing-appdomain-in-dotnet-core/ // https://github.com/aspnet/Announcements/issues/149
mit
C#
8cb6275bdd49c5501c5f951c1cb10b5cbc44ecae
add LineIteratorTest
shimat/opencvsharp,shimat/opencvsharp,shimat/opencvsharp
test/OpenCvSharp.Tests/imgproc/LineIteratorTest.cs
test/OpenCvSharp.Tests/imgproc/LineIteratorTest.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace OpenCvSharp.Tests.ImgProc { public class LineIteratorTest : TestBase { [Fact] public void CountPixels() { var p1 = new Point(0, 0); var p2 = new Point(9, 9); using (Mat mat = Mat.Zeros(10, 10, MatType.CV_8UC1)) using (var lineIterator = new LineIterator(mat, p1, p2)) { var count = lineIterator.Count(); Assert.Equal(10, count); } } [Fact] public void SumPixelsByte() { var p1 = new Point(0, 0); var p2 = new Point(9, 9); using (Mat mat = new Mat(10, 10, MatType.CV_8UC1, 2)) using (var lineIterator = new LineIterator(mat, p1, p2)) { var sum = lineIterator.Sum(pixel => pixel.GetValue<byte>()); Assert.Equal(10 * 2, sum); } } [Fact] public void SumPixelsVec3b() { var p1 = new Point(0, 0); var p2 = new Point(9, 9); using (Mat mat = new Mat(10, 10, MatType.CV_8UC3, new Scalar(1, 2, 3))) using (var lineIterator = new LineIterator(mat, p1, p2)) { int b = 0, g = 0, r = 0; foreach (var pixel in lineIterator) { var value = pixel.GetValue<Vec3b>(); (b, g, r) = (b + value.Item0, g + value.Item1, r + value.Item2); } Assert.Equal(10, b); Assert.Equal(20, g); Assert.Equal(30, r); } } } }
apache-2.0
C#
82b7e898ecf87f8c377be52b7f2248654806954a
Create TestImpl.cs
ilgazdotcom/Arches
ArchesFramework/Arches.BusinessLogic/Concrete/TestImpl.cs
ArchesFramework/Arches.BusinessLogic/Concrete/TestImpl.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Arches.BusinessLogic.Abstract; using Arches.Models; using Arches.DataAccess; using System.Data; namespace Arches.BusinessLogic.Concrete { public class TestImpl : ITest { readonly DatabaseConnection _databaseConnection; private DataTable _dt; private int _res; public TestImpl() { _databaseConnection = new DatabaseConnection("myConnection"); } public Test Find(Test test) { _dt = _databaseConnection.Select("Select TOP(1) Col1, Col2, Col3 from Test where Col1=" + test.Col1); // and Col2 = test.Col2... if (_dt.Rows.Count > 0) { Test _test = new Test() { Col1 = _dt.Rows[0]["Col1"].ToString(), Col2 = _dt.Rows[0]["Col2"].ToString(), Col3 = _dt.Rows[0]["Col3"].ToString(), }; _dt.Clear(); return _test; } } public List<Test> FindAll() { _dt = _databaseConnection.Select("Select Col1, Col2, Col3 from Test"); return (from DataRow row in _dt.Rows select new Test() { Col1 = Convert.ToInt32(row["Col1"]), Col2 = row["Col2"].ToString(), Col3 = row["Col3"].ToString() }).ToList(); } public void Insert(Test test) { _res = _databaseConnection.ExecQuery("Insert Into Test(Col1, Col2, Col3) values(" + test.Col1 + ",'" + test.Col2 + "','" + test.Col3 + "'"); } public void Update(Test test) { _res = _databaseConnection.ExecQuery("Update Test Set Col1=" + test.Col1 + ", Col2='" + test.Col2 + "', Col3='" + test.Col3 + "' where Id='"+test.Id+"'"); } public bool Delete(int id) { _res = _databaseConnection.ExecQuery("Delete From Test Where Id=" + id); return _res > 0; } } }
mpl-2.0
C#
8a4717d2e9e84875f14f02f318020f8f6949d1cf
Add catch statistics
johnneijzen/osu,peppy/osu-new,johnneijzen/osu,ppy/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,naoey/osu,peppy/osu,2yangk23/osu,DrabWeb/osu,peppy/osu,naoey/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,DrabWeb/osu,2yangk23/osu,NeoAdonis/osu,DrabWeb/osu,ZLima12/osu,UselessToucan/osu,UselessToucan/osu,naoey/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu
osu.Game.Rulesets.Catch/Beatmaps/CatchBeatmap.cs
osu.Game.Rulesets.Catch/Beatmaps/CatchBeatmap.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Catch.Objects; namespace osu.Game.Rulesets.Catch.Beatmaps { public class CatchBeatmap : Beatmap<CatchHitObject> { public override IEnumerable<BeatmapStatistic> GetStatistics() { int juiceStreams = HitObjects.Count(s => s is JuiceStream); int bananaShowers = HitObjects.Count(s => s is BananaShower); int fruits = HitObjects.Count - juiceStreams - bananaShowers; return new[] { new BeatmapStatistic { Name = @"Object Count", Content = HitObjects.Count.ToString(), Icon = FontAwesome.fa_circle }, new BeatmapStatistic { Name = @"Fruit Count", Content = fruits.ToString(), Icon = FontAwesome.fa_circle_o }, new BeatmapStatistic { Name = @"Juice Stream Count", Content = juiceStreams.ToString(), Icon = FontAwesome.fa_circle }, new BeatmapStatistic { Name = @"Banana Shower Count", Content = bananaShowers.ToString(), Icon = FontAwesome.fa_circle } }; } } }
mit
C#
82b106137b1040d17a0509dc19bff5fb80fc2a70
Bump 2.6.0.0
klesta490/BTDB,yonglehou/BTDB,karasek/BTDB,Bobris/BTDB
BTDB/Properties/AssemblyInfo.cs
BTDB/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright Boris Letocha 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("2.6.0.0")] [assembly: AssemblyFileVersion("2.6.0.0")] [assembly: InternalsVisibleTo("BTDBTest")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BTDB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BTDB")] [assembly: AssemblyCopyright("Copyright Boris Letocha 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM componenets. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d949b20a-70ec-46bf-8eed-3a3cfb0d4593")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision [assembly: AssemblyVersion("2.5.3.0")] [assembly: AssemblyFileVersion("2.5.3.0")] [assembly: InternalsVisibleTo("BTDBTest")]
mit
C#
841e515971fa6029c8087bce868c9effd0bb8ace
add IDataReportRenderer abstraction for rendering a data only report to excel format
volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity
src/Serenity.Net.Services/Reporting/IDataReportExcelRenderer.cs
src/Serenity.Net.Services/Reporting/IDataReportExcelRenderer.cs
 namespace Serenity.Reporting { public interface IDataReportExcelRenderer { /// <summary> /// Renders the specified report to Excel format. /// </summary> /// <param name="report">The report.</param> /// <returns></returns> byte[] Render(IDataOnlyReport report); } }
mit
C#
5070721e2e652bccfd8dbea44451f2b80431d7ba
add Winner struct
svmnotn/friendly-guacamole
Assets/src/data/Winner.cs
Assets/src/data/Winner.cs
public struct Winner { public bool win; public Player winner; public Winner (bool win, Player winner){ this.win = win; this.winner = winner; } }
mit
C#
6ebd5e03b95b40c568426f8b5a695f291ae6a7b3
fix sleep during video
MediaBrowser/Emby.Theater,MediaBrowser/Emby.Theater,MediaBrowser/Emby.Theater
Emby.Theater/App/Standby.cs
Emby.Theater/App/Standby.cs
using System; using System.Runtime.InteropServices; namespace Emby.Theater.App { /// <summary> /// Class NativeApp /// </summary> public static class Standby { public static void PreventSystemStandby() { SystemHelper.ResetStandbyTimer(); } [Flags] internal enum EXECUTION_STATE : uint { ES_NONE = 0, ES_SYSTEM_REQUIRED = 0x00000001, ES_DISPLAY_REQUIRED = 0x00000002, ES_USER_PRESENT = 0x00000004, ES_AWAYMODE_REQUIRED = 0x00000040, ES_CONTINUOUS = 0x80000000 } public class SystemHelper { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags); public static void ResetStandbyTimer() { EXECUTION_STATE es = SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED); } } } }
mit
C#
c03eb9a3540f7e0139f07ff24d48bd6e247e42ca
add the Properties folder and AssemblyInfo.cs
miridfd/MassTransit.Automatonymous.UnityIntegration
AssemblyInfo.cs
AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MassTransit.Automatonymous.UnityIntegration")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MassTransit.Automatonymous.UnityIntegration")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2edeee00-69e0-4e0b-b241-6cf6a58ead63")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
d589e2ba2e59ca0fa11df7c7db65ef6cb7f65c5a
Add tests for F.Increment
farity/farity
Farity.Tests/IncrementTests.cs
Farity.Tests/IncrementTests.cs
using Xunit; namespace Farity.Tests { public class IncrementTests { [Theory] [InlineData(1.22d)] [InlineData(-1.22d)] public void IncrementIncrementsDoubleByOne(double a) { var expected = a + 1; var actual = F.Increment(a); Assert.Equal(expected, actual); } [Theory] [InlineData(1.22f)] [InlineData(-1.22f)] public void IncrementIncrementsFloatByOne(float a) { var expected = a + 1; var actual = F.Increment(a); Assert.Equal(expected, actual); } [Theory] [InlineData(1)] [InlineData(-1)] public void IncrementIncrementsIntegerByOne(int a) { var expected = a + 1; var actual = F.Increment(a); Assert.Equal(expected, actual); } [Theory] [InlineData(1L)] [InlineData(-1L)] public void IncrementIncrementsLongByOne(long a) { var expected = a + 1; var actual = F.Increment(a); Assert.Equal(expected, actual); } [Theory] [InlineData(1U)] [InlineData(12U)] public void IncrementIncrementsUintByOne(uint a) { var expected = a + 1; var actual = F.Increment(a); Assert.Equal(expected, actual); } [Theory] [InlineData(1UL)] [InlineData(11UL)] public void IncrementIncrementsUlongByOne(ulong a) { var expected = a + 1; var actual = F.Increment(a); Assert.Equal(expected, actual); } } }
mit
C#
2f1149aa5f2b235844fa6900f1415d65fba930c3
Create Spacefolder.cs
KerbaeAdAstra/KerbalFuture
KerbalFuture/Spacefolder.cs
KerbalFuture/Spacefolder.cs
mit
C#
3680f0cb6adc7ac71bbd16dcea952c371c0e48ba
Create FiniteStateMachine.cs
efruchter/UnityUtilities
Patterns/FiniteStateMachine.cs
Patterns/FiniteStateMachine.cs
using System; using UnityEngine; // ReSharper disable CheckNamespace namespace Patterns.State { /// <summary> /// Monobehaviour implementation of a state pattern. Each state is a seperate class. /// It is up to the behaviour to properly link up the exit states in each state. /// </summary> public abstract class StatefulMonoBehaviour : MonoBehaviour { private readonly StateMachine _stateMachine = new StateMachine(); /// <summary> /// Get the reference to the starting state. /// </summary> /// <returns>the first state to run.</returns> public abstract IState GetStartingState(); /// <summary> /// Link the exit state references in each state to the corresponding state. /// </summary> public abstract void SetupInterStateConnections(); /// <summary> /// Set the state of the internal state machine. /// </summary> /// <param name="state">new state.</param> protected void SetState(IState state) { _stateMachine.SetState(state); } public void Start() { SetupInterStateConnections(); SetState(GetStartingState()); } public void Update() { _stateMachine.Update(); } public void OnEnable() { _stateMachine.Resume(); } public void OnDisable() { _stateMachine.Pause(); } } public sealed class StateMachine { private IState _state; private static readonly IState NullState = new NullState(); public StateMachine() { _state = NullState; } public StateMachine(IState state) : this() { SetState(state); } public void SetState(IState state) { if (state == null) { state = NullState; } _state.OnStop(); _state = state; _state.OnStart(); } public void Pause() { _state.OnStop(); } public void Resume() { _state.OnStart(); } public void Update() { _state.OnUpdate(this); } } public interface IState { void OnStart(); void OnUpdate(StateMachine stateMachine); void OnStop(); } public sealed class NullState : IState { public void OnStart() { } public void OnUpdate(StateMachine stateMachine) { } public void OnStop() { } } }
mit
C#
9a5cf00723e4a90746c3f931acd86afed77e8ad1
add immutable version of BitArray, used to track spent/unspent outputs of a transaction
ArsenShnurkov/BitSharp
BitSharp.Common/ImmutableBitArray.cs
BitSharp.Common/ImmutableBitArray.cs
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitSharp.Common { public class ImmutableBitArray : IEnumerable<bool> { private readonly BitArray bitArray; public ImmutableBitArray(int length, bool defaultValue) { this.bitArray = new BitArray(length, defaultValue); } public ImmutableBitArray(BitArray bitArray) { this.bitArray = (BitArray)bitArray.Clone(); } private ImmutableBitArray(BitArray bitArray, bool clone) { this.bitArray = clone ? (BitArray)bitArray.Clone() : bitArray; } public bool this[int index] { get { return this.bitArray[index]; } } public int Length { get { return this.bitArray.Length; } } public ImmutableBitArray Set(int index, bool value) { var bitArray = (BitArray)this.bitArray.Clone(); bitArray[index] = value; return new ImmutableBitArray(bitArray, clone: false); } public IEnumerator<bool> GetEnumerator() { for (var i = 0; i < this.bitArray.Length; i++) yield return this.bitArray[i]; } IEnumerator IEnumerable.GetEnumerator() { return this.bitArray.GetEnumerator(); } public override bool Equals(object obj) { if (!(obj is ImmutableBitArray)) return false; return (ImmutableBitArray)obj == this; } public override int GetHashCode() { return this.bitArray.GetHashCode(); } public static bool operator ==(ImmutableBitArray left, ImmutableBitArray right) { return left.SequenceEqual(right); } public static bool operator !=(ImmutableBitArray left, ImmutableBitArray right) { return !(left == right); } } }
unlicense
C#
0cf59fcff988a090eb3aee3f76f702210cfae7a5
add string pair class from old version
0culus/ElectronicCash
ElectronicCash/IdentityStringPair.cs
ElectronicCash/IdentityStringPair.cs
using System; using System.Collections; using System.Collections.Generic; namespace e_cash { [Serializable] public struct IdentityStringPair<T> : IEnumerable<T> { private readonly T _left; private readonly T _right; public IdentityStringPair(T left, T right) { _left = left; _right = right; } public T Left { get { return _left; } } public T Right { get { return _right; } } public IEnumerator<T> GetEnumerator() { yield return Left; yield return Right; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
mit
C#
6169be4c983fc31099281bf04d806f62d0031615
add OrchestrationJumpStartEvent
affandar/durabletask,ddobric/durabletask,Azure/durabletask
Framework/Tracking/OrchestrationJumpStartEvent.cs
Framework/Tracking/OrchestrationJumpStartEvent.cs
// ---------------------------------------------------------------------------------- // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace DurableTask.Tracking { using System; public class OrchestrationJumpStartEvent : OrchestrationHistoryEvent { public DateTime JumpStartTime; public OrchestrationState State; } }
apache-2.0
C#
f3555ad08cfdc71a61efeb88fde64104484bf8e5
add APIWikiPage response
peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,peppy/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu
osu.Game/Online/API/Requests/Responses/APIWikiPage.cs
osu.Game/Online/API/Requests/Responses/APIWikiPage.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.Collections.Generic; using Newtonsoft.Json; namespace osu.Game.Online.API.Requests.Responses { public class APIWikiPage { [JsonProperty("layout")] public string Layout { get; set; } [JsonProperty("locale")] public string Locale { get; set; } [JsonProperty("markdown")] public string Markdown { get; set; } [JsonProperty("path")] public string Path { get; set; } [JsonProperty("subtitle")] public string Subtitle { get; set; } [JsonProperty("tags")] public List<string> Tags { get; set; } [JsonProperty("title")] public string Title { get; set; } } }
mit
C#
ffd277f7739a5da1df939f4709d986c15f7b0f88
Create VectorCurrencyConverter.cs
orbital7/orbital7.extensions,orbital7/orbital7.extensions
src/Orbital7.Extensions.Xamarin/VectorCurrencyConverter.cs
src/Orbital7.Extensions.Xamarin/VectorCurrencyConverter.cs
using System; using System.Globalization; using System.Text.RegularExpressions; namespace Xamarin.Forms { public class VectorCurrencyConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { var d = decimal.Parse(value.ToString()); var conversion = d.ToString("C"); if (d > 0) conversion = "+" + conversion; return conversion; } else { return null; } } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { string valueFromString = Regex.Replace(value.ToString(), @"\D", ""); if (valueFromString.Length <= 0) return null; if (!long.TryParse(valueFromString, out long valueLong)) return null; if (valueLong < 0) return null; return valueLong / 100m; } } }
mit
C#
c1ad6b37521ac3de31486ab2f728a1d7e951dcf4
Add suport of nullable reference type attributes for lower TFM
KodamaSakuno/Sakuno.Base
src/Sakuno.Base/NullableReferenceTypeSupportForLowerTFM.cs
src/Sakuno.Base/NullableReferenceTypeSupportForLowerTFM.cs
#if !NETSTANDARD2_1 namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } #endif
mit
C#
ae4be94d940040fd43e150b11154defd5a90f588
Add RazorDocumentInfoFactory (#43226)
AlekseyTs/roslyn,wvdd007/roslyn,sharwell/roslyn,mavasani/roslyn,panopticoncentral/roslyn,brettfo/roslyn,stephentoub/roslyn,aelij/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,gafter/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,reaction1989/roslyn,heejaechang/roslyn,dotnet/roslyn,gafter/roslyn,physhi/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,genlu/roslyn,brettfo/roslyn,panopticoncentral/roslyn,reaction1989/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,davkean/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,aelij/roslyn,stephentoub/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,gafter/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,tannergooding/roslyn,wvdd007/roslyn,davkean/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,jmarolf/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,diryboy/roslyn,eriawan/roslyn,heejaechang/roslyn,wvdd007/roslyn,physhi/roslyn,aelij/roslyn,eriawan/roslyn,bartdesmet/roslyn,davkean/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,sharwell/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,tmat/roslyn,genlu/roslyn,mavasani/roslyn,AmadeusW/roslyn,physhi/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,genlu/roslyn,eriawan/roslyn
src/Tools/ExternalAccess/Razor/RazorDocumentInfoFactory.cs
src/Tools/ExternalAccess/Razor/RazorDocumentInfoFactory.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.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal static class RazorDocumentInfoFactory { public static DocumentInfo Create( DocumentId id, string name, IEnumerable<string>? folders, SourceCodeKind sourceCodeKind, TextLoader? loader, string? filePath, bool isGenerated, RazorDocumentServiceProviderWrapper documentServiceProvider) { return DocumentInfo.Create(id, name, folders.ToBoxedImmutableArray(), sourceCodeKind, loader, filePath, isGenerated, documentServiceProvider); } } }
mit
C#
5ce48a9fcb0ca25cc2771435dfd5fad6f8ef107e
Add the builder of DateRange
Seddryck/NBi,Seddryck/NBi
NBi.Core/Members/Ranges/DateRangeBuilder.cs
NBi.Core/Members/Ranges/DateRangeBuilder.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace NBi.Core.Members.Ranges { internal class DateRangeBuilder : BaseBuilder { protected new DateRange Range { get { return (DateRange)base.Range; } } protected override void InternalBuild() { if (string.IsNullOrEmpty(Range.Format)) Result = Build(Range.Start, Range.End, Range.Culture, ToShortDatePattern); else Result = Build(Range.Start, Range.End, Range.Culture, Range.Format); } public IEnumerable<string> Build(DateTime start, DateTime end, CultureInfo culture, Func<CultureInfo, DateTime, string> dateFormatter) { var list = new List<string>(); var date= start; while (date <= end) { var dateString = dateFormatter(culture, date); list.Add(dateString); date = date.AddDays(1); } return list; } public IEnumerable<string> Build(DateTime start, DateTime end, CultureInfo culture, string format) { var list = new List<string>(); var date = start; while (date <= end) { var dateString = date.ToString(format, culture.DateTimeFormat); list.Add(dateString); date = date.AddDays(1); } return list; } protected string ToLongDatePattern(CultureInfo culture, DateTime value) { return value.ToString(culture.DateTimeFormat.LongDatePattern); } protected string ToShortDatePattern(CultureInfo culture, DateTime value) { return value.ToString(culture.DateTimeFormat.ShortDatePattern); } } }
apache-2.0
C#
1d9c28ddd8b9cf8c786a9f56c2db49a809a325f5
Fix incorrect copying of blending values.
naoey/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,RedNesto/osu-framework,peppy/osu-framework,default0/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,naoey/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,default0/osu-framework,NeoAdonis/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,NeoAdonis/osu-framework,ppy/osu-framework,peppy/osu-framework,paparony03/osu-framework,Tom94/osu-framework,RedNesto/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework
osu.Framework/Graphics/BlendingInfo.cs
osu.Framework/Graphics/BlendingInfo.cs
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK.Graphics.ES30; namespace osu.Framework.Graphics { public struct BlendingInfo { public BlendingFactorSrc Source; public BlendingFactorDest Destination; public BlendingFactorSrc SourceAlpha; public BlendingFactorDest DestinationAlpha; public BlendingInfo(bool additive) { Source = BlendingFactorSrc.SrcAlpha; Destination = BlendingFactorDest.OneMinusSrcAlpha; SourceAlpha = BlendingFactorSrc.One; DestinationAlpha = BlendingFactorDest.One; Additive = additive; } public bool Additive { set { Destination = value ? BlendingFactorDest.One : BlendingFactorDest.OneMinusSrcAlpha; } } /// <summary> /// Copies the current BlendingInfo into target. /// </summary> /// <param name="target">The BlendingInfo to be filled with the copy.</param> public void Copy(ref BlendingInfo target) { target.Source = Source; target.Destination = Destination; target.SourceAlpha = SourceAlpha; target.DestinationAlpha = DestinationAlpha; } public bool Equals(BlendingInfo other) { return other.Source == Source && other.Destination == Destination && other.SourceAlpha == SourceAlpha && other.DestinationAlpha == DestinationAlpha; } } }
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK.Graphics.ES30; namespace osu.Framework.Graphics { public struct BlendingInfo { public BlendingFactorSrc Source; public BlendingFactorDest Destination; public BlendingFactorSrc SourceAlpha; public BlendingFactorDest DestinationAlpha; public BlendingInfo(bool additive) { Source = BlendingFactorSrc.SrcAlpha; Destination = BlendingFactorDest.OneMinusSrcAlpha; SourceAlpha = BlendingFactorSrc.One; DestinationAlpha = BlendingFactorDest.One; Additive = additive; } public bool Additive { set { Destination = value ? BlendingFactorDest.One : BlendingFactorDest.OneMinusSrcAlpha; } } /// <summary> /// Copies the current BlendingInfo into target. /// </summary> /// <param name="target">The BlendingInfo to be filled with the copy.</param> public void Copy(ref BlendingInfo target) { target.Source = Source; target.Destination = Destination; target.SourceAlpha = Source; target.DestinationAlpha = Destination; } public bool Equals(BlendingInfo other) { return other.Source == Source && other.Destination == Destination && other.SourceAlpha == SourceAlpha && other.DestinationAlpha == DestinationAlpha; } } }
mit
C#
9974c205d2bdd90ca5fde9904bda9708d415e972
Tag Search Unit Test
InstaSharp/InstaSharp,crashdavis23/InstaSharp,crashdavis23/InstaSharp,3nGercog/InstaSharp,danielmundim/InstaSharp,3nGercog/InstaSharp,danielmundim/InstaSharp,theShiva/InstaSharp,theShiva/InstaSharp
src/InstaSharp.Tests/Tags.cs
src/InstaSharp.Tests/Tags.cs
using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace InstaSharp.Tests { [TestClass] public class Tags : TestBase { readonly Endpoints.Tags tags; public Tags() { tags = new Endpoints.Tags(Config); } [TestMethod, TestCategory("Tags.Get")] public async Task Get() { var result = await tags.Get("beiber"); Assert.IsTrue(result.Data.Name == "beiber"); } [TestMethod, TestCategory("Tags.Search")] public async Task Search() { var result = await tags.Search("Cats"); Assert.IsTrue(result.Data.Any()); } [TestMethod, TestCategory("Tags.Recent")] public async Task Recent() { var result = await tags.Recent("csharp"); Assert.IsTrue(result.Data.Count > 0); } [TestMethod, TestCategory("Tags.Recent")] public async Task Recent_MinId() { var result = await tags.Recent("csharp"); result = await tags.Recent("csharp", result.Pagination.NextMinId, null); Assert.IsTrue(result.Data.Count == 0); } [TestMethod, TestCategory("Tags.Recent")] public async Task Recent_MaxId() { var result = await tags.Recent("csharp"); result = await tags.Recent("csharp", null, result.Pagination.NextMaxId); Assert.IsTrue(result.Data.Count > 0); } } }
using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace InstaSharp.Tests { [TestClass] public class Tags : TestBase { readonly Endpoints.Tags tags; public Tags() { tags = new Endpoints.Tags(Config); } [TestMethod, TestCategory("Tags.Get")] public async Task Get() { var result = await tags.Get("beiber"); Assert.IsTrue(result.Data.Name == "beiber"); } [TestMethod, TestCategory("Tags.Recent")] public async Task Recent() { var result = await tags.Recent("csharp"); Assert.IsTrue(result.Data.Count > 0); } [TestMethod, TestCategory("Tags.Recent")] public async Task Recent_MinId() { var result = await tags.Recent("csharp"); result = await tags.Recent("csharp", result.Pagination.NextMinId, null); Assert.IsTrue(result.Data.Count == 0); } [TestMethod, TestCategory("Tags.Recent")] public async Task Recent_MaxId() { var result = await tags.Recent("csharp"); result = await tags.Recent("csharp", null, result.Pagination.NextMaxId); Assert.IsTrue(result.Data.Count > 0); } } }
apache-2.0
C#
40ffd1bc43aef5eadfa2eb4e6ab179afb0ee97c3
Add files via upload
brandonseydel/MailChimp.Net
MailChimp.Net.Tests/ECommerceLogicTest.cs
MailChimp.Net.Tests/ECommerceLogicTest.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ApiTest.cs" company="Brandon Seydel"> // N/A // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MailChimp.Net.Tests { /// <summary> /// The authorized app test. /// </summary> [TestClass] public class ECommerceLogicTest : MailChimpTest { /// <summary> /// The should_ return_ app_ information. /// </summary> /// <returns> /// The <see cref="Task"/>. /// </returns> [TestMethod] public async Task Should_Return_App_Information() { var apiInfo = await this._mailChimpManager.ECommerceStores.Carts("asdfd").GetAllAsync(); Assert.IsNotNull(apiInfo); } } }
mit
C#
df7dc4f20276d14fa5f340632734a02cf6580d77
Add FileSystem implementation for the iOS project
laurentiustamate94/netstandard-storage
Plugin.NetStandardStorage.iOS/Implementations/FileSystem.cs
Plugin.NetStandardStorage.iOS/Implementations/FileSystem.cs
using System; using System.IO; using Foundation; using Plugin.NetStandardStorage.Abstractions.Interfaces; namespace Plugin.NetStandardStorage.Implementations { public class FileSystem : IFileSystem { public IFolder LocalStorage { get { var localStorage = NSFileManager.DefaultManager .GetUrls(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User)[0]; return new Folder(localStorage.Path, canDelete: false); } } public IFolder RoamingStorage { get { throw new PlatformNotSupportedException("The Roaming folder is not supported in iOS !"); } } public IFile GetFileFromPath(string path) { if (string.IsNullOrEmpty(path)) { throw new FormatException("Null or emtpy *path* argument not allowed !"); } if (System.IO.File.Exists(path)) { return new File(path); } return null; } public IFolder GetFolderFromPath(string path) { if (string.IsNullOrEmpty(path)) { throw new FormatException("Null or emtpy *path* argument not allowed !"); } if (Directory.Exists(path)) { return new Folder(path); } return null; } } }
mit
C#
05ea82468287d358f53dd0bb5a9d9d7aaf7705ec
add fizz1
CiaranCarrick/Test
Assets/fizz1.cs
Assets/fizz1.cs
using UnityEngine; using System.Collections; public class fizz1 : MonoBehaviour { // Use this for initialization void Start () { } void swap(){ int a = 132; int b = 1223; a = a - a; a = b+a; print (a); } void fizz(){ for (int i = 1; i <= 100; i++) { if(i % 3 == 0 && i % 5 == 0){ Debug.Log("FizzBuzz"); } else if(i % 3 == 0){ Debug.Log("Fizz"); } else if(i % 5 == 0){ Debug.Log("Buzz"); } else Debug.Log(i); } } // Update is called once per frame void Update () { } }
mit
C#
fb0a056d76bab60ecf9dfe3ca7d13aa7f859c6cf
Add IUser#SendMessageAsync extension (#706)
RogueException/Discord.Net,AntiTcb/Discord.Net,Confruggy/Discord.Net
src/Discord.Net.Core/Extensions/UserExtensions.cs
src/Discord.Net.Core/Extensions/UserExtensions.cs
using System.Threading.Tasks; namespace Discord { public static class UserExtensions { public static async Task<IUserMessage> SendMessageAsync(this IUser user, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null) { return await (await user.GetOrCreateDMChannelAsync().ConfigureAwait(false)).SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false); } } }
mit
C#
f889f0df364614214445733214d68ad94bc94416
Add tests for the BarLineGenerator
ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game.Rulesets.Taiko.Tests/TestSceneBarLineGeneration.cs
osu.Game.Rulesets.Taiko.Tests/TestSceneBarLineGeneration.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.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Beatmaps.Timing; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Taiko.Objects; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Taiko.Tests { public class TestSceneBarLineGeneration : OsuTestScene { [Test] public void TestCloseBarLineGeneration() { const double start_time = 1000; var beatmap = new Beatmap<TaikoHitObject> { HitObjects = { new Hit { Type = HitType.Centre, StartTime = start_time } }, BeatmapInfo = { Difficulty = new BeatmapDifficulty { SliderTickRate = 4 }, Ruleset = new TaikoRuleset().RulesetInfo }, }; beatmap.ControlPointInfo.Add(start_time, new TimingControlPoint()); beatmap.ControlPointInfo.Add(start_time + 1, new TimingControlPoint()); var barlines = new BarLineGenerator<BarLine>(beatmap).BarLines; AddAssert("first barline generated", () => barlines.Any(b => b.StartTime == start_time)); AddAssert("second barline generated", () => barlines.Any(b => b.StartTime == start_time + 1)); } [Test] public void TestOmitBarLineEffectPoint() { const double start_time = 1000; const double beat_length = 500; const int time_signature_numerator = 4; var beatmap = new Beatmap<TaikoHitObject> { HitObjects = { new Hit { Type = HitType.Centre, StartTime = start_time } }, BeatmapInfo = { Difficulty = new BeatmapDifficulty { SliderTickRate = 4 }, Ruleset = new TaikoRuleset().RulesetInfo }, }; beatmap.ControlPointInfo.Add(start_time, new TimingControlPoint { BeatLength = beat_length, TimeSignature = new TimeSignature(time_signature_numerator) }); beatmap.ControlPointInfo.Add(start_time, new EffectControlPoint { OmitFirstBarLine = true }); var barlines = new BarLineGenerator<BarLine>(beatmap).BarLines; AddAssert("first barline ommited", () => !barlines.Any(b => b.StartTime == start_time)); AddAssert("second barline generated", () => barlines.Any(b => b.StartTime == start_time + (beat_length * time_signature_numerator))); } } }
mit
C#
b48952e9b5af446ff0326591df07c91a1ede14f6
Add CssUnitTests
Carbon/Css
src/Carbon.Css.Tests/CssUnitTests.cs
src/Carbon.Css.Tests/CssUnitTests.cs
using Xunit; namespace Carbon.Css.Tests { public class CssUnitTests { // switch = 224ms // dictionary = 149ms [Fact] public void Lookup() { Assert.Equal(CssUnitInfo.Px, CssUnitInfo.Get("px")); Assert.Equal(CssUnitInfo.Pt, CssUnitInfo.Get("pt")); Assert.Equal(CssUnitInfo.Deg, CssUnitInfo.Get("deg")); } [Fact] public void Equality() { Assert.True(CssUnitInfo.Px.Equals(CssUnitInfo.Px)); Assert.False(CssUnitInfo.Pt.Equals(CssUnitInfo.Px)); } [Theory] [InlineData("px", NodeKind.Length)] [InlineData("pt", NodeKind.Length)] [InlineData("kHz", NodeKind.Frequency)] [InlineData("s", NodeKind.Time)] public void KindIsCorrect(string text, NodeKind kind) { Assert.Equal(kind, CssUnitInfo.Get(text).Kind); } [Fact] public void UnknownUnitEquality() { Assert.True(CssUnitInfo.Get("ns").Equals(CssUnitInfo.Get("ns"))); Assert.False(CssUnitInfo.Get("ns").Equals(CssUnitInfo.Get("ms"))); } } }
mit
C#
d18d729c665dfdad443f778e2946b05cd2b247c5
Introduce empty unit tests for Conversion tuples
thnetii/dotnet-common
test/THNETII.Common.Test/Common/Test/ConversionTupleTest.cs
test/THNETII.Common.Test/Common/Test/ConversionTupleTest.cs
using System; using Xunit; namespace THNETII.Common.Test { public class ConversionTupleTest { } }
mit
C#
4779b9b21fa603a111202d300c537eb0f1bbf064
Add RuleLexerFactory
StevenLiekens/TextFx,StevenLiekens/Txt
src/Txt.ABNF/RuleLexerFactory.cs
src/Txt.ABNF/RuleLexerFactory.cs
using System; using JetBrains.Annotations; using Txt.Core; namespace Txt.ABNF { public abstract class RuleLexerFactory<T> : LexerFactory<T> where T : Element { protected RuleLexerFactory() : this( TerminalLexerFactory.Default, ValueRangeLexerFactory.Default, AlternationLexerFactory.Default, ConcatenationLexerFactory.Default, RepetitionLexerFactory.Default, OptionLexerFactory.Default) { } protected RuleLexerFactory( [NotNull] ITerminalLexerFactory terminalLexerFactory, [NotNull] IValueRangeLexerFactory valueRangeLexerFactory, [NotNull] IAlternationLexerFactory alternationLexerFactory, [NotNull] IConcatenationLexerFactory concatenationLexerFactory, [NotNull] IRepetitionLexerFactory repetitionLexerFactory, [NotNull] IOptionLexerFactory optionLexerFactory) { if (terminalLexerFactory == null) { throw new ArgumentNullException(nameof(terminalLexerFactory)); } if (valueRangeLexerFactory == null) { throw new ArgumentNullException(nameof(valueRangeLexerFactory)); } if (alternationLexerFactory == null) { throw new ArgumentNullException(nameof(alternationLexerFactory)); } if (concatenationLexerFactory == null) { throw new ArgumentNullException(nameof(concatenationLexerFactory)); } if (repetitionLexerFactory == null) { throw new ArgumentNullException(nameof(repetitionLexerFactory)); } if (optionLexerFactory == null) { throw new ArgumentNullException(nameof(optionLexerFactory)); } Terminal = terminalLexerFactory; ValueRange = valueRangeLexerFactory; Alternation = alternationLexerFactory; Concatenation = concatenationLexerFactory; Repetition = repetitionLexerFactory; Option = optionLexerFactory; } [NotNull] public IAlternationLexerFactory Alternation { get; set; } [NotNull] public IConcatenationLexerFactory Concatenation { get; set; } [NotNull] public IOptionLexerFactory Option { get; set; } [NotNull] public IRepetitionLexerFactory Repetition { get; set; } [NotNull] public ITerminalLexerFactory Terminal { get; set; } [NotNull] public IValueRangeLexerFactory ValueRange { get; set; } } }
mit
C#
d6eb5eee2533f4117a8b0943999b848b378d9cda
Add ChangeType
charlenni/Mapsui,pauldendulk/Mapsui,charlenni/Mapsui
Mapsui/ChangeType.cs
Mapsui/ChangeType.cs
namespace Mapsui { public enum ChangeType { /// <summary> /// Discrete changes in Viewport state. /// Examples: /// - Plus and minus buttons. /// - Map Initialization. /// - Final change in an animation /// - Touch-up after dragging. /// - Final mouse wheel change /// </summary> Discrete, /// <summary> /// Continuous changes in Viewport state. /// Examples: /// - Dragging the map /// - During animations /// - Mouse wheel changes /// </summary> Continuous } }
mit
C#
d6d0e2c9a7eec5a2403e8cad5f89213b168feb72
Create a supplier that supply elements continually(Stream).
nohros/must,nohros/must,nohros/must
src/base/common/type/suppliers/ISupplierStream.cs
src/base/common/type/suppliers/ISupplierStream.cs
using System; namespace Nohros { /// <summary> /// A implementation of the <see cref="ISupplier{T}"/> class that supply /// elements of type <typeparamref name="T"/> in a sequence. /// </summary> /// <typeparam name="T"> /// The type of objects supplied. /// </typeparam> public interface ISupplierStream<T> : ISupplier<T> { /// <summary> /// Gets a value indicating if an item available is available from the /// supplier. /// </summary> /// <value> /// <c>true</c> if an item is available from the supplier(that is, if /// <see cref="ISupplier{T}.Supply"/> method wolud return a value); /// otherwise <c>false</c>. /// </value> bool Available { get; } } }
mit
C#
708a4577c18da9ef643ac8fe02b8f1f3de8e294a
Create FocusOnPointerMovedBehavior.cs
XamlBehaviors/XamlBehaviors,XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Core/FocusOnPointerMovedBehavior.cs
src/Avalonia.Xaml.Interactions/Core/FocusOnPointerMovedBehavior.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Avalonia.Controls; using Avalonia.Input; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Core { /// <summary> /// Focuses the AssociatedObject on PointerMoved event. /// </summary> public sealed class FocusOnPointerMovedBehavior : Behavior<Control> { /// <inheritdoc/> protected override void OnAttached() { base.OnAttached(); AssociatedObject.PointerMoved += PointerMoved; } /// <inheritdoc/> protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PointerMoved -= PointerMoved; } private void PointerMoved(object sender, PointerEventArgs args) { AssociatedObject.Focus(); } } }
mit
C#
a14b4179ee3dab0037aad36b899b38150a13aa48
Add provider for RequestProfilers
mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype
src/Glimpse.Agent.Web/Framework/IRequestProfilerProvider.cs
src/Glimpse.Agent.Web/Framework/IRequestProfilerProvider.cs
using System; using System.Collections.Generic; namespace Glimpse.Agent.Web { public interface IRequestProfilerProvider { IEnumerable<IRequestProfiler> Profilers { get; } } }
mit
C#
19b2ffa3dfcc1e16ba7ad7c5a90d175e4d83ff2b
Add GuidOption
merijndejonge/OptionParser
src/OptionParser/GuidOption.cs
src/OptionParser/GuidOption.cs
using System; namespace OpenSoftware.OptionParsing { public class GuidOption : Option<Guid> { public override Guid Value { get => Guid.TryParse(RawValue, out var result) ? result : Guid.Empty; protected set => RawValue = value.ToString(); } public override string RawValue { get => base.RawValue; protected set { if (Guid.TryParse(value, out var _) == false) { throw new InvalidOptionValueException($@"{value} is not a valid GUID."); } base.RawValue = value; } } } }
apache-2.0
C#
1ab449b73e081284f88125c696845c51c35ae984
Add test scene for drawings screen
NeoAdonis/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,smoogipooo/osu
osu.Game.Tournament.Tests/Screens/TestSceneDrawingsScreen.cs
osu.Game.Tournament.Tests/Screens/TestSceneDrawingsScreen.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.IO; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game.Graphics.Cursor; using osu.Game.Tournament.Screens.Drawings; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneDrawingsScreen : TournamentTestScene { [BackgroundDependencyLoader] private void load(Storage storage) { using (var stream = storage.GetStream("drawings.txt", FileAccess.Write)) using (var writer = new StreamWriter(stream)) { writer.WriteLine("KR : South Korea : KOR"); writer.WriteLine("US : United States : USA"); writer.WriteLine("PH : Philippines : PHL"); writer.WriteLine("BR : Brazil : BRA"); writer.WriteLine("JP : Japan : JPN"); } Add(new OsuContextMenuContainer { RelativeSizeAxes = Axes.Both, Child = new DrawingsScreen() }); } } }
mit
C#
50ee23f0f22276fe1c48d92e5eab907919734425
Make debug more robust
sillsdev/gtk-sharp,sillsdev/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,Gankov/gtk-sharp,orion75/gtk-sharp
cairo/CairoDebug.cs
cairo/CairoDebug.cs
// // CairoDebug.cs // // Author: // Michael Hutchinson (mhutch@xamarin.com) // // Copyright (C) 2013 Xamarin Inc. (http://www.xamarin.com) // // 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. // using System; namespace Cairo { static class CairoDebug { static System.Collections.Generic.Dictionary<IntPtr,string> traces; public static readonly bool Enabled; static CairoDebug () { var dbg = Environment.GetEnvironmentVariable ("MONO_CAIRO_DEBUG_DISPOSE"); if (dbg == null) return; Enabled = true; traces = new System.Collections.Generic.Dictionary<IntPtr,string> (); } public static void OnAllocated (IntPtr obj) { if (!Enabled) throw new InvalidOperationException (); traces[obj] = Environment.StackTrace; } public static void OnDisposed<T> (IntPtr obj, bool disposing) { if (disposing && !Enabled) throw new InvalidOperationException (); if (!disposing) { Console.Error.WriteLine ("{0} is leaking, programmer is missing a call to Dispose", typeof(T).FullName); if (Enabled) { string val; if (traces.TryGetValue (obj, out val)) { Console.Error.WriteLine ("Allocated from:"); Console.Error.WriteLine (val); } } else { Console.Error.WriteLine ("Set MONO_CAIRO_DEBUG_DISPOSE to track allocation traces"); } } if (Enabled) traces.Remove (obj); } } }
// // CairoDebug.cs // // Author: // Michael Hutchinson (mhutch@xamarin.com) // // Copyright (C) 2013 Xamarin Inc. (http://www.xamarin.com) // // 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. // using System; namespace Cairo { static class CairoDebug { static System.Collections.Generic.Dictionary<IntPtr,string> traces; public static readonly bool Enabled; static CairoDebug () { var dbg = Environment.GetEnvironmentVariable ("MONO_CAIRO_DEBUG_DISPOSE"); if (dbg == null) return; Enabled = true; traces = new System.Collections.Generic.Dictionary<IntPtr,string> (); } public static void OnAllocated (IntPtr obj) { if (!Enabled) throw new InvalidOperationException (); traces.Add (obj, Environment.StackTrace); } public static void OnDisposed<T> (IntPtr obj, bool disposing) { if (disposing && !Enabled) throw new InvalidOperationException (); if (!disposing) { Console.Error.WriteLine ("{0} is leaking, programmer is missing a call to Dispose", typeof(T).FullName); if (Enabled) { Console.Error.WriteLine ("Allocated from:"); Console.Error.WriteLine (traces[obj]); } else { Console.Error.WriteLine ("Set MONO_CAIRO_DEBUG_DISPOSE to track allocation traces"); } } if (Enabled) traces.Remove (obj); } } }
lgpl-2.1
C#
2c2f1e49d5fb0ddd93b9d2bab8555c4a6f089ffd
add missing attribute formatting
sillsdev/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp
audit/extract-missing.cs
audit/extract-missing.cs
// extract-missing.cs - grab missing api elements from api-diff files. // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2005 Mike Kestner // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GtkSharp.Auditing { using System; using System.IO; using System.Xml; using System.Xml.XPath; public class ExtractMissing { public static int Main (string[] args) { if (args.Length != 1 || !File.Exists (args [0])) { Console.WriteLine ("Usage: extract-missing <filename>"); return 0; } XmlDocument doc = new XmlDocument (); try { Stream stream = File.OpenRead (args [0]); doc.Load (stream); stream.Close (); } catch (XmlException e) { Console.WriteLine ("Invalid apidiff file."); Console.WriteLine (e); return 1; } XPathNavigator nav = doc.CreateNavigator (); XPathNodeIterator iter = nav.Select ("//*[@presence='missing']"); while (iter.MoveNext ()) { XmlElement node = ((IHasXmlNode)iter.Current).GetNode () as XmlElement; if (node.Name == "class") Console.WriteLine ("Missing type: " + node.GetAttribute ("name")); else if (node.ParentNode.ParentNode.Name == "class") Console.WriteLine ("Missing " + node.Name + " " + (node.ParentNode.ParentNode as XmlElement).GetAttribute ("name") + "." + node.GetAttribute ("name")); else if (node.Name == "attribute") { if (node.ParentNode.ParentNode.Name == "class") Console.WriteLine ("Missing attribute (" + (node as XmlElement).GetAttribute ("name") + ") on type: " + (node.ParentNode.ParentNode as XmlElement).GetAttribute ("name")); else if (node.ParentNode.ParentNode.ParentNode.ParentNode.Name == "class") Console.WriteLine ("Missing attribute (" + (node as XmlElement).GetAttribute ("name") + ") on " + (node.ParentNode.ParentNode.ParentNode.ParentNode as XmlElement).GetAttribute ("name") + "." + (node.ParentNode.ParentNode as XmlElement).GetAttribute ("name")); else Console.WriteLine ("oopsie: " + node.Name + " " + node.ParentNode.ParentNode.Name); } else Console.WriteLine ("oopsie: " + node.Name + " " + node.ParentNode.ParentNode.Name); } return 0; } } }
// extract-missing.cs - grab missing api elements from api-diff files. // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2005 Mike Kestner // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GtkSharp.Auditing { using System; using System.IO; using System.Xml; using System.Xml.XPath; public class ExtractMissing { public static int Main (string[] args) { if (args.Length != 1 || !File.Exists (args [0])) { Console.WriteLine ("Usage: extract-missing <filename>"); return 0; } XmlDocument doc = new XmlDocument (); try { Stream stream = File.OpenRead (args [0]); doc.Load (stream); stream.Close (); } catch (XmlException e) { Console.WriteLine ("Invalid apidiff file."); Console.WriteLine (e); return 1; } XPathNavigator nav = doc.CreateNavigator (); XPathNodeIterator iter = nav.Select ("//*[@presence='missing']"); while (iter.MoveNext ()) { XmlElement node = ((IHasXmlNode)iter.Current).GetNode () as XmlElement; if (node.Name == "class") Console.WriteLine ("Missing type: " + node.GetAttribute ("name")); else if (node.ParentNode.ParentNode.Name == "class") Console.WriteLine ("Missing " + node.Name + " " + (node.ParentNode.ParentNode as XmlElement).GetAttribute ("name") + "." + node.GetAttribute ("name")); else Console.WriteLine ("oopsie: " + node.Name + " " + node.ParentNode.ParentNode.Name); } return 0; } } }
lgpl-2.1
C#
11457be3d7c2d27568b0ab6ed7a1f860aa37797f
add Addin file to test Mono.Cecil.Rocks independantly
kzu/cecil,cgourlay/cecil,SiliconStudio/Mono.Cecil,gluck/cecil,ttRevan/cecil,sailro/cecil,joj/cecil,fnajera-rac-de/cecil,saynomoo/cecil,xen2/cecil,mono/cecil,furesoft/cecil,jbevain/cecil
rocks/Test/Mono.Cecil.Tests/Addin.cs
rocks/Test/Mono.Cecil.Tests/Addin.cs
using NUnit.Core.Extensibility; namespace Mono.Cecil.Tests { [NUnitAddin] public class CecilRocksAddin : CecilTestAddin { } }
mit
C#
a4f86d3660a6034185bc8db45f31d51485cc456f
Add examples and unit tests for comparing structs.
StephenCleary/Comparers
test/UnitTests/ComparableBase_Struct_DefaultComparer.cs
test/UnitTests/ComparableBase_Struct_DefaultComparer.cs
using System; using System.Collections.Generic; using System.Linq; using Nito.Comparers; using Nito.Comparers.Util; using Xunit; namespace UnitTests { public class ComparableBase_Struct_DefaultComparerUnitTests { private struct Person : IComparable<Person>, IEquatable<Person>, IComparable { public static readonly IFullComparer<Person> DefaultComparer = ComparerBuilder.For<Person>().OrderBy(p => p.LastName).ThenBy(p => p.FirstName); public string FirstName { get; set; } public string LastName { get; set; } public override bool Equals(object obj) => ComparableImplementations.ImplementEquals(DefaultComparer, this, obj); public override int GetHashCode() => ComparableImplementations.ImplementGetHashCode(DefaultComparer, this); public int CompareTo(Person other) => ComparableImplementations.ImplementCompareTo(DefaultComparer, this, other); public bool Equals(Person other) => ComparableImplementations.ImplementEquals(DefaultComparer, this, other); public int CompareTo(object obj) => ComparableImplementations.ImplementCompareTo(DefaultComparer, this, obj); } private static readonly Person AbeAbrams = new Person { FirstName = "Abe", LastName = "Abrams" }; private static readonly Person JackAbrams = new Person { FirstName = "Jack", LastName = "Abrams" }; private static readonly Person WilliamAbrams = new Person { FirstName = "William", LastName = "Abrams" }; private static readonly Person CaseyJohnson = new Person { FirstName = "Casey", LastName = "Johnson" }; [Fact] public void ImplementsComparerDefault() { var list = new List<Person> { JackAbrams, CaseyJohnson, AbeAbrams, WilliamAbrams }; list.Sort(); Assert.Equal(new[] { AbeAbrams, JackAbrams, WilliamAbrams, CaseyJohnson }, list); } [Fact] public void ImplementsComparerDefault_Hash() { var set = new HashSet<Person> { JackAbrams, CaseyJohnson, AbeAbrams }; Assert.True(set.Contains(new Person { FirstName = AbeAbrams.FirstName, LastName = AbeAbrams.LastName })); Assert.False(set.Contains(WilliamAbrams)); } [Fact] public void ImplementsComparerDefault_NonGeneric() { var set = new System.Collections.ArrayList() { JackAbrams, CaseyJohnson, AbeAbrams }; Assert.True(set.Contains(new Person { FirstName = AbeAbrams.FirstName, LastName = AbeAbrams.LastName })); Assert.False(set.Contains(WilliamAbrams)); } } }
mit
C#
d4c3780f3b611e5f6a198d444a992cc8bdd98e77
Add RelayCommand
SVss/SPP_3
XmlParserWpf/XmlParserWpf/Commands/RelayCommand.cs
XmlParserWpf/XmlParserWpf/Commands/RelayCommand.cs
using System; using System.Windows.Input; namespace XmlParserWpf.Commands { public class RelayCommand : ICommand { private readonly Action<object> _execute; private readonly Func<object, bool> _canExecute; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null) { _execute = execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute == null || _canExecute(parameter); } public void Execute(object parameter) { _execute(parameter); } } }
mit
C#
b2564ef0c0184cb285e5f3098e32c28d2be9cc45
Reorder list - off by one
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
LeetCode/remote/reorder_list.cs
LeetCode/remote/reorder_list.cs
// https://leetcode.com/problems/reorder-list/ // // Given a singly linked list L: L0→L1→…→Ln-1→Ln, // reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… // // You must do this in-place without altering the nodes' values. // // For example, // Given {1,2,3,4}, reorder it to {1,4,2,3}. using System; public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } public override String ToString() { return String.Format("{0} {1}", val, next == null ? String.Empty : next.ToString()); } } public class Solution { public void ReorderList(ListNode head) { if (head == null) { return; } var slow = head; var mid = new ListNode(0); mid.next = slow; var fast = head; while (fast != null && fast.next != null) { mid.next = slow; slow = slow.next; fast = fast.next.next; } mid.next.next = null; mid = slow; ListNode prev = null; while (slow != null) { var next = slow.next; slow.next = prev; prev = slow; slow = next; } mid = prev; while (mid != null) { var firstNext = head.next; var secondNext = mid.next; head.next = mid; mid.next = firstNext; head = firstNext; mid = secondNext; } } static void Main() { ListNode root = null; for (var i = 4; i >= 1; i--) { root = new ListNode(i) { next = root }; } Console.WriteLine(root); new Solution().ReorderList(root); Console.WriteLine(root); root = null; for (var i = 3; i >= 1; i--) { root = new ListNode(i) { next = root }; } Console.WriteLine(root); new Solution().ReorderList(root); Console.WriteLine(root); } }
mit
C#
67b346a75266128a431984a4473f6599cc78017d
Add Youtube filter to blockings
Nanabell/NoAdsHere
NoAdsHere/Services/AntiAds/Youtube.cs
NoAdsHere/Services/AntiAds/Youtube.cs
using System; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using NLog; using NoAdsHere.Common; using NoAdsHere.Services.Penalties; namespace NoAdsHere.Services.AntiAds { public class Youtube { private readonly Regex _ytLink = new Regex(@"(?i)youtu(?:\.(?i)be|be\.com)\/(?:.*v(?:\/|=)|(?:.*\/)?)([a-zA-Z0-9-_]+)", RegexOptions.Compiled); private readonly DiscordSocketClient _client; private readonly MongoClient _mongo; private readonly Logger _logger = LogManager.GetLogger("AntiAds"); public Youtube(IServiceProvider provider) { _client = provider.GetService<DiscordSocketClient>(); _mongo = provider.GetService<MongoClient>(); } public Task StartService() { _client.MessageReceived += YoutubeChecker; _logger.Info("Anti Youtube Service Started"); return Task.CompletedTask; } private async Task YoutubeChecker(SocketMessage socketMessage) { var message = socketMessage as SocketUserMessage; if (message == null) return; var context = GetConxtext(message); if (context.Guild == null) return; if (context.User.IsBot) return; if (_ytLink.IsMatch(context.Message.Content)) { _logger.Info($"Detected Youtube Link in Message {context.Message.Id}"); var setting = await _mongo.GetCollection<GuildSetting>(_client).GetGuildAsync(context.Guild.Id); await TryDelete(setting, context); } } private ICommandContext GetConxtext(SocketUserMessage message) => new SocketCommandContext(_client, message); private async Task TryDelete(GuildSetting settings, ICommandContext context) { var guildUser = context.User as IGuildUser; if (settings.Ignorings.Users.Contains(context.User.Id)) return; if (settings.Ignorings.Channels.Contains(context.Channel.Id)) return; if (guildUser != null && guildUser.RoleIds.Any(userRole => settings.Ignorings.Roles.Contains(userRole))) return; if (settings.Blockings.Youtube) { if (context.Channel.CheckChannelPermission(ChannelPermission.ManageMessages, await context.Guild.GetCurrentUserAsync())) { _logger.Info($"Deleting Message {context.Message.Id} from {context.User}. Message contained a Youtube Link"); try { await context.Message.DeleteAsync(); } catch (Exception e) { _logger.Warn(e, $"Deleting of Message {context.Message.Id} Failed"); } } else _logger.Warn($"Unable to Delete Message {context.Message.Id}. Missing ManageMessages Permission"); await Violations.AddPoint(context); } } } }
mit
C#
3c474f44b52467eb6d6880448d1bc55fcaeb26ca
Create Program.cs
szoliver/wxpay,szoliver/wxpay,szoliver/wxpay
dotnetcore3.1/Program.cs
dotnetcore3.1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Senparc.CO2NET; namespace AdminCP { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables().SetBasePath(AppContext.BaseDirectory); }); webBuilder.UseUrls("http://*:8899"); webBuilder.UseStartup<Startup>(); }).UseServiceProviderFactory(new SenparcServiceProviderFactory()); } }
mit
C#
acbfee5b1c54f302496c16dfda4e757ca9bf7cab
Add "options", "check for updates" to context menu
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/ClickOnceHelper.cs
SteamAccountSwitcher/ClickOnceHelper.cs
#region using System; using System.Deployment.Application; using System.Windows; using Microsoft.Win32; #endregion namespace SteamAccountSwitcher { internal class ClickOnceHelper { public static bool IsFirstRun => (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.IsFirstRun); public static void CheckForUpdates() { if (!ApplicationDeployment.IsNetworkDeployed) { MessageBox.Show("This version was not installed via ClickOnce and cannot be updated automatically."); return; } var ad = ApplicationDeployment.CurrentDeployment; UpdateCheckInfo info; try { info = ad.CheckForDetailedUpdate(); } catch (DeploymentDownloadException dde) { MessageBox.Show( "The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message); return; } catch (InvalidDeploymentException ide) { MessageBox.Show( "Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message); return; } catch (InvalidOperationException ioe) { MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message); return; } if (info.UpdateAvailable) { var doUpdate = true; if (!info.IsUpdateRequired) { var dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButton.OKCancel); if (dr != MessageBoxResult.OK) { doUpdate = false; } } else { // Display a message that the app MUST reboot. Display the minimum required version. MessageBox.Show("This application has detected a mandatory update from your current " + "version to version " + info.MinimumRequiredVersion + ". The application will now install the update and shutdown.", "Update Available", MessageBoxButton.OK, MessageBoxImage.Information); } if (doUpdate) { try { ad.Update(); MessageBox.Show("The application has been upgraded, and will now shutdown."); System.Windows.Application.Current.Shutdown(); } catch (DeploymentDownloadException dde) { MessageBox.Show( "Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde); } } } } public static void RunOnStartup(bool run) { // The path to the key where Windows looks for startup applications var rkApp = Registry.CurrentUser.OpenSubKey( @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", run); //Path to launch shortcut var startPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs) + @"\Daniel Chalmers\SteamAccountSwitcher.appref-ms"; rkApp?.SetValue("SteamAccountSwitcher", startPath); } } }
mit
C#