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
77f1e96200bf8bf68cf3c7ee77f7ffbfe0f6c367
Update 20161207-2
novuslogic/NovuscodeLibrary.NET
Source/NovusCodeLibrary4.Utils/SystemUtils.cs
Source/NovusCodeLibrary4.Utils/SystemUtils.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace NovusCodeLibrary.Utils { public class SystemUtils { public static void MkDir(string aDirectory) { System.IO.Directory.CreateDirectory(aDirectory); } public static string TrailingBackSlash(string aPath) { string separator1 = Path.DirectorySeparatorChar.ToString(); string separator2 = Path.AltDirectorySeparatorChar.ToString(); aPath = aPath.TrimEnd(); if (aPath.EndsWith(separator1) || aPath.EndsWith(separator2)) return aPath; if (aPath.Contains(separator2)) return aPath + separator2; return aPath + separator1; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NovusCodeLibrary.Utils { public class SystemUtils { public static void MkDir(string aDirectory) { System.IO.Directory.CreateDirectory(aDirectory); } } }
apache-2.0
C#
e0753150fc23ed8a57ec0a65628447b7faeea408
Implement FilePath.Equals() and GetHashCode()
xoofx/libgit2sharp,Zoxive/libgit2sharp,jeffhostetler/public_libgit2sharp,GeertvanHorrik/libgit2sharp,nulltoken/libgit2sharp,AMSadek/libgit2sharp,shana/libgit2sharp,vorou/libgit2sharp,dlsteuer/libgit2sharp,mono/libgit2sharp,github/libgit2sharp,vorou/libgit2sharp,AArnott/libgit2sharp,PKRoma/libgit2sharp,nulltoken/libgit2sharp,libgit2/libgit2sharp,mono/libgit2sharp,whoisj/libgit2sharp,Skybladev2/libgit2sharp,AMSadek/libgit2sharp,jorgeamado/libgit2sharp,rcorre/libgit2sharp,Skybladev2/libgit2sharp,AArnott/libgit2sharp,OidaTiftla/libgit2sharp,jamill/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,ethomson/libgit2sharp,red-gate/libgit2sharp,dlsteuer/libgit2sharp,vivekpradhanC/libgit2sharp,psawey/libgit2sharp,jorgeamado/libgit2sharp,github/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,OidaTiftla/libgit2sharp,GeertvanHorrik/libgit2sharp,rcorre/libgit2sharp,oliver-feng/libgit2sharp,sushihangover/libgit2sharp,jamill/libgit2sharp,whoisj/libgit2sharp,shana/libgit2sharp,oliver-feng/libgit2sharp,red-gate/libgit2sharp,xoofx/libgit2sharp,sushihangover/libgit2sharp,Zoxive/libgit2sharp,vivekpradhanC/libgit2sharp,ethomson/libgit2sharp,psawey/libgit2sharp,jeffhostetler/public_libgit2sharp
LibGit2Sharp/Core/FilePath.cs
LibGit2Sharp/Core/FilePath.cs
using System; using System.IO; namespace LibGit2Sharp.Core { internal class FilePath : IEquatable<FilePath> { internal static FilePath Empty = new FilePath(string.Empty); private const char posixDirectorySeparatorChar = '/'; private readonly string native; private readonly string posix; private FilePath(string path) { native = Replace(path, posixDirectorySeparatorChar, Path.DirectorySeparatorChar); posix = Replace(path, Path.DirectorySeparatorChar, posixDirectorySeparatorChar); } public string Native { get { return native; } } public string Posix { get { return posix; } } public override string ToString() { return Native; } public static implicit operator FilePath(string path) { switch (path) { case null: return null; case "": return Empty; default: return new FilePath(path); } } private static string Replace(string path, char oldChar, char newChar) { if (oldChar == newChar) { return path; } return path == null ? null : path.Replace(oldChar, newChar); } public bool Equals(FilePath other) { return other == null ? posix == null : string.Equals(posix, other.posix, StringComparison.Ordinal); } public override bool Equals(object obj) { return Equals(obj as FilePath); } public override int GetHashCode() { return posix == null ? 0 : posix.GetHashCode(); } } }
using System.IO; namespace LibGit2Sharp.Core { internal class FilePath { internal static FilePath Empty = new FilePath(string.Empty); private const char posixDirectorySeparatorChar = '/'; private readonly string native; private readonly string posix; private FilePath(string path) { native = Replace(path, posixDirectorySeparatorChar, Path.DirectorySeparatorChar); posix = Replace(path, Path.DirectorySeparatorChar, posixDirectorySeparatorChar); } public string Native { get { return native; } } public string Posix { get { return posix; } } public override string ToString() { return Native; } public static implicit operator FilePath(string path) { switch (path) { case null: return null; case "": return Empty; default: return new FilePath(path); } } private static string Replace(string path, char oldChar, char newChar) { if (oldChar == newChar) { return path; } return path == null ? null : path.Replace(oldChar, newChar); } } }
mit
C#
8697da06c5ba4f8ae987c1a9b40b526e162a0b89
Update Source/Libraries/openXDA.Model/SystemCenter/RemoteXDAMeter.cs
GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA
Source/Libraries/openXDA.Model/SystemCenter/RemoteXDAMeter.cs
Source/Libraries/openXDA.Model/SystemCenter/RemoteXDAMeter.cs
//****************************************************************************************************** // AdditionalField.cs - Gbtc // // Copyright © 2019, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 05/19/2022 - Gabriel Santos // Generated original version of source code. // //****************************************************************************************************** using GSF.Data.Model; namespace openXDA.Model { /// <summary> /// Model of a remote asset. /// </summary> [AllowSearch] [DeleteRoles("Administrator")] [TableName("MetersToDataPush"), CustomView(@" SELECT MetersToDataPush.ID, MetersToDataPush.RemoteXDAInstanceID, MetersToDataPush.LocalXDAMeterID, MetersToDataPush.RemoteXDAMeterID, MetersToDataPush.RemoteXDAName, MetersToDataPush.RemoteXDAAssetKey, MetersToDataPush.Obsfucate, MetersToDataPush.Synced, Meter.Alias as LocalAlias, Meter.Name as LocalMeterName, Meter.AssetKey as LocalAssetKey FROM MetersToDataPush LEFT JOIN Meter ON MetersToDataPush.LocalXDAMeterID = Meter.ID")] public class RemoteXDAMeter : MetersToDataPush { public string LocalAlias { get; set; } public string LocalMeterName { get; set; } public string LocalAssetKey { get; set; } } }
//****************************************************************************************************** // AdditionalField.cs - Gbtc // // Copyright © 2019, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 05/19/2022 - Gabriel Santos // Generated original version of source code. // //****************************************************************************************************** using GSF.Data.Model; namespace openXDA.Model { /// <summary> /// Model of a remote asset. /// </summary> [AllowSearch] [DeleteRoles("Administrator")] [TableName("MetersToDataPush"), CustomView(@" SELECT MetersToDataPush.ID, MetersToDataPush.RemoteXDAInstanceID, MetersToDataPush.LocalXDAMeterID, MetersToDataPush.RemoteXDAMeterID, MetersToDataPush.RemoteXDAName, MetersToDataPush.RemoteXDAAssetKey, MetersToDataPush.Obsfucate, MetersToDataPush.Synced, Meter.Alias as LocalAlias, Meter.Name as LocalMeterName, Meter.AssetKey as LocalAssetKey FROM MetersToDataPush LEFT JOIN Meter ON MetersToDataPush.LocalXDAMeterID = Meter.ID")] public class RemoteXDAMeter : MetersToDataPush { public string LocalAlias { get; set; } public string LocalMeterName { get; set; } public string LocalAssetKey { get; set; } } }
mit
C#
6d60f398053cd504b905aeafc71089e95a3c2923
Add tests for SA1206 with the 'readonly', 'ref', and 'partial' keywords
DotNetAnalyzers/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/OrderingRules/SA1206CSharp7UnitTests.cs
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/OrderingRules/SA1206CSharp7UnitTests.cs
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.OrderingRules { using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using StyleCop.Analyzers.Test.OrderingRules; using TestHelper; using Xunit; public class SA1206CSharp7UnitTests : SA1206UnitTests { [Theory] [InlineData("readonly")] [InlineData("ref")] [InlineData("readonly ref")] [InlineData("readonly partial")] [InlineData("ref partial")] [InlineData("readonly ref partial")] [WorkItem(2578, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2578")] public async Task TestReadonlyRefKeywordInStructDeclarationAsync(string keywords) { var testCode = $@"class OuterClass {{ private {keywords} struct BitHelper {{ }} }} "; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestReadonlyKeywordInStructDeclarationWrongOrderAsync() { // Note that we don't need a test for ref with the wrong order, because this would be a compile time error var testCode = @"class OuterClass { readonly private struct BitHelper { } } "; DiagnosticResult[] expected = new[] { this.CSharpDiagnostic().WithLocation(3, 14).WithArguments("private", "readonly"), }; await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); } protected override Project ApplyCompilationOptions(Project project) { var newProject = base.ApplyCompilationOptions(project); var parseOptions = (CSharpParseOptions)newProject.ParseOptions; return newProject.WithParseOptions(parseOptions.WithLanguageVersion(LanguageVersion.Latest)); } } }
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.OrderingRules { using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using StyleCop.Analyzers.Test.OrderingRules; using TestHelper; using Xunit; public class SA1206CSharp7UnitTests : SA1206UnitTests { [Fact] public async Task TestRefKeywordInStructDeclarationAsync() { var testCode = @"class OuterClass { private ref struct BitHelper { } } "; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestReadonlyKeywordInStructDeclarationAsync() { var testCode = @"class OuterClass { private readonly struct BitHelper { } } "; await this.VerifyCSharpDiagnosticAsync(testCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestReadonlyKeywordInStructDeclarationWrongOrderAsync() { // Note that we don't need a test for ref with the wrong order, because this would be a compile time error var testCode = @"class OuterClass { readonly private struct BitHelper { } } "; DiagnosticResult[] expected = new[] { this.CSharpDiagnostic().WithLocation(3, 14).WithArguments("private", "readonly"), }; await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false); } protected override Project ApplyCompilationOptions(Project project) { var newProject = base.ApplyCompilationOptions(project); var parseOptions = (CSharpParseOptions)newProject.ParseOptions; return newProject.WithParseOptions(parseOptions.WithLanguageVersion(LanguageVersion.Latest)); } } }
mit
C#
43b322d0626704f1b1d7ff8c09480cdb474d1c6b
Remove the window content before adding a new child
mminns/xwt,hwthomas/xwt,steffenWi/xwt,residuum/xwt,akrisiun/xwt,sevoku/xwt,TheBrainTech/xwt,iainx/xwt,directhex/xwt,antmicro/xwt,lytico/xwt,cra0zy/xwt,hamekoz/xwt,mminns/xwt,mono/xwt
Xwt.Gtk/Xwt.GtkBackend/WindowBackend.cs
Xwt.Gtk/Xwt.GtkBackend/WindowBackend.cs
// // WindowBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Konrad Kruczyński <kkruczynski@antmicro.com> // // Copyright (c) 2011 Xamarin Inc // // 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; using Xwt.Backends; namespace Xwt.GtkBackend { public class WindowBackend: WindowFrameBackend, IWindowBackend { Gtk.Alignment alignment; Gtk.MenuBar mainMenu; Gtk.VBox mainBox; public override void Initialize () { Window = new Gtk.Window (""); Window.Add (CreateMainLayout ()); } protected virtual Gtk.Widget CreateMainLayout () { mainBox = new Gtk.VBox (); mainBox.Show (); alignment = new Gtk.Alignment (0, 0, 1, 1); mainBox.PackStart (alignment, true, true, 0); alignment.Show (); return mainBox; } public Gtk.VBox MainBox { get { return mainBox; } } public void SetChild (IWidgetBackend child) { var w = (IGtkWidgetBackend) child; if (alignment.Child != null) alignment.Remove (alignment.Child); alignment.Child = w.Widget; } public void SetMainMenu (IMenuBackend menu) { if (mainMenu != null) mainBox.Remove (mainMenu); if (menu != null) { MenuBackend m = (MenuBackend) menu; mainMenu = m.MenuBar; mainBox.PackStart (mainMenu, false, false, 0); ((Gtk.Box.BoxChild)mainBox[mainMenu]).Position = 0; } else mainMenu = null; } public void SetPadding (double left, double top, double right, double bottom) { alignment.LeftPadding = (uint) left; alignment.RightPadding = (uint) right; alignment.TopPadding = (uint) top; alignment.BottomPadding = (uint) bottom; } public void SetMinSize (Size s) { // Not required } } }
// // WindowBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Konrad Kruczyński <kkruczynski@antmicro.com> // // Copyright (c) 2011 Xamarin Inc // // 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; using Xwt.Backends; namespace Xwt.GtkBackend { public class WindowBackend: WindowFrameBackend, IWindowBackend { Gtk.Alignment alignment; Gtk.MenuBar mainMenu; Gtk.VBox mainBox; public override void Initialize () { Window = new Gtk.Window (""); Window.Add (CreateMainLayout ()); } protected virtual Gtk.Widget CreateMainLayout () { mainBox = new Gtk.VBox (); mainBox.Show (); alignment = new Gtk.Alignment (0, 0, 1, 1); mainBox.PackStart (alignment, true, true, 0); alignment.Show (); return mainBox; } public Gtk.VBox MainBox { get { return mainBox; } } public void SetChild (IWidgetBackend child) { var w = (IGtkWidgetBackend) child; alignment.Child = w.Widget; } public void SetMainMenu (IMenuBackend menu) { if (mainMenu != null) mainBox.Remove (mainMenu); if (menu != null) { MenuBackend m = (MenuBackend) menu; mainMenu = m.MenuBar; mainBox.PackStart (mainMenu, false, false, 0); ((Gtk.Box.BoxChild)mainBox[mainMenu]).Position = 0; } else mainMenu = null; } public void SetPadding (double left, double top, double right, double bottom) { alignment.LeftPadding = (uint) left; alignment.RightPadding = (uint) right; alignment.TopPadding = (uint) top; alignment.BottomPadding = (uint) bottom; } public void SetMinSize (Size s) { // Not required } } }
mit
C#
d4dc9773cebeeb25f3aa51e07dac7100b883581f
fix todo item
xamarin/monotouch-samples,xamarin/monotouch-samples,xamarin/monotouch-samples
ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Notitfications/MarkNotificationsReadSample.cs
ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Notitfications/MarkNotificationsReadSample.cs
using System.Collections.Generic; using System.Threading.Tasks; using UIKit; using Foundation; using CloudKit; namespace CloudKitAtlas { public class NotificationsCache { public Results Results { get; private set; } = new Results (null, alwaysShowAsList: true); public void AddNotification (CKNotification notification) { Results.Items.Add (new CKNotificationWrapper (notification)); Results.Added.Add (Results.Items.Count - 1); } public HashSet<int> AddedIndices { get { return Results.Added; } } public CKNotificationID [] NewNotificationIDs { get { var ids = new CKNotificationID [Results.Added.Count]; var i = 0; foreach (var index in Results.Added) { var notification = Results.Items [index] as CKNotification; var id = notification?.NotificationId; if (notification != null && id != null) ids [i++] = id; } return ids; } } public CKNotificationID [] NotificationIDsToBeMarkedAsRead { get; set; } = new CKNotificationID [0]; public void MarkAsRead () { var notificationIDs = NotificationIDsToBeMarkedAsRead; foreach (var notificationID in notificationIDs) { var index = Results.Items.FindIndex (result => { var notification = result as CKNotification; if (notification != null) return notification.NotificationId == notificationID; return false; }); if (index >= 0) Results.Added.Remove (index); } UIApplication.SharedApplication.ApplicationIconBadgeNumber = Results.Added.Count; } } public class MarkNotificationsReadSample : CodeSample { public NotificationsCache Cache { get; private set; } = new NotificationsCache (); public MarkNotificationsReadSample () : base (title: "CKMarkNotificationsReadOperation", className: "CKMarkNotificationsReadOperation", methodName: ".ctor(CKNotificationID[])", descriptionKey: "Notifications.MarkAsRead") { } public override Task<Results> Run () { CKNotificationID [] ids = Cache.NewNotificationIDs; var tcs = new TaskCompletionSource<Results> (); if (ids.Length > 0) { var operation = new CKMarkNotificationsReadOperation (ids); operation.Completed = (CKNotificationID [] notificationIDsMarkedRead, NSError operationError) => { if (operationError != null) { tcs.SetException (new NSErrorException (operationError)); } else { Cache.NotificationIDsToBeMarkedAsRead = notificationIDsMarkedRead; tcs.SetResult (Cache.Results); } }; operation.Start (); } else { tcs.SetResult (Cache.Results); } return tcs.Task; } } }
using System; using System.Collections.Generic; using UIKit; using Foundation; using CloudKit; using System.Threading.Tasks; namespace CloudKitAtlas { public class NotificationsCache { public Results Results { get; private set; } = new Results (null, alwaysShowAsList: true); public void AddNotification (CKNotification notification) { Results.Items.Add (new CKNotificationWrapper (notification)); Results.Added.Add (Results.Items.Count - 1); } public HashSet<int> AddedIndices { get { return Results.Added; } } public CKNotificationID [] NewNotificationIDs { get { var ids = new CKNotificationID [Results.Added.Count]; var i = 0; foreach (var index in Results.Added) { var notification = Results.Items [index] as CKNotification; var id = notification?.NotificationId; if (notification != null && id != null) ids [i++] = id; } return ids; } } public CKNotificationID [] NotificationIDsToBeMarkedAsRead { get; set; } = new CKNotificationID [0]; public void MarkAsRead () { var notificationIDs = NotificationIDsToBeMarkedAsRead; foreach (var notificationID in notificationIDs) { var index = Results.Items.FindIndex (result => { var notification = result as CKNotification; if (notification != null) return notification.NotificationId == notificationID; return false; }); if (index >= 0) Results.Added.Remove (index); } UIApplication.SharedApplication.ApplicationIconBadgeNumber = Results.Added.Count; } } public class MarkNotificationsReadSample : CodeSample { public NotificationsCache Cache { get; private set; } = new NotificationsCache (); public MarkNotificationsReadSample () : base (title: "CKMarkNotificationsReadOperation", className: "CKMarkNotificationsReadOperation", methodName: ".init(notificationIDsToMarkRead:)", // TODO: use C# name instead descriptionKey: "Notifications.MarkAsRead") { } public override Task<Results> Run () { var ids = Cache.NewNotificationIDs; var tcs = new TaskCompletionSource<Results> (); if (ids.Length > 0) { var operation = new CKMarkNotificationsReadOperation (ids); operation.Completed = (CKNotificationID [] notificationIDsMarkedRead, NSError operationError) => { if (operationError != null) { tcs.SetException (new NSErrorException (operationError)); } else { Cache.NotificationIDsToBeMarkedAsRead = notificationIDsMarkedRead; tcs.SetResult (Cache.Results); } }; operation.Start (); } else { tcs.SetResult (Cache.Results); } return tcs.Task; } } }
mit
C#
650aac06335a8dffabb4321ee62a1a498febc438
Add editor button to update build path
Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
Assets/Editor/MicrogameCollectionEditor.cs
Assets/Editor/MicrogameCollectionEditor.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } if (GUILayout.Button("Update Build Path")) { collection.updateBuildPath(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(MicrogameCollection))] public class MicrogameCollectionEditor : Editor { public override void OnInspectorGUI() { MicrogameCollection collection = (MicrogameCollection)target; if (GUILayout.Button("Update Microgames")) { collection.updateMicrogames(); EditorUtility.SetDirty(collection); } DrawDefaultInspector(); } }
mit
C#
abf7dc9c5410c44daa8777c120375cd7885d6412
fix merge issue
vmandic/dreamlet,vmandic/dreamlet,vmandic/dreamlet
dreamlet.server/dreamlet.WebService/App_Start/WebApiConfig.cs
dreamlet.server/dreamlet.WebService/App_Start/WebApiConfig.cs
using Newtonsoft.Json.Serialization; using System.Linq; using System.Web.Http; namespace dreamlet.WebService { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); var contractResolver = new DefaultContractResolver(); contractResolver.NamingStrategy = new SnakeCaseNamingStrategy(true, false); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = contractResolver; config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore; // Register DryIoc IoC manager DryIocConfig.Register(config); } } }
using Newtonsoft.Json.Serialization; using System.Linq; using System.Web.Http; namespace dreamlet.WebService { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); var contractResolver = new DefaultContractResolver(); contractResolver.NamingStrategy = new SnakeCaseNamingStrategy(true, false); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = contractResolver; config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore; // enable CORS due to client app on different origin config.EnableCors(); // Register DryIoc IoC manager DryIocConfig.Register(config); } } }
apache-2.0
C#
f1506e361c50e5104cad2d37c474076fbd584c1c
remove unused stuff
kersny/libuv-csharp,kersny/libuv-csharp
webserver.cs
webserver.cs
using System; using System.Runtime.InteropServices; using System.IO; namespace webserver { class webserver { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void uv_connection_cb(IntPtr socket, int status); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void manos_uv_read_cb(IntPtr socket, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] byte[] data); static void Main () { uv_init(); //THIS NEEDS TO BE CHANGED... size changes based on OS, we need some way to get that //152 is what it is on my mac int size = manos_uv_tcp_t_size(); IntPtr server = Marshal.AllocHGlobal(size); uv_tcp_init(server); manos_uv_tcp_bind(server, "0.0.0.0", 8080); uv_tcp_listen(server, 128, (sock, status) => { IntPtr handle = Marshal.AllocHGlobal(size); uv_tcp_init(handle); uv_accept(sock, handle); manos_uv_read_start(handle, (socket, count, data) => { Console.WriteLine(BitConverter.ToString(data, 0, count)); Console.WriteLine(System.Text.Encoding.ASCII.GetString(data, 0, count)); }); }); Console.WriteLine ("Hello World"); uv_run(); Marshal.FreeHGlobal(server); } [DllImport ("uvwrap")] public static extern void uv_init (); [DllImport ("uvwrap")] public static extern void uv_run (); [DllImport ("uvwrap")] public static extern void uv_tcp_init (IntPtr socket); [DllImport ("uvwrap")] public static extern void manos_uv_tcp_bind (IntPtr socket, string host, int port); [DllImport ("uvwrap")] public static extern void uv_tcp_listen(IntPtr socket, int backlog, uv_connection_cb callback); [DllImport ("uvwrap")] public static extern void uv_accept(IntPtr socket, IntPtr stream); [DllImport ("uvwrap")] public static extern int manos_uv_read_start(IntPtr stream, manos_uv_read_cb cb); [DllImport ("uvwrap")] public static extern int manos_uv_tcp_t_size(); } }
using System; using System.Runtime.InteropServices; using System.IO; namespace webserver { class webserver { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void uv_connection_cb(IntPtr socket, int status); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void manos_uv_read_cb(IntPtr socket, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] byte[] data); static void Main () { uv_init(); //THIS NEEDS TO BE CHANGED... size changes based on OS, we need some way to get that //152 is what it is on my mac int size = manos_uv_tcp_t_size(); IntPtr server = Marshal.AllocHGlobal(size); uv_tcp_init(server); manos_uv_tcp_bind(server, "0.0.0.0", 8080); uv_tcp_listen(server, 128, (sock, status) => { IntPtr handle = Marshal.AllocHGlobal(size); uv_tcp_init(handle); uv_accept(sock, handle); manos_uv_read_start(handle, (socket, count, data) => { Console.WriteLine(BitConverter.ToString(data, 0, count)); Console.WriteLine(System.Text.Encoding.ASCII.GetString(data, 0, count)); }); }); Console.WriteLine ("Hello World"); uv_run(); Marshal.FreeHGlobal(server); } [DllImport ("uvwrap")] public static extern void uv_init (); [DllImport ("uvwrap")] public static extern void uv_run (); [DllImport ("uvwrap")] public static extern void uv_tcp_init (IntPtr socket); [DllImport ("uvwrap")] public static extern void manos_uv_tcp_bind (IntPtr socket, string host, int port); [DllImport ("uvwrap")] public static extern void uv_tcp_listen(IntPtr socket, int backlog, uv_connection_cb callback); [DllImport ("uvwrap")] public static extern sockaddr_in uv_ip4_addr(string host, int port); [DllImport ("uvwrap")] public static extern void uv_accept(IntPtr socket, IntPtr stream); [DllImport ("uvwrap")] public static extern int manos_uv_read_start(IntPtr stream, manos_uv_read_cb cb); [DllImport ("uvwrap")] public static extern int manos_uv_tcp_t_size(); //Stolen from http://www.elitepvpers.com/forum/co2-programming/159327-advanced-winsock-c.html [StructLayout(LayoutKind.Sequential, Size=16)] public struct sockaddr_in { public const int Size = 16; public short sin_family; public ushort sin_port; public struct in_addr { public uint S_addr; public struct _S_un_b { public byte s_b1, s_b2, s_b3, s_b4; } public _S_un_b S_un_b; public struct _S_un_w { public ushort s_w1, s_w2; } public _S_un_w S_un_w; } public in_addr sin_addr; } } }
mit
C#
e5531816f8e57d52b73ab07071aba12334a2363f
Switch to informational level logging.
KevinRansom/roslyn,physhi/roslyn,mavasani/roslyn,physhi/roslyn,AmadeusW/roslyn,eriawan/roslyn,diryboy/roslyn,diryboy/roslyn,wvdd007/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,mavasani/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,sharwell/roslyn,wvdd007/roslyn,sharwell/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,dotnet/roslyn,weltkante/roslyn,weltkante/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,sharwell/roslyn
src/VisualStudio/Core/Def/Implementation/LanguageClient/InProcLanguageServer_ILspLogger.cs
src/VisualStudio/Core/Def/Implementation/LanguageClient/InProcLanguageServer_ILspLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.LogHub; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.ServiceBroker; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { internal partial class InProcLanguageServer : ILspLoggerProvider { public async Task<ILspLogger> CreateLoggerAsync(string logName, CancellationToken cancellationToken) { if (_asyncServiceProvider == null) return NoOpLspLogger.Instance; var cleaned = string.Concat(logName.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries)); var logId = new LogId(cleaned, new ServiceMoniker("Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient")); var serviceContainer = await _asyncServiceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>().ConfigureAwait(false); var service = serviceContainer.GetFullAccessServiceBroker(); var configuration = await TraceConfiguration.CreateTraceConfigurationInstanceAsync(service, cancellationToken).ConfigureAwait(false); var traceSource = await configuration.RegisterLogSourceAsync(logId, new LogHub.LoggerOptions(), cancellationToken).ConfigureAwait(false); traceSource.Switch.Level = SourceLevels.ActivityTracing | SourceLevels.Information; return new LogHubLspLogger(configuration, traceSource); } private class LogHubLspLogger : ILspLogger { private readonly TraceConfiguration _configuration; private readonly TraceSource _traceSource; public LogHubLspLogger(TraceConfiguration configuration, TraceSource traceSource) { _configuration = configuration; _traceSource = traceSource; } public void Dispose() { _traceSource.Flush(); _traceSource.Close(); _configuration.Dispose(); } public void TraceInformation(string message) => _traceSource.TraceInformation(message); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.LogHub; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.ServiceBroker; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient { internal partial class InProcLanguageServer : ILspLoggerProvider { public async Task<ILspLogger> CreateLoggerAsync(string logName, CancellationToken cancellationToken) { if (_asyncServiceProvider == null) return NoOpLspLogger.Instance; var cleaned = string.Concat(logName.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries)); var logId = new LogId(cleaned, new ServiceMoniker("Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient")); var serviceContainer = await _asyncServiceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>().ConfigureAwait(false); var service = serviceContainer.GetFullAccessServiceBroker(); var configuration = await TraceConfiguration.CreateTraceConfigurationInstanceAsync(service, cancellationToken).ConfigureAwait(false); var traceSource = await configuration.RegisterLogSourceAsync(logId, new LogHub.LoggerOptions(), cancellationToken).ConfigureAwait(false); traceSource.Switch.Level = SourceLevels.ActivityTracing | SourceLevels.Verbose; return new LogHubLspLogger(configuration, traceSource); } private class LogHubLspLogger : ILspLogger { private readonly TraceConfiguration _configuration; private readonly TraceSource _traceSource; public LogHubLspLogger(TraceConfiguration configuration, TraceSource traceSource) { _configuration = configuration; _traceSource = traceSource; } public void Dispose() { _traceSource.Flush(); _traceSource.Close(); _configuration.Dispose(); } public void TraceInformation(string message) => _traceSource.TraceInformation(message); } } }
mit
C#
5f23f4725831e8f5427775add196b8a1e322e806
use next working day if D+2 falls into weekend in spot tiles
AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud,AdaptiveConsulting/ReactiveTraderCloud
src/server/Adaptive.ReactiveTrader.Server.Pricing/MeanReversionRandomWalkPriceGenerator.cs
src/server/Adaptive.ReactiveTrader.Server.Pricing/MeanReversionRandomWalkPriceGenerator.cs
using System; using System.Diagnostics; using Adaptive.ReactiveTrader.Contract; namespace Adaptive.ReactiveTrader.Server.Pricing { public sealed class MeanReversionRandomWalkPriceGenerator : BaseWalkPriceGenerator, IPriceGenerator { private readonly decimal _halfSpreadPercentage; private readonly decimal _reversion; private readonly decimal _vol; public MeanReversionRandomWalkPriceGenerator(CurrencyPair currencyPair, decimal initial, int precision, decimal reversionCoefficient = 0.001m, decimal volatility = 5m) : base(currencyPair, initial, precision) { _reversion = reversionCoefficient; var power = (decimal)Math.Pow(10, precision); _vol = volatility * 1m / power; _halfSpreadPercentage = Random.Value.Next(2, 16) / power / _initial; } public override void UpdateWalkPrice() { var random = (decimal)Random.Value.NextNormal(); lock (_lock) { _previousMid += _reversion * (_initial - _previousMid) + random * _vol; } _priceChanges.OnNext( new SpotPriceDto { Symbol = CurrencyPair.Symbol, ValueDate = DateTime.UtcNow.AddDays(2).Date.ToWeekday(), Mid = Format(_previousMid), Ask = Format(_previousMid * (1 + _halfSpreadPercentage)), Bid = Format(_previousMid * (1 - _halfSpreadPercentage)), CreationTimestamp = Stopwatch.GetTimestamp() }); } private decimal Format(decimal price) { var power = (decimal)Math.Pow(10, _precision); var mid = (int)(price * power); return mid / power; } } }
using System; using System.Diagnostics; using Adaptive.ReactiveTrader.Contract; namespace Adaptive.ReactiveTrader.Server.Pricing { public sealed class MeanReversionRandomWalkPriceGenerator : BaseWalkPriceGenerator, IPriceGenerator { private readonly decimal _halfSpreadPercentage; private readonly decimal _reversion; private readonly decimal _vol; public MeanReversionRandomWalkPriceGenerator(CurrencyPair currencyPair, decimal initial, int precision, decimal reversionCoefficient = 0.001m, decimal volatility = 5m) : base(currencyPair, initial, precision) { _reversion = reversionCoefficient; var power = (decimal)Math.Pow(10, precision); _vol = volatility * 1m / power; _halfSpreadPercentage = Random.Value.Next(2, 16) / power / _initial; } public override void UpdateWalkPrice() { var random = (decimal)Random.Value.NextNormal(); lock (_lock) { _previousMid += _reversion * (_initial - _previousMid) + random * _vol; } _priceChanges.OnNext( new SpotPriceDto { Symbol = CurrencyPair.Symbol, ValueDate = DateTime.UtcNow.AddDays(2).Date, Mid = Format(_previousMid), Ask = Format(_previousMid * (1 + _halfSpreadPercentage)), Bid = Format(_previousMid * (1 - _halfSpreadPercentage)), CreationTimestamp = Stopwatch.GetTimestamp() }); } private decimal Format(decimal price) { var power = (decimal)Math.Pow(10, _precision); var mid = (int)(price * power); return mid / power; } } }
apache-2.0
C#
cb71bd1f97b0d17764fe8421ae0de2cb1a165e41
Make GetTabForItem throw for nonexistent items
jcmoyer/Yeena
Yeena/PathOfExile/PoEStash.cs
Yeena/PathOfExile/PoEStash.cs
// Copyright 2013 J.C. Moyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; using System.Linq; namespace Yeena.PathOfExile { class PoEStash : IReadOnlyList<PoEStashTab> { private readonly List<PoEStashTab> _tabs; public PoEStash(IEnumerable<PoEStashTab> tabs) { _tabs = new List<PoEStashTab>(tabs); } public IReadOnlyList<PoEStashTab> Tabs { get { return _tabs; } } public PoEStashTab GetTabForItem(PoEItem item) { return _tabs.First(t => t.Any(i => i == item)); } public IEnumerator<PoEStashTab> GetEnumerator() { return Tabs.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return Tabs.Count; } } public PoEStashTab this[int index] { get { return Tabs[index]; } } } }
// Copyright 2013 J.C. Moyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; using System.Linq; namespace Yeena.PathOfExile { class PoEStash : IReadOnlyList<PoEStashTab> { private readonly List<PoEStashTab> _tabs; public PoEStash(IEnumerable<PoEStashTab> tabs) { _tabs = new List<PoEStashTab>(tabs); } public IReadOnlyList<PoEStashTab> Tabs { get { return _tabs; } } public PoEStashTab GetTabForItem(PoEItem item) { return _tabs.FirstOrDefault(t => t.Any(i => i == item)); } public IEnumerator<PoEStashTab> GetEnumerator() { return Tabs.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return Tabs.Count; } } public PoEStashTab this[int index] { get { return Tabs[index]; } } } }
apache-2.0
C#
5e4717cedcf366f03c0499c64b9f05d7cc409e0c
Add square extension method to floats
dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo
DynamixelServo.Quadruped/MathExtensions.cs
DynamixelServo.Quadruped/MathExtensions.cs
using System; namespace DynamixelServo.Quadruped { static class MathExtensions { public static double RadToDegree(this double angle) { return angle * (180.0 / Math.PI); } public static float RadToDegree(this float angle) { return angle * (180f / (float)Math.PI); } public static double DegreeToRad(this double angle) { return Math.PI * angle / 180.0; } public static float DegreeToRad(this float angle) { return (float)Math.PI * angle / 180f; } public static double ToPower(this double number, double powerOf) { return Math.Pow(number, powerOf); } public static float Square(this float number) { return number * number; } } }
using System; namespace DynamixelServo.Quadruped { static class MathExtensions { public static double RadToDegree(this double angle) { return angle * (180.0 / Math.PI); } public static float RadToDegree(this float angle) { return angle * (180f / (float)Math.PI); } public static double DegreeToRad(this double angle) { return Math.PI * angle / 180.0; } public static float DegreeToRad(this float angle) { return (float)Math.PI * angle / 180f; } public static double ToPower(this double number, double powerOf) { return Math.Pow(number, powerOf); } } }
apache-2.0
C#
42eefec1cb19382bf6952f725b73bf7f36c85037
Use https by default for new servers
cwensley/JabbR.Eto,cwensley/JabbR.Eto,JabbR/JabbR.Desktop,cwensley/JabbR.Eto,JabbR/JabbR.Desktop,JabbR/JabbR.Desktop
Source/JabbR.Eto/Actions/AddServer.cs
Source/JabbR.Eto/Actions/AddServer.cs
using System; using Eto.Forms; using JabbR.Eto.Interface.Dialogs; using JabbR.Eto.Model.JabbR; using System.Diagnostics; namespace JabbR.Eto.Actions { public class AddServer : ButtonAction { public const string ActionID = "AddServer"; public bool AutoConnect { get; set; } public AddServer () { this.ID = ActionID; this.MenuText = "Add Server..."; } protected override void OnActivated (EventArgs e) { base.OnActivated (e); var server = new JabbRServer { Name = "JabbR.net", Address = "https://jabbr.net", JanrainAppName = "jabbr" }; using (var dialog = new ServerDialog(server, true, true)) { dialog.DisplayMode = DialogDisplayMode.Attached; var ret = dialog.ShowDialog (Application.Instance.MainForm); if (ret == DialogResult.Ok) { Debug.WriteLine ("Added Server, Name: {0}", server.Name); var config = JabbRApplication.Instance.Configuration; config.AddServer (server); JabbRApplication.Instance.SaveConfiguration (); if (AutoConnect) { Application.Instance.AsyncInvoke(delegate { server.Connect (); }); } } } } } }
using System; using Eto.Forms; using JabbR.Eto.Interface.Dialogs; using JabbR.Eto.Model.JabbR; using System.Diagnostics; namespace JabbR.Eto.Actions { public class AddServer : ButtonAction { public const string ActionID = "AddServer"; public bool AutoConnect { get; set; } public AddServer () { this.ID = ActionID; this.MenuText = "Add Server..."; } protected override void OnActivated (EventArgs e) { base.OnActivated (e); var server = new JabbRServer { Name = "JabbR.net", Address = "http://jabbr.net", JanrainAppName = "jabbr" }; using (var dialog = new ServerDialog(server, true, true)) { dialog.DisplayMode = DialogDisplayMode.Attached; var ret = dialog.ShowDialog (Application.Instance.MainForm); if (ret == DialogResult.Ok) { Debug.WriteLine ("Added Server, Name: {0}", server.Name); var config = JabbRApplication.Instance.Configuration; config.AddServer (server); JabbRApplication.Instance.SaveConfiguration (); if (AutoConnect) { Application.Instance.AsyncInvoke(delegate { server.Connect (); }); } } } } } }
mit
C#
7ff84385cc1257dc41c01fd1e7f0a1f69fa0282d
Fix parameter
mika-f/Sagitta
Source/Sagitta/Clients/MangaClient.cs
Source/Sagitta/Clients/MangaClient.cs
using System.Collections.Generic; using System.Threading.Tasks; using Sagitta.Extensions; using Sagitta.Models; namespace Sagitta.Clients { /// <summary> /// マンガ関連 API /// </summary> public class MangaClient : ApiClient { internal MangaClient(PixivClient pixivClient) : base(pixivClient) { } /// <summary> /// おすすめのマンガ一覧を取得します。 /// </summary> /// <param name="bookmarkIllustIds">TODO</param> /// <param name="includeRankingIllusts">ランキング上位のイラストをレスポンスに含むか</param> /// <param name="filter">フィルター (`for_ios` が有効)</param> /// <returns> /// <see cref="IllustCollection" /> /// </returns> public async Task<IllustCollection> RecommendedAsync(List<long> bookmarkIllustIds = null, bool includeRankingIllusts = false, string filter = "") { var parameters = new List<KeyValuePair<string, string>>(); if (bookmarkIllustIds != null) parameters.Add(new KeyValuePair<string, string>("bookmark_illust_ids", string.Join(",", bookmarkIllustIds))); if (includeRankingIllusts) parameters.Add(new KeyValuePair<string, string>("include_ranking_illusts", true.ToString())); if (!string.IsNullOrWhiteSpace(filter)) parameters.Add(new KeyValuePair<string, string>("filter", filter)); return await PixivClient.GetAsync<IllustCollection>("https://app-api.pixiv.net/v1/manga/recommended", parameters).Stay(); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Sagitta.Extensions; using Sagitta.Models; namespace Sagitta.Clients { /// <summary> /// マンガ関連 API /// </summary> public class MangaClient : ApiClient { internal MangaClient(PixivClient pixivClient) : base(pixivClient) { } /// <summary> /// おすすめのマンガ一覧を取得します。 /// </summary> /// <param name="bookmarkIllustIds">TODO</param> /// <param name="includeRankingIllusts">ランキング上位のイラストをレスポンスに含むか</param> /// <param name="filter">フィルター (`for_ios` が有効)</param> /// <returns> /// <see cref="IllustCollection" /> /// </returns> public async Task<IllustCollection> RecommendedAsync(List<long> bookmarkIllustIds, bool includeRankingIllusts = false, string filter = "") { var parameters = new List<KeyValuePair<string, string>>(); if (bookmarkIllustIds != null) parameters.Add(new KeyValuePair<string, string>("bookmark_illust_ids", string.Join(",", bookmarkIllustIds))); if (includeRankingIllusts) parameters.Add(new KeyValuePair<string, string>("include_ranking_illusts", true.ToString())); if (!string.IsNullOrWhiteSpace(filter)) parameters.Add(new KeyValuePair<string, string>("filter", filter)); return await PixivClient.GetAsync<IllustCollection>("https://app-api.pixiv.net/v1/manga/recommended", parameters).Stay(); } } }
mit
C#
0a6b79e24de002b28d657d8773fa37fd809bfe2c
Fix error after merge
Sitecore/Sitecore-Instance-Manager
src/SIM.Tool.Windows/UserControls/Install/ParametersEditor/Install9ParametersEditor.xaml.cs
src/SIM.Tool.Windows/UserControls/Install/ParametersEditor/Install9ParametersEditor.xaml.cs
using SIM.Sitecore9Installer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SIM.Tool.Windows.UserControls.Install.ParametersEditor { /// <summary> /// Interaction logic for Install9ParametersEditor.xaml /// </summary> public partial class Install9ParametersEditor : Window { public Install9ParametersEditor() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var tasker = this.DataContext as Tasker; List<TasksModel> model = new List<TasksModel>(); model.Add(new TasksModel("Global", tasker.GlobalParams)); foreach (PowerShellTask task in tasker.Tasks.Where(t=>t.ShouldRun)) { if (!tasker.UnInstall || (tasker.UnInstall && task.SupportsUninstall())) { model.Add(new TasksModel(task.Name, task.LocalParams)); } } this.InstallationParameters.DataContext = model; this.InstallationParameters.SelectedIndex = 0; } private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { ScrollViewer scrollviewer = sender as ScrollViewer; if (e.Delta > 0) scrollviewer.LineLeft(); else scrollviewer.LineRight(); e.Handled = true; } private class TasksModel { public TasksModel(string Name, List<InstallParam> Params) { this.Name = Name; this.Params = Params; } public string Name { get; } public List<InstallParam> Params { get; } } private void Btn_Close_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
using SIM.Sitecore9Installer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SIM.Tool.Windows.UserControls.Install.ParametersEditor { /// <summary> /// Interaction logic for Install9ParametersEditor.xaml /// </summary> public partial class Install9ParametersEditor : Window { public Install9ParametersEditor() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var tasker = this.DataContext as Tasker; List<TasksModel> model = new List<TasksModel>(); model.Add(new TasksModel("Global", args.Tasker.GlobalParams)); foreach (PowerShellTask task in args.Tasker.Tasks.Where(t=>t.ShouldRun)) { if (!tasker.UnInstall || (tasker.UnInstall && task.SupportsUninstall())) { model.Add(new TasksModel(task.Name, task.LocalParams)); } } this.InstallationParameters.DataContext = model; this.InstallationParameters.SelectedIndex = 0; } private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { ScrollViewer scrollviewer = sender as ScrollViewer; if (e.Delta > 0) scrollviewer.LineLeft(); else scrollviewer.LineRight(); e.Handled = true; } private class TasksModel { public TasksModel(string Name, List<InstallParam> Params) { this.Name = Name; this.Params = Params; } public string Name { get; } public List<InstallParam> Params { get; } } private void Btn_Close_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
mit
C#
9585deffa920fb8acdb697e5068aefa820affa83
Add regions
bartlomiejwolk/DestroyAfterTime
DestroyAfterTime.cs
DestroyAfterTime.cs
using UnityEngine; using System.Collections; namespace DestroyAfterTimeEx { public class DestroyAfterTime : MonoBehaviour { #region INSPECTOR FIELDS /// GO to be destroyed. [SerializeField] private GameObject target; /// Destroy delay. [SerializeField] private float delay; #endregion #region PROPERTIES /// GO to be destroyed. public GameObject Target { get { return target; } set { target = value; } } /// Destroy delay. public float Delay { get { return delay; } set { delay = value; } } #endregion #region UNITY MESSAGES // todo extract private void Start () { if (Target) { Destroy(Target, Delay); } else { Utilities.MissingReference(this, "Target"); } } #endregion #region METHODS public void Now() { Destroy(Target); } #endregion } }
using UnityEngine; using System.Collections; namespace DestroyAfterTimeEx { public class DestroyAfterTime : MonoBehaviour { /// GO to be destroyed. [SerializeField] private GameObject target; /// Destroy delay. [SerializeField] private float delay; /// GO to be destroyed. public GameObject Target { get { return target; } set { target = value; } } /// Destroy delay. public float Delay { get { return delay; } set { delay = value; } } // todo extract private void Start () { if (Target) { Destroy(Target, Delay); } else { Utilities.MissingReference(this, "Target"); } } public void Now() { Destroy(Target); } } }
mit
C#
44ea83b2907e1dd3e97c3beca0b7ff9fb1ce4535
Add method 'DetalheCurso'
fmassaretto/formacao-talentos,fmassaretto/formacao-talentos,fmassaretto/formacao-talentos
Fatec.Treinamento.Data/Repositories/CursoRepository.cs
Fatec.Treinamento.Data/Repositories/CursoRepository.cs
using Fatec.Treinamento.Data.Repositories.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Fatec.Treinamento.Model.DTO; using Fatec.Treinamento.Data.Repositories.Base; using Dapper; using Fatec.Treinamento.Model; namespace Fatec.Treinamento.Data.Repositories { public class CursoRepository : RepositoryBase, ICursoRepository { public IEnumerable<DetalhesCurso> ListarCursosPorNome(string nome) { return Connection.Query<DetalhesCurso>( @"SELECT c.Id, c.Nome, a.Nome as Assunto, u.Nome as Autor, c.DataCriacao, c.Classificacao FROM curso c inner join assunto a on c.IdAssunto = a.id inner join usuario u on c.IdAutor = u.Id WHERE c.nome like @Nome ORDER BY c.Nome", param: new { Nome = "%" + nome + "%" } ).ToList(); } public IEnumerable<DetalhesCurso> ListarTodosCursos() { return Connection.Query<DetalhesCurso>( @"SELECT c.Id, c.Nome, a.Nome as Assunto, u.Nome as Autor, c.DataCriacao, c.Classificacao FROM curso c inner join assunto a on c.IdAssunto = a.id inner join usuario u on c.IdAutor = u.Id ORDER BY c.Nome" ).ToList(); } public IEnumerable<Detalhe> DetalheCurso(int id) { return Connection.Query<Detalhe>( @"SELECT c.Id, c.Nome, a.Nome as Assunto, u.Nome as Autor, c.DataCriacao, c.Classificacao, cd.Descricao FROM curso c inner join assunto a on c.IdAssunto = a.id inner join usuario u on c.IdAutor = u.Id inner join curso_descricao cd on cd.IdCurso = c.Id WHERE c.Id = @Id", param: new { Id = id } ).ToList(); } } }
using Fatec.Treinamento.Data.Repositories.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Fatec.Treinamento.Model.DTO; using Fatec.Treinamento.Data.Repositories.Base; using Dapper; namespace Fatec.Treinamento.Data.Repositories { public class CursoRepository : RepositoryBase, ICursoRepository { public IEnumerable<DetalhesCurso> ListarCursosPorNome(string nome) { return Connection.Query<DetalhesCurso>( @"SELECT c.Id, c.Nome, a.Nome as Assunto, u.Nome as Autor, c.DataCriacao, c.Classificacao FROM curso c inner join assunto a on c.IdAssunto = a.id inner join usuario u on c.IdAutor = u.Id WHERE c.nome like @Nome ORDER BY c.Nome", param: new { Nome = "%" + nome + "%" } ).ToList(); } } }
apache-2.0
C#
f6f55aea5f11c8574f5698c6501e1e95be8a6f75
Add Cards.BaconPoolMinions
HearthSim/HearthDb
HearthDb/Cards.cs
HearthDb/Cards.cs
#region using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Serialization; using HearthDb.CardDefs; using HearthDb.Enums; #endregion namespace HearthDb { public static class Cards { public static readonly Dictionary<string, Card> All = new Dictionary<string, Card>(); public static readonly Dictionary<string, Card> Collectible = new Dictionary<string, Card>(); public static readonly Dictionary<string, Card> BaconPoolMinions = new Dictionary<string, Card>(); static Cards() { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("HearthDb.CardDefs.xml"); if(stream == null) return; using(TextReader tr = new StreamReader(stream)) { var xml = new XmlSerializer(typeof(CardDefs.CardDefs)); var cardDefs = (CardDefs.CardDefs)xml.Deserialize(tr); foreach(var entity in cardDefs.Entites) { // For some reason Deflect-o-bot is missing divine shield if (IsDeflectOBot(entity) && !entity.Tags.Any(x => x.EnumId == (int)GameTag.DIVINE_SHIELD)) entity.Tags.Add(new Tag { EnumId = (int)GameTag.DIVINE_SHIELD, Value = 1 }); var card = new Card(entity); All.Add(entity.CardId, card); if(card.Collectible && (card.Type != CardType.HERO || card.Set != CardSet.CORE && card.Set != CardSet.HERO_SKINS)) Collectible.Add(entity.CardId, card); if(card.IsBaconPoolMinion) BaconPoolMinions.Add(entity.CardId, card); } } } public static Card GetFromName(string name, Locale lang, bool collectible = true) => (collectible ? Collectible : All).Values.FirstOrDefault(x => x.GetLocName(lang)?.Equals(name, StringComparison.InvariantCultureIgnoreCase) ?? false); public static Card GetFromDbfId(int dbfId, bool collectibe = true) => (collectibe ? Collectible : All).Values.FirstOrDefault(x => x.DbfId == dbfId); private static bool IsDeflectOBot(Entity entity) => entity.CardId == CardIds.NonCollectible.Neutral.DeflectOBot || entity.CardId == CardIds.NonCollectible.Neutral.DeflectOBotTavernBrawl; } }
#region using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Serialization; using HearthDb.CardDefs; using HearthDb.Enums; #endregion namespace HearthDb { public static class Cards { public static readonly Dictionary<string, Card> All = new Dictionary<string, Card>(); public static readonly Dictionary<string, Card> Collectible = new Dictionary<string, Card>(); static Cards() { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("HearthDb.CardDefs.xml"); if(stream == null) return; using(TextReader tr = new StreamReader(stream)) { var xml = new XmlSerializer(typeof(CardDefs.CardDefs)); var cardDefs = (CardDefs.CardDefs)xml.Deserialize(tr); foreach(var entity in cardDefs.Entites) { // For some reason Deflect-o-bot is missing divine shield if (IsDeflectOBot(entity) && !entity.Tags.Any(x => x.EnumId == (int)GameTag.DIVINE_SHIELD)) entity.Tags.Add(new Tag { EnumId = (int)GameTag.DIVINE_SHIELD, Value = 1 }); var card = new Card(entity); All.Add(entity.CardId, card); if(card.Collectible && (card.Type != CardType.HERO || card.Set != CardSet.CORE && card.Set != CardSet.HERO_SKINS)) Collectible.Add(entity.CardId, card); } } } public static Card GetFromName(string name, Locale lang, bool collectible = true) => (collectible ? Collectible : All).Values.FirstOrDefault(x => x.GetLocName(lang)?.Equals(name, StringComparison.InvariantCultureIgnoreCase) ?? false); public static Card GetFromDbfId(int dbfId, bool collectibe = true) => (collectibe ? Collectible : All).Values.FirstOrDefault(x => x.DbfId == dbfId); private static bool IsDeflectOBot(Entity entity) => entity.CardId == CardIds.NonCollectible.Neutral.DeflectOBot || entity.CardId == CardIds.NonCollectible.Neutral.DeflectOBotTavernBrawl; } }
mit
C#
262872030ccabba8fb299414a6a0295270efa7b6
Fix the while(true) loop
TeamLabyrinth4/Labyrinth-4
Labyrinth-4/Game.cs
Labyrinth-4/Game.cs
namespace Labyrinth { using System; using Labyrinth.Renderer; using Labyrinth.Users; public sealed class Game { private static volatile Game gameInstance; private IRenderer renderer; private IPlayer player; private LabyrinthProcesor processor; private IScoreBoardObserver scoreBoardHandler; private string input; private static object syncLock = new object(); private Game(IPlayer player, IRenderer renderer, IScoreBoardObserver scoreboard, LabyrinthProcesor processor) { this.renderer = renderer; this.player = player; this.scoreBoardHandler = scoreboard; this.processor = processor; } public static Game Instance(IPlayer player, IRenderer renderer, IScoreBoardObserver scoreboard, LabyrinthProcesor processor) { if (gameInstance == null) { lock (syncLock) { if (gameInstance == null) { gameInstance = new Game(player, renderer, scoreboard, processor); } } } return gameInstance; } public void GameRun() { while (true) { this.renderer.ShowLabyrinth(this.processor.Matrix, this.player); this.processor.ShowInputMessage(); this.input = this.renderer.AddInput(); this.processor.HandleInput(input); } } } }
namespace Labyrinth { using System; using Labyrinth.Renderer; using Labyrinth.Users; public sealed class Game { private static volatile Game gameInstance; private IRenderer renderer; private IPlayer player; private LabyrinthProcesor processor; private IScoreBoardObserver scoreBoardHandler; private static object syncLock = new object(); private Game(IPlayer player, IRenderer renderer, IScoreBoardObserver scoreboard, LabyrinthProcesor processor) { this.renderer = renderer; this.player = player; this.scoreBoardHandler = scoreboard; this.processor = processor; } public static Game Instance(IPlayer player, IRenderer renderer, IScoreBoardObserver scoreboard, LabyrinthProcesor processor) { if (gameInstance == null) { lock (syncLock) { if (gameInstance == null) { gameInstance = new Game(player, renderer, scoreboard, processor); } } } return gameInstance; } public void GameRun() { while (true) { this.renderer.ShowLabyrinth(this.processor.Matrix, this.player); this.processor.ShowInputMessage(); string input; input = this.renderer.AddInput(); this.processor.HandleInput(input); } } } }
mit
C#
5d8892ed0d0ea3a5135f88dd3518f740dac2a5d8
Remove sticky notes
croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/website-application,croquet-australia/croquet-australia-website
source/CroquetAustralia.Website/Layouts/Shared/Sidebar.cshtml
source/CroquetAustralia.Website/Layouts/Shared/Sidebar.cshtml
@* sticky note example <div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> came into effect 3 April, 2017 </p> </div> </div> </div> *@
<div class="sticky-notes"> <div class="sticky-note"> <i class="pin"></i> <div class="content green"> <h1> GC Handicapping System </h1> <p> New <a href="/disciplines/golf-croquet/resources">GC Handicapping System</a> came into effect 3 April, 2017 </p> </div> </div> </div>
mit
C#
7e395f10dae600b0d474dba4ff06153c619021a2
Update Back
IanEarnest/Unity-GUI
Assets/Back.cs
Assets/Back.cs
using UnityEngine; using System; // system is only used on standalone. using System.Collections; public class Back : MonoBehaviour { Rect backRect = new Rect(Screen.width-70, Screen.height-30, 70, 30); Rect backRect2 = new Rect(Screen.width-70, Screen.height-60, 70, 30); public GameObject welcomeScript; static bool isActive; void Start(){ welcomeScript = new GameObject("Script1"); welcomeScript.AddComponent ("Welcome"); welcomeScript.SetActive (isActive); } void OnGUI(){ if(GUI.Button(backRect, "Exit level")){ Application.LoadLevel("Welcome"); } if(GUI.Button(backRect2, "Show menu")){ isActive = !isActive; welcomeScript.SetActive (isActive); } } }
using UnityEngine; using System; // system is only used on standalone. using System.Collections; public class Back : MonoBehaviour { Rect backRect = new Rect(Screen.width-70, Screen.height-30, 70, 30); Rect backRect2 = new Rect(Screen.width-70, Screen.height-60, 70, 30); public GameObject welcomeScript; static bool isActive; void Start(){ welcomeScript = new GameObject("Script1"); welcomeScript.AddComponent ("Welcome"); welcomeScript.SetActive (isActive); } void OnGUI(){ if(GUI.Button(backRect, "Back")){ Application.LoadLevel("Welcome"); } if(GUI.Button(backRect2, "Levels")){ isActive = !isActive; welcomeScript.SetActive (isActive); } } }
mit
C#
dd05cf3104a91a103a672d7e12f82858a8b03ed1
update database name
WebmarksApp/webmarks.nancy,WebmarksApp/webmarks.nancy,WebmarksApp/webmarks.nancy
webmarks.nancy/Bootstrapper.cs
webmarks.nancy/Bootstrapper.cs
using MongoDB.Driver; using Nancy; using Nancy.Conventions; using Nancy.TinyIoc; using System; using System.Configuration; using webmarks.nancy.Models; namespace webmarks.nancy { public class Bootstrapper : DefaultNancyBootstrapper { protected override void ConfigureConventions(NancyConventions nancyConventions) { base.ConfigureConventions(nancyConventions); Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/", @"Content")); } protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); //var connString = "mongodb://localhost:27017"; var connString = Environment.GetEnvironmentVariable("MONGOLAB_URI"); if(connString == null) { connString = ConfigurationManager.AppSettings.Get("MONGOLAB_URI"); } //var databaseName = "speakersdb"; var databaseName = "appharbor_pq17xkjp"; var mongoClient = new MongoClient(connString); //MongoServer server = mongoClient.GetServer(); var database = mongoClient.GetDatabase(databaseName); var collection = database.GetCollection<Speaker>("speakers"); container.Register(database); container.Register(collection); } } }
using MongoDB.Driver; using Nancy; using Nancy.Conventions; using Nancy.TinyIoc; using System; using System.Configuration; using webmarks.nancy.Models; namespace webmarks.nancy { public class Bootstrapper : DefaultNancyBootstrapper { protected override void ConfigureConventions(NancyConventions nancyConventions) { base.ConfigureConventions(nancyConventions); Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("/", @"Content")); } protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); //var connString = "mongodb://localhost:27017"; var connString = Environment.GetEnvironmentVariable("MONGOLAB_URI"); if(connString == null) { connString = ConfigurationManager.AppSettings.Get("MONGOLAB_URI"); } var databaseName = "speakersdb"; var mongoClient = new MongoClient(connString); //MongoServer server = mongoClient.GetServer(); var database = mongoClient.GetDatabase(databaseName); var collection = database.GetCollection<Speaker>("speakers"); container.Register(database); container.Register(collection); } } }
mit
C#
10fbc56b1cb42bd16baffe77a8873eb551103467
update formatting
designsbyjuan/UnityLib
LookDownCanvas.cs
LookDownCanvas.cs
using UnityEngine; using UnityEngine.EventSystems; using System.Collections; using VRStandardAssets.Utils; public class LookDownCanvas : MonoBehaviour { private CanvasGroup canvasGroup; private UIFader uiFader; private CardboardMain main; public float UIDistance = 300f; public float UIHeight = -400f; public float UIRotation = 65f; // Use this for initialization void Start () { uiFader = GetComponent<UIFader>(); canvasGroup = GetComponent<CanvasGroup>(); main = FindObjectOfType<CardboardMain>(); } // Update is called once per frame void Update() { // checks if canvas should follow player StartCoroutine(FollowPlayer()); } IEnumerator FollowPlayer() { // check if lookdowncanvas is visible if (canvasGroup.alpha <= 0) // canvas is not visible, so it should follow the player { Quaternion offsetRot = Quaternion.AngleAxis(UIRotation, Vector3.right); Quaternion playerLookRot = Quaternion.LookRotation(main.ProjectedVector(), Vector3.up); // set canvas to player look rotation transform.rotation = playerLookRot * offsetRot; // set canvas to player position transform.position = main.transform.position; // set distance from player transform.position += main.ProjectedVector() * UIDistance; // set height from ground transform.position += Vector3.up * UIHeight; } yield return null; } public void ShowCanvas() { StartCoroutine(uiFader.FadeIn()); canvasGroup.interactable = true; } public void HideCanvas() { StartCoroutine(uiFader.FadeOut()); canvasGroup.interactable = false; } }
using UnityEngine; using UnityEngine.EventSystems; using System.Collections; using VRStandardAssets.Utils; public class LookDownCanvas : MonoBehaviour { private CanvasGroup canvasGroup; private UIFader uiFader; private CardboardMain main; public float UIDistance = 300f; public float UIHeight = -400f; public float UIRotation = 65f; // Use this for initialization void Start () { uiFader = GetComponent<UIFader>(); canvasGroup = GetComponent<CanvasGroup>(); main = FindObjectOfType<CardboardMain>(); } // Update is called once per frame void Update() { // checks if canvas should follow player StartCoroutine(FollowPlayer()); } IEnumerator FollowPlayer() { // check if lookdowncanvas is visible if (canvasGroup.alpha <= 0) // canvas is not visible, so it should follow the player { Quaternion offsetRot = Quaternion.AngleAxis(UIRotation, Vector3.right); Quaternion playerLookRot = Quaternion.LookRotation(main.ProjectedVector(), Vector3.up); // set canvas to player look rotation transform.rotation = playerLookRot * offsetRot; // set canvas to player position transform.position = main.transform.position; // set distance from player transform.position += main.ProjectedVector() * UIDistance; // set height from ground transform.position += Vector3.up * UIHeight; } yield return null; } public void ShowCanvas() { StartCoroutine(uiFader.FadeIn()); canvasGroup.interactable = true; } public void HideCanvas() { StartCoroutine(uiFader.FadeOut()); canvasGroup.interactable = false; } }
mit
C#
bd7531ebc7f6bd0cb1ba4658528adf4e929554f5
add hint on gui for performance_test
thing-nacho/slua,ChinaLongGanHu/slua,thing-nacho/slua,takaaptech/slua,dayongxie/slua,angeldnd/slua,DebugClub/slua,yongkangchen/slua,yongkangchen/slua,dayongxie/slua,wang1986one/slua,lingkeyang/slua,lingkeyang/slua,soulgame/slua,haolly/slua_source_note,zenkj/slua,Roland0511/slua,houxuanfelix/slua,thing-nacho/slua,mr-kelly/slua,zhaog/slua,luzexi/slua-3rd-lib,Salada/slua,yaukeywang/slua,haolly/slua_source_note,wland/slua,mr-kelly/slua,mr-kelly/slua,luzexi/slua-3rd,thing-nacho/slua,thing-nacho/slua,yaukeywang/slua,DebugClub/slua,hlouis/slua,zhaoluxyz/slua,pangweiwei/slua,hlouis/slua,chiuan/slua,Roland0511/slua,shenxiyou/slua,shrimpz/slua,soulgame/slua,leonardave/slua,zhukunqian/slua-1,XingHong/slua,yaukeywang/slua,XingHong/slua,luzexi/slua-3rd,haolly/slua_source_note,chiuan/slua,LacusCon/slua,LacusCon/slua,yongkangchen/slua,luzexi/slua-3rd,jiangzhhhh/slua,jiangzhhhh/slua,moto2002/slua,moto2002/slua,Roland0511/slua,zhukunqian/slua-1,Roland0511/slua,haolly/slua_source_note,yaukeywang/slua,chiuan/slua,pangweiwei/slua,chiuan/slua,LacusCon/slua,dongxie/slua,luzexi/slua-3rd-lib,jiangzhhhh/slua,luzexi/slua-3rd,yaukeywang/slua-old,zhaog/slua,zhukunqian/slua-1,soulgame/slua,chiuan/slua,lyntel/slua,DebugClub/slua,luzexi/slua-3rd-lib,zenkj/slua,pangweiwei/slua,Salada/slua,pangweiwei/slua,angeldnd/slua,yaukeywang/slua-old,mr-kelly/slua,lingkeyang/slua,DebugClub/slua,luzexi/slua-3rd,pangweiwei/slua,littleboss/slua,yaukeywang/slua,thing-nacho/slua,chiuan/slua,luzexi/slua-3rd-lib,jiangzhhhh/slua,leonardave/slua,takaaptech/slua,dongxie/slua,Salada/slua,shrimpz/slua,lingkeyang/slua,zhaoluxyz/slua,angeldnd/slua,wland/slua,shenxiyou/slua,zhukunqian/slua-1,Salada/slua,DebugClub/slua,mr-kelly/slua,angeldnd/slua,lyntel/slua,Roland0511/slua,LacusCon/slua,jiangzhhhh/slua,yjpark/slua,soulgame/slua,houxuanfelix/slua,LacusCon/slua,luzexi/slua-3rd-lib,angeldnd/slua,soulgame/slua,yaukeywang/slua,soulgame/slua,dayongxie/slua,haolly/slua_source_note,Roland0511/slua,dayongxie/slua,slb1988/slua,slb1988/slua,wang1986one/slua,luzexi/slua-3rd-lib,zhukunqian/slua-1,mr-kelly/slua,LacusCon/slua,Salada/slua,lingkeyang/slua,DebugClub/slua,yongkangchen/slua,haolly/slua_source_note,yongkangchen/slua,Salada/slua,angeldnd/slua,ChinaLongGanHu/slua,jiangzhhhh/slua,dayongxie/slua,littleboss/slua,luzexi/slua-3rd,yjpark/slua,lingkeyang/slua
Assets/example/Perf.cs
Assets/example/Perf.cs
using UnityEngine; using System.Collections; using SLua; public class Perf : MonoBehaviour { LuaSvr l; // Use this for initialization void Start () { l = new LuaSvr("perf"); Application.RegisterLogCallback(this.log); } string logText=""; void log(string cond,string trace,LogType lt) { logText+=cond; logText+="\n"; } void OnGUI() { if (GUI.Button(new Rect(10, 10, 120, 50), "Test1")) { logText=""; l.luaState.getFunction("test1").call(); } if (GUI.Button(new Rect(10, 100, 120, 50), "Test2")) { logText=""; l.luaState.getFunction("test2").call(); } if (GUI.Button(new Rect(10, 200, 120, 50), "Test3")) { logText=""; l.luaState.getFunction("test3").call(); } if (GUI.Button(new Rect(10, 300, 120, 50), "Test4")) { logText=""; l.luaState.getFunction("test4").call(); } if (GUI.Button(new Rect(200, 10, 120, 50), "Test5")) { logText=""; l.luaState.getFunction("test5").call(); } if (GUI.Button(new Rect(10, 400, 300, 50), "Click here for detail(in Chinese)")) { Application.OpenURL("http://www.sineysoft.com/post/164"); } GUI.Label(new Rect(200,200,300,50),logText); } }
using UnityEngine; using System.Collections; using SLua; public class Perf : MonoBehaviour { LuaSvr l; // Use this for initialization void Start () { l = new LuaSvr("perf"); } void OnGUI() { if (GUI.Button(new Rect(10, 10, 120, 50), "Test1")) { l.luaState.getFunction("test1").call(); } if (GUI.Button(new Rect(10, 100, 120, 50), "Test2")) { l.luaState.getFunction("test2").call(); } if (GUI.Button(new Rect(10, 200, 120, 50), "Test3")) { l.luaState.getFunction("test3").call(); } if (GUI.Button(new Rect(10, 300, 120, 50), "Test4")) { l.luaState.getFunction("test4").call(); } if (GUI.Button(new Rect(200, 10, 120, 50), "Test5")) { l.luaState.getFunction("test5").call(); } if (GUI.Button(new Rect(10, 400, 300, 50), "Click here for detail(in Chinese)")) { Application.OpenURL("http://www.sineysoft.com/post/164"); } } }
mit
C#
718eb3961d2a11ad27eb3cab0f842ec50b5c4017
Fix line endings
alexmaris/Dosnic
Dosnic/Crypto.cs
Dosnic/Crypto.cs
using System; using System.IO; using System.Security.Cryptography; using System.Text; using NetJ = NetJSON.NetJSON; namespace Dosnic { public class Crypto<T> : IDisposable { public string Key { get; protected internal set; } public string IV { get; protected internal set; } public SymmetricAlgorithm SymetricAlgo { get; protected internal set; } public string Encrypt(object originalObject) { if (Key == null || IV == null) throw new NullReferenceException("Key and IV must be non-null"); byte[] originalStrAsBytes = Encoding.Default.GetBytes(NetJ.Serialize(originalObject)); using (MemoryStream memStream = new MemoryStream(originalStrAsBytes.Length)) using (ICryptoTransform rdTranasform = SymetricAlgo.CreateEncryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV))) using (CryptoStream cryptoStream = new CryptoStream(memStream, rdTranasform, CryptoStreamMode.Write)) { cryptoStream.Write(originalStrAsBytes, 0, originalStrAsBytes.Length); cryptoStream.FlushFinalBlock(); return Convert.ToBase64String(memStream.ToArray()); } } public T Decrypt(string encryptedObject) { if (Key == null || IV == null) throw new NullReferenceException("Key and IV must be non-null"); byte[] encryptedObjectAsBytes = Convert.FromBase64String(encryptedObject); using (MemoryStream memStream = new MemoryStream(encryptedObjectAsBytes)) using (ICryptoTransform rdTranasform = SymetricAlgo.CreateDecryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV))) using (CryptoStream cryptoStream = new CryptoStream(memStream, rdTranasform, CryptoStreamMode.Read)) using (StreamReader sr = new StreamReader(cryptoStream, true)) { return NetJ.Deserialize<T>(sr.ReadToEnd()); } } public void Dispose() { if (SymetricAlgo != null) SymetricAlgo.Clear(); } } }
using System; using System.IO; using System.Security.Cryptography; using System.Text; using NetJ = NetJSON.NetJSON; namespace Dosnic { public class Crypto<T> : IDisposable { public string Key { get; protected internal set; } public string IV { get; protected internal set; } public SymmetricAlgorithm SymetricAlgo { get; protected internal set; } public string Encrypt(object originalObject) { if (Key == null || IV == null) throw new NullReferenceException("Key and IV must be non-null"); byte[] originalStrAsBytes = Encoding.Default.GetBytes(NetJ.Serialize(originalObject)); using (MemoryStream memStream = new MemoryStream(originalStrAsBytes.Length)) using (ICryptoTransform rdTranasform = SymetricAlgo.CreateEncryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV))) using (CryptoStream cryptoStream = new CryptoStream(memStream, rdTranasform, CryptoStreamMode.Write)) { cryptoStream.Write(originalStrAsBytes, 0, originalStrAsBytes.Length); cryptoStream.FlushFinalBlock(); return Convert.ToBase64String(memStream.ToArray()); } } public T Decrypt(string encryptedObject) { if (Key == null || IV == null) throw new NullReferenceException("Key and IV must be non-null"); byte[] encryptedObjectAsBytes = Convert.FromBase64String(encryptedObject); using (MemoryStream memStream = new MemoryStream(encryptedObjectAsBytes)) using (ICryptoTransform rdTranasform = SymetricAlgo.CreateDecryptor(Convert.FromBase64String(Key), Convert.FromBase64String(IV))) using (CryptoStream cryptoStream = new CryptoStream(memStream, rdTranasform, CryptoStreamMode.Read)) using (StreamReader sr = new StreamReader(cryptoStream, true)) { return NetJ.Deserialize<T>(sr.ReadToEnd()); } } public void Dispose() { if (SymetricAlgo != null) SymetricAlgo.Clear(); } } }
mit
C#
0e392a90244336f4276b35a2d00a2a331e41e476
remove zero check
TakeAsh/cs-TakeAshUtility
TakeAshUtility/Base64Converter.cs
TakeAshUtility/Base64Converter.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace TakeAshUtility { public static class Base64Converter { public static string ToBase64String<T>(this T obj) where T : struct { var size = Marshal.SizeOf(obj); var arr = new byte[size]; var ptr = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(obj, ptr, true); Marshal.Copy(ptr, arr, 0, size); return Convert.ToBase64String(arr); } catch (Exception ex) { Debug.Print(ex.GetAllMessages()); return null; } finally { Marshal.FreeHGlobal(ptr); } } public static T FromBase64String<T>(string text) where T : struct { if (String.IsNullOrEmpty(text)) { return default(T); } var size = Marshal.SizeOf(typeof(T)); var arr = Convert.FromBase64String(text); var ptr = Marshal.AllocHGlobal(Math.Max(size, arr.Length)); try { Marshal.Copy(arr, 0, ptr, size); return (T)Marshal.PtrToStructure(ptr, typeof(T)); } catch (Exception ex) { Debug.Print(ex.GetAllMessages()); return default(T); } finally { Marshal.FreeHGlobal(ptr); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace TakeAshUtility { public static class Base64Converter { public static string ToBase64String<T>(this T obj) where T : struct { var size = Marshal.SizeOf(obj); var arr = new byte[size]; var ptr = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(obj, ptr, true); Marshal.Copy(ptr, arr, 0, size); return Convert.ToBase64String(arr); } catch (Exception ex) { Debug.Print(ex.GetAllMessages()); return null; } finally { if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); } } } public static T FromBase64String<T>(string text) where T : struct { if (String.IsNullOrEmpty(text)) { return default(T); } var size = Marshal.SizeOf(typeof(T)); var arr = Convert.FromBase64String(text); var ptr = Marshal.AllocHGlobal(Math.Max(size, arr.Length)); try { Marshal.Copy(arr, 0, ptr, size); return (T)Marshal.PtrToStructure(ptr, typeof(T)); } catch (Exception ex) { Debug.Print(ex.GetAllMessages()); return default(T); } finally { if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); } } } } }
mit
C#
7a99cfa2e9297ff9e6294f8c257714ef6d1a12c3
Fix instance reference test.
mavasani/roslyn,jmarolf/roslyn,tmeschter/roslyn,heejaechang/roslyn,Giftednewt/roslyn,diryboy/roslyn,pdelvo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,dotnet/roslyn,bartdesmet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bkoelman/roslyn,khyperia/roslyn,mattscheffer/roslyn,tannergooding/roslyn,tvand7093/roslyn,MattWindsor91/roslyn,swaroop-sridhar/roslyn,nguerrera/roslyn,jkotas/roslyn,xasx/roslyn,MichalStrehovsky/roslyn,panopticoncentral/roslyn,jkotas/roslyn,abock/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn,tvand7093/roslyn,ErikSchierboom/roslyn,genlu/roslyn,srivatsn/roslyn,jmarolf/roslyn,Hosch250/roslyn,aelij/roslyn,Hosch250/roslyn,pdelvo/roslyn,MattWindsor91/roslyn,shyamnamboodiripad/roslyn,orthoxerox/roslyn,jcouv/roslyn,brettfo/roslyn,bartdesmet/roslyn,jamesqo/roslyn,dpoeschl/roslyn,jcouv/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,dotnet/roslyn,OmarTawfik/roslyn,genlu/roslyn,mattscheffer/roslyn,AmadeusW/roslyn,MattWindsor91/roslyn,CaptainHayashi/roslyn,AmadeusW/roslyn,davkean/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,sharwell/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,tvand7093/roslyn,ErikSchierboom/roslyn,khyperia/roslyn,stephentoub/roslyn,abock/roslyn,AmadeusW/roslyn,agocke/roslyn,KevinRansom/roslyn,jmarolf/roslyn,lorcanmooney/roslyn,weltkante/roslyn,gafter/roslyn,Giftednewt/roslyn,paulvanbrenk/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,agocke/roslyn,CyrusNajmabadi/roslyn,dpoeschl/roslyn,agocke/roslyn,diryboy/roslyn,eriawan/roslyn,tannergooding/roslyn,dpoeschl/roslyn,srivatsn/roslyn,sharwell/roslyn,jamesqo/roslyn,mgoertz-msft/roslyn,orthoxerox/roslyn,OmarTawfik/roslyn,mmitche/roslyn,xasx/roslyn,CyrusNajmabadi/roslyn,OmarTawfik/roslyn,gafter/roslyn,CaptainHayashi/roslyn,KevinRansom/roslyn,jcouv/roslyn,pdelvo/roslyn,eriawan/roslyn,lorcanmooney/roslyn,cston/roslyn,weltkante/roslyn,abock/roslyn,reaction1989/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,mmitche/roslyn,tmeschter/roslyn,Giftednewt/roslyn,nguerrera/roslyn,jamesqo/roslyn,physhi/roslyn,MichalStrehovsky/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,aelij/roslyn,sharwell/roslyn,diryboy/roslyn,gafter/roslyn,tmeschter/roslyn,lorcanmooney/roslyn,paulvanbrenk/roslyn,wvdd007/roslyn,DustinCampbell/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,MattWindsor91/roslyn,physhi/roslyn,nguerrera/roslyn,tmat/roslyn,Hosch250/roslyn,brettfo/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,reaction1989/roslyn,tannergooding/roslyn,DustinCampbell/roslyn,mavasani/roslyn,cston/roslyn,panopticoncentral/roslyn,tmat/roslyn,davkean/roslyn,bartdesmet/roslyn,paulvanbrenk/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,DustinCampbell/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,mmitche/roslyn,jkotas/roslyn,reaction1989/roslyn,genlu/roslyn,bkoelman/roslyn,srivatsn/roslyn,khyperia/roslyn,xasx/roslyn,mavasani/roslyn,tmat/roslyn,orthoxerox/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,bkoelman/roslyn,physhi/roslyn,mattscheffer/roslyn,cston/roslyn,panopticoncentral/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,CaptainHayashi/roslyn,weltkante/roslyn,dotnet/roslyn,KevinRansom/roslyn,brettfo/roslyn,KirillOsenkov/roslyn
src/Compilers/CSharp/Test/Semantic/IOperation/IOperationTests_IPropertyReferenceExpression.cs
src/Compilers/CSharp/Test/Semantic/IOperation/IOperationTests_IPropertyReferenceExpression.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IOperationTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IPropertyReferenceExpression_PropertyReferenceInDerivedTypeUsesDerivedTypeAsInstanceType() { string source = @" class C { void M1() { C2 c2 = new C2() { /*<bind>*/P1 = 1/*</bind>*/ }; } } class C1 { public virtual int P1 { get; set; } } class C2 : C1 { } "; string expectedOperationTree = @" ISimpleAssignmentExpression (OperationKind.SimpleAssignmentExpression, Type: System.Int32) (Syntax: 'P1 = 1') Left: IPropertyReferenceExpression: System.Int32 C1.P1 { get; set; } (OperationKind.PropertyReferenceExpression, Type: System.Int32) (Syntax: 'P1') Instance Receiver: IInstanceReferenceExpression (OperationKind.InstanceReferenceExpression, Type: C1) (Syntax: 'P1') Right: ILiteralExpression (Text: 1) (OperationKind.LiteralExpression, Type: System.Int32, Constant: 1) (Syntax: '1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IOperationTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IPropertyReferenceExpression_PropertyReferenceInDerivedTypeUsesDerivedTypeAsInstanceType() { string source = @" class C { void M1() { C2 c2 = new C2() { /*<bind>*/P1 = 1/*</bind>*/ }; } } class C1 { public virtual int P1 { get; set; } } class C2 : C1 { } "; string expectedOperationTree = @" IPropertyReferenceExpression: System.Int32 C1.P1 { get; } (OperationKind.PropertyReferenceExpression, Type: System.Int32) (Syntax: 'c2.P1') Instance Receiver: ILocalReferenceExpression: c2 (OperationKind.LocalReferenceExpression, Type: C2) (Syntax: 'c2') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
mit
C#
82afbb5781165081e6167e4679a89ed1caeba8b6
add cache busting to js files
MarkPieszak/aspnetcore-angular2-universal,MarkPieszak/aspnetcore-angular2-universal,MarkPieszak/aspnetcore-angular2-universal,MarkPieszak/aspnetcore-angular2-universal
Views/_ViewImports.cshtml
Views/_ViewImports.cshtml
@using AspCoreServer @addTagHelper "*, Microsoft.AspNetCore.SpaServices" @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@using AspCoreServer @addTagHelper "*, Microsoft.AspNetCore.SpaServices"
mit
C#
f716151f46af96bcdfd3aaee1409f829bea4802b
Include fix for A* unit test.
eylvisaker/AgateLib
UnitTests/Algorithms/AStarTest.cs
UnitTests/Algorithms/AStarTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using AgateLib.Geometry; using AgateLib.Algorithms.PathFinding; namespace ZodiacTests.Algorithms { [TestClass] public class AStarTest { class FakeMap : IAStarMap<Point> { public void ReportProgress(AStarState<Point> task) { } public int CalculateHeuristic(Point location, Point destination) { return Math.Abs(destination.X - location.X) + Math.Abs(destination.Y - location.Y); } public int CalculateHeuristic(Point location, List<Point> destination) { int minval = int.MaxValue; foreach (var dest in destination) { int val = CalculateHeuristic(location, dest); if (val < minval) minval = val; } return minval; } public IEnumerable<Point> GetAvailableSteps(AStarState<Point> task, Point location) { for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { if (i == j || i == -j) continue; Point trial = new Point(location.X + i, location.Y + j); if (IsAvailable(trial)) yield return trial; } } } private bool IsAvailable(Point trial) { if (trial.X < 0) return false; if (trial.Y < 0) return false; if (trial.X > 15) return false; if (trial.Y > 15) return false; // area in (3, 3) - (12, 12) is blocked if (trial.X < 3) return true; if (trial.Y < 3) return true; if (trial.X > 12) return true; if (trial.Y > 12) return true; return false; } public int GetStepCost(AgateLib.Geometry.Point target, AgateLib.Geometry.Point start) { return 1; } } [TestMethod] public void AStarPath() { AStarState<Point> task = new AStarState<Point>(); task.Start = new AgateLib.Geometry.Point(4, 2); task.EndPoints.Add(new AgateLib.Geometry.Point(5, 15)); var astar = new AStar<Point>(new FakeMap()); astar.FindPathSync(task); // two steps to the left to get to (2, 2) // 13 steps down to get to (2, 15) // 3 steps to the right to get to (5, 15) // that's 18 steps, plus the start point makes 19. Assert.AreEqual(19, task.Path.Count); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using AgateLib.Geometry; using AgateLib.Algorithms.PathFinding; namespace ZodiacTests.Algorithms { [TestClass] public class AStarTest { class FakeMap : IAStarMap { public void ReportProgress(AStarTask task) { } public int CalculateHeuristic(Point location, Point destination) { return Math.Abs(destination.X - location.X) + Math.Abs(destination.Y - location.Y); } public int CalculateHeuristic(Point location, List<Point> destination) { int minval = int.MaxValue; foreach(var dest in destination) { int val = CalculateHeuristic(location, dest); if (val < minval) minval = val; } return minval; } public IEnumerable<Point> GetAvailableSteps(AStarTask task, Point location) { for (int j = -1; j <= 1; j++) { for (int i = -1; i <= 1; i++) { if (i == j || i == -j) continue; Point trial = new Point(location.X + i, location.Y + j); if (IsAvailable(trial)) yield return trial; } } } private bool IsAvailable(Point trial) { if (trial.X < 0) return false; if (trial.Y < 0) return false; if (trial.X > 15) return false; if (trial.Y > 15) return false; // area in (3, 3) - (12, 12) is blocked if (trial.X < 3) return true; if (trial.Y < 3) return true; if (trial.X > 12) return true; if (trial.Y > 12) return true; return false; } public int GetStepCost(AgateLib.Geometry.Point target, AgateLib.Geometry.Point start) { return 1; } } [TestMethod] public void AStarPath() { AStarTask task = new AStarTask(); task.Start = new AgateLib.Geometry.Point(4, 2); task.EndPoints.Add(new AgateLib.Geometry.Point(5, 15)); AStar.SetMap(new FakeMap()); AStar.FindPathSync(task); // two steps to the left to get to (2, 2) // 13 steps down to get to (2, 15) // 3 steps to the right to get to (5, 15) // that's 18 steps, plus the start point makes 19. Assert.AreEqual(19, task.Path.Count); } } }
mit
C#
b22e2229fb311b96a770680479c7572144a2d5d9
Add PointMass.ApplyImpulse.
drewnoakes/boing
Boing/PointMass.cs
Boing/PointMass.cs
using System.Collections.Generic; using System.Diagnostics; namespace Boing { public sealed class PointMass { private Vector2f _force; internal HashSet<ILocalForce> LocalForces { get; } = new HashSet<ILocalForce>(); public float Mass { get; set; } public float Damping { get; set; } public bool IsPinned { get; set; } public object Tag { get; set; } public Vector2f Position { get; set; } public Vector2f Velocity { get; set; } public PointMass(float mass = 1.0f, float damping = 0.5f, Vector2f? position = null) { Mass = mass; Damping = damping; Position = position ?? Vector2f.Random(); } public void ApplyForce(Vector2f force) { Debug.Assert(!float.IsNaN(force.X) && !float.IsNaN(force.Y), "!float.IsNaN(force.X) && !float.IsNaN(force.Y)"); Debug.Assert(!float.IsInfinity(force.X) && !float.IsInfinity(force.Y), "!float.IsInfinity(force.X) && !float.IsInfinity(force.Y)"); // Accumulate force _force += force; } public void ApplyImpulse(Vector2f impulse) { // Update velocity Velocity += impulse/Mass; } public void Update(float dt) { // Update velocity Velocity += _force/Mass*dt; Velocity *= Damping; // Update position Position += Velocity*dt; Debug.Assert(!float.IsNaN(Position.X) && !float.IsNaN(Position.Y), "!float.IsNaN(Position.X) && !float.IsNaN(Position.Y)"); Debug.Assert(!float.IsInfinity(Position.X) && !float.IsInfinity(Position.Y), "!float.IsInfinity(Position.X) && !float.IsInfinity(Position.Y)"); // Clear force _force = Vector2f.Zero; } } }
using System.Collections.Generic; using System.Diagnostics; namespace Boing { public sealed class PointMass { private Vector2f _force; internal HashSet<ILocalForce> LocalForces { get; } = new HashSet<ILocalForce>(); public float Mass { get; set; } public float Damping { get; set; } public bool IsPinned { get; set; } public object Tag { get; set; } public Vector2f Position { get; set; } public Vector2f Velocity { get; set; } public PointMass(float mass = 1.0f, float damping = 0.5f, Vector2f? position = null) { Mass = mass; Damping = damping; Position = position ?? Vector2f.Random(); } public void ApplyForce(Vector2f force) { Debug.Assert(!float.IsNaN(force.X) && !float.IsNaN(force.Y), "!float.IsNaN(force.X) && !float.IsNaN(force.Y)"); Debug.Assert(!float.IsInfinity(force.X) && !float.IsInfinity(force.Y), "!float.IsInfinity(force.X) && !float.IsInfinity(force.Y)"); // Accumulate force _force += force; } public void Update(float dt) { // Update velocity Velocity += _force/Mass*dt; Velocity *= Damping; // Update position Position += Velocity*dt; Debug.Assert(!float.IsNaN(Position.X) && !float.IsNaN(Position.Y), "!float.IsNaN(Position.X) && !float.IsNaN(Position.Y)"); Debug.Assert(!float.IsInfinity(Position.X) && !float.IsInfinity(Position.Y), "!float.IsInfinity(Position.X) && !float.IsInfinity(Position.Y)"); // Clear force _force = Vector2f.Zero; } } }
apache-2.0
C#
c86587f46b1013c5ab55cc9bf8ea7dc0229f94c7
Remove unused properties
delahermosa/Caliburn101
Caliburn101/Caliburn101.Shared/ViewModels/MainPageViewModel.cs
Caliburn101/Caliburn101.Shared/ViewModels/MainPageViewModel.cs
using Caliburn.Micro; using Caliburn101.Services; using System; using System.Collections.Generic; using System.Text; using System.Linq; using Windows.UI.Xaml.Controls; namespace Caliburn101.ViewModels { public class MainPageViewModel : Screen { private readonly IContactsService _contactsService; private readonly INavigationService _navigationService; private IEnumerable<ContactListViewModel> _contact; public IEnumerable<ContactListViewModel> Contact { get { return _contact; } set { _contact = value; NotifyOfPropertyChange(() => Contact); } } public MainPageViewModel(IContactsService contactsService, INavigationService navigationService) { _contactsService = contactsService; _navigationService = navigationService; } protected override void OnActivate() { base.OnActivate(); Contact = _contactsService.GetContacts().Select(c => new ContactListViewModel(c)); } public void Navigate(ItemClickEventArgs args) { var contact = args.ClickedItem as ContactListViewModel; _navigationService.NavigateToViewModel<ContactDetailViewModel>(contact.Id); } public void Add() { _navigationService.NavigateToViewModel<ContactDetailViewModel>(Guid.Empty); } public void Back() { _navigationService.GoBack(); } public bool CanBack() { return _navigationService.CanGoBack; } } }
using Caliburn.Micro; using Caliburn101.Services; using System; using System.Collections.Generic; using System.Text; using System.Linq; using Windows.UI.Xaml.Controls; namespace Caliburn101.ViewModels { public class MainPageViewModel : Screen { private readonly IContactsService _contactsService; private readonly INavigationService _navigationService; private IEnumerable<ContactListViewModel> _contact; private ContactListViewModel _selectedContact; public IEnumerable<ContactListViewModel> Contact { get { return _contact; } set { _contact = value; NotifyOfPropertyChange(() => Contact); } } public ContactListViewModel SelectedContact { get { return _selectedContact; } set { _selectedContact = value; NotifyOfPropertyChange(() => SelectedContact); } } public MainPageViewModel(IContactsService contactsService, INavigationService navigationService) { _contactsService = contactsService; _navigationService = navigationService; } protected override void OnActivate() { base.OnActivate(); Contact = _contactsService.GetContacts().Select(c => new ContactListViewModel(c)); } public void Navigate(ItemClickEventArgs args) { var contact = args.ClickedItem as ContactListViewModel; _navigationService.NavigateToViewModel<ContactDetailViewModel>(contact.Id); } public void Add() { _navigationService.NavigateToViewModel<ContactDetailViewModel>(Guid.Empty); } public void Back() { _navigationService.GoBack(); } public bool CanBack() { return _navigationService.CanGoBack; } } }
mit
C#
bd0c9a3d586107e41dc06ce829d78b910ef9162a
Fix running on < iOS 6.0
PowerOfCode/Eto,l8s/Eto,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto
Source/Eto.Platform.iOS/EtoAppDelegate.cs
Source/Eto.Platform.iOS/EtoAppDelegate.cs
using System; using MonoTouch.Foundation; using MonoTouch.UIKit; using Eto.Platform.iOS.Forms; using Eto.Forms; namespace Eto.Platform.iOS { [MonoTouch.Foundation.Register("EtoAppDelegate")] public class EtoAppDelegate : UIApplicationDelegate { public EtoAppDelegate () { } public override bool FinishedLaunching (UIApplication application, NSDictionary launcOptions) { ApplicationHandler.Instance.Initialize(this); return true; } } }
using System; using MonoTouch.Foundation; using MonoTouch.UIKit; using Eto.Platform.iOS.Forms; using Eto.Forms; namespace Eto.Platform.iOS { [MonoTouch.Foundation.Register("EtoAppDelegate")] public class EtoAppDelegate : UIApplicationDelegate { public EtoAppDelegate () { } public override bool WillFinishLaunching (UIApplication application, NSDictionary launchOptions) { ApplicationHandler.Instance.Initialize(this); return true; } } }
bsd-3-clause
C#
e4b1575f4f7ba2b693bccc38f898c561472e04be
Remove unused code
dk307/HSPI_WUWeather
DescriptionEnum.cs
DescriptionEnum.cs
using NullGuard; using System.ComponentModel; using System.Reflection; namespace Hspi { [NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)] public static class EnumHelper { /// <summary> /// Returns the value of the DescriptionAttribute if the specified Enum value has one. /// If not, returns the ToString() representation of the Enum value. /// </summary> /// <param name="value">The Enum to get the description for</param> /// <returns></returns> public static string GetDescription(System.Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) return attributes[0].Description; else return value.ToString(); } } }
using NullGuard; using System; using System.ComponentModel; using System.Reflection; namespace Hspi { [NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)] public static class EnumHelper { /// <summary> /// Returns the value of the DescriptionAttribute if the specified Enum value has one. /// If not, returns the ToString() representation of the Enum value. /// </summary> /// <param name="value">The Enum to get the description for</param> /// <returns></returns> public static string GetDescription(System.Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) return attributes[0].Description; else return value.ToString(); } /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivilant enumerated object. /// Note: Utilised the DescriptionAttribute for values that use it. /// </summary> /// <param name="enumType">The System.Type of the enumeration.</param> /// <param name="value">A string containing the name or value to convert.</param> /// <returns></returns> public static object Parse(Type enumType, string value) { return Parse(enumType, value, false); } /// <summary> /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivilant enumerated object. /// A parameter specified whether the operation is case-sensitive. /// Note: Utilised the DescriptionAttribute for values that use it. /// </summary> /// <param name="enumType">The System.Type of the enumeration.</param> /// <param name="value">A string containing the name or value to convert.</param> /// <param name="ignoreCase">Whether the operation is case-sensitive or not.</param> /// <returns></returns> public static object Parse(Type enumType, string value, bool ignoreCase) { if (ignoreCase) { value = value.ToLowerInvariant(); } foreach (System.Enum val in System.Enum.GetValues(enumType)) { string comparisson = GetDescription(val); if (ignoreCase) { comparisson = comparisson.ToLowerInvariant(); } if (GetDescription(val) == value) { return val; } } return System.Enum.Parse(enumType, value, ignoreCase); } } }
mit
C#
84e6895f77cef2044d59dbe53e1aafa0f41045c2
Add custom display option props based on sliders
bcemmett/SurveyMonkeyApi-v3,davek17/SurveyMonkeyApi-v3
SurveyMonkey/Containers/QuestionDisplayOptionsCustomOptions.cs
SurveyMonkey/Containers/QuestionDisplayOptionsCustomOptions.cs
using Newtonsoft.Json; using System.Collections.Generic; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class QuestionDisplayOptionsCustomOptions { public List<string> OptionSet { get; set; } public int StartingPosition { get; set; } public int StepSize { get; set; } } }
using Newtonsoft.Json; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class QuestionDisplayOptionsCustomOptions { } }
mit
C#
145aa9ed31d79c7ffae40f55f83215a206095506
Rename args to _
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Behaviors/ClearPropertyOnLostFocusBehavior.cs
WalletWasabi.Gui/Behaviors/ClearPropertyOnLostFocusBehavior.cs
using Avalonia; using Avalonia.Controls; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Xaml.Interactivity; using System; using System.Reactive.Disposables; using System.Reactive.Linq; namespace WalletWasabi.Gui.Behaviors { public class ClearPropertyOnLostFocusBehavior : Behavior<Control> { private CompositeDisposable Disposables { get; set; } public static readonly AvaloniaProperty<object> TargetPropertyProperty = AvaloniaProperty.Register<ClearPropertyOnLostFocusBehavior, object>(nameof(TargetProperty), defaultBindingMode: BindingMode.TwoWay); public object TargetProperty { get => GetValue(TargetPropertyProperty); set => SetValue(TargetPropertyProperty, value); } protected override void OnAttached() { Disposables = new CompositeDisposable { Observable.FromEventPattern<RoutedEventArgs>(AssociatedObject, nameof(AssociatedObject.LostFocus)).Subscribe(_=> { TargetProperty = null; }) }; base.OnAttached(); } protected override void OnDetaching() { base.OnDetaching(); Disposables?.Dispose(); } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Data; using Avalonia.Interactivity; using Avalonia.Xaml.Interactivity; using System; using System.Reactive.Disposables; using System.Reactive.Linq; namespace WalletWasabi.Gui.Behaviors { public class ClearPropertyOnLostFocusBehavior : Behavior<Control> { private CompositeDisposable Disposables { get; set; } public static readonly AvaloniaProperty<object> TargetPropertyProperty = AvaloniaProperty.Register<ClearPropertyOnLostFocusBehavior, object>(nameof(TargetProperty), defaultBindingMode: BindingMode.TwoWay); public object TargetProperty { get => GetValue(TargetPropertyProperty); set => SetValue(TargetPropertyProperty, value); } protected override void OnAttached() { Disposables = new CompositeDisposable { Observable.FromEventPattern<RoutedEventArgs>(AssociatedObject, nameof(AssociatedObject.LostFocus)).Subscribe(args=> { TargetProperty = null; }) }; base.OnAttached(); } protected override void OnDetaching() { base.OnDetaching(); Disposables?.Dispose(); } } }
mit
C#
4f9fdc883e9d0087583e48d53dde2804c8d56ebd
Convert all dates to UTC time
os2kitos/kitos,miracle-as/kitos,os2kitos/kitos,os2kitos/kitos,miracle-as/kitos,os2kitos/kitos,miracle-as/kitos,miracle-as/kitos
Presentation.Web/Global.asax.cs
Presentation.Web/Global.asax.cs
using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Presentation.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Turns off self reference looping when serializing models in API controlllers GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // Support polymorphism in web api JSON output GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Convert all dates to UTC GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; } } }
using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace Presentation.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); // Turns off self reference looping when serializing models in API controlllers GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // Support polymorphism in web api JSON output GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto; // Set JSON serialization in WEB API to use camelCase (javascript) instead of PascalCase (C#) GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //Format datetime correctly. From: http://stackoverflow.com/questions/20143739/date-format-in-mvc-4-api-controller var dateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings .Converters.Add(dateTimeConverter); } } }
mpl-2.0
C#
d154cfee181e009e96bee3c87292877325b987e5
Use arrays instead of generic enumerations in data models
InfiniteSoul/Azuria
Azuria/Api/v1/DataModels/Manga/ChapterDataModel.cs
Azuria/Api/v1/DataModels/Manga/ChapterDataModel.cs
using System; using System.Collections.Generic; using Azuria.Api.v1.Converters; using Azuria.Api.v1.Converters.Manga; using Newtonsoft.Json; namespace Azuria.Api.v1.DataModels.Manga { /// <summary> /// </summary> public class ChapterDataModel { #region Properties /// <summary> /// </summary> [JsonProperty("cid")] public int ChapterId { get; set; } /// <summary> /// </summary> [JsonProperty("title")] public string ChapterTitle { get; set; } /// <summary> /// </summary> [JsonProperty("eid")] public int EntryId { get; set; } /// <summary> /// </summary> [JsonProperty("pages")] [JsonConverter(typeof(PagesConverter))] public PageDataModel[] Pages { get; set; } /// <summary> /// </summary> [JsonProperty("server")] public int ServerId { get; set; } /// <summary> /// </summary> [JsonProperty("tid")] public int? TranslatorId { get; set; } /// <summary> /// </summary> [JsonProperty("tname")] public string TranslatorName { get; set; } /// <summary> /// </summary> [JsonProperty("uploader")] public int UploaderId { get; set; } /// <summary> /// </summary> [JsonProperty("username")] public string UploaderName { get; set; } /// <summary> /// </summary> [JsonProperty("timestamp")] [JsonConverter(typeof(UnixToDateTimeConverter))] public DateTime UploadTimestamp { get; set; } #endregion } }
using System; using System.Collections.Generic; using Azuria.Api.v1.Converters; using Azuria.Api.v1.Converters.Manga; using Newtonsoft.Json; namespace Azuria.Api.v1.DataModels.Manga { /// <summary> /// </summary> public class ChapterDataModel { #region Properties /// <summary> /// </summary> [JsonProperty("cid")] public int ChapterId { get; set; } /// <summary> /// </summary> [JsonProperty("title")] public string ChapterTitle { get; set; } /// <summary> /// </summary> [JsonProperty("eid")] public int EntryId { get; set; } /// <summary> /// </summary> [JsonProperty("pages")] [JsonConverter(typeof(PagesConverter))] public IEnumerable<PageDataModel> Pages { get; set; } /// <summary> /// </summary> [JsonProperty("server")] public int ServerId { get; set; } /// <summary> /// </summary> [JsonProperty("tid")] public int? TranslatorId { get; set; } /// <summary> /// </summary> [JsonProperty("tname")] public string TranslatorName { get; set; } /// <summary> /// </summary> [JsonProperty("uploader")] public int UploaderId { get; set; } /// <summary> /// </summary> [JsonProperty("username")] public string UploaderName { get; set; } /// <summary> /// </summary> [JsonProperty("timestamp")] [JsonConverter(typeof(UnixToDateTimeConverter))] public DateTime UploadTimestamp { get; set; } #endregion } }
mit
C#
8d5683fd5841eeadfed12be62336f27661f98bbf
Change xpath for testing with policesuccess site
SkillsFundingAgency/das-referencedata,SkillsFundingAgency/das-referencedata
src/SFA.DAS.ReferenceData.PublicSectorOrgs.WebJob/Updater/PublicSectorOrganisationHtmlScraper.cs
src/SFA.DAS.ReferenceData.PublicSectorOrgs.WebJob/Updater/PublicSectorOrganisationHtmlScraper.cs
using System; using System.Linq; using HtmlAgilityPack; using SFA.DAS.NLog.Logger; using SFA.DAS.ReferenceData.Domain.Models; using SFA.DAS.ReferenceData.Types.DTO; namespace SFA.DAS.ReferenceData.PublicSectorOrgs.WebJob.Updater { public class PublicSectorOrganisationHtmlScraper : IPublicSectorOrganisationHtmlScraper { public PublicSectorOrganisationLookUp Scrape(string url, ILog logger) { var ol = new PublicSectorOrganisationLookUp(); try { var web = new HtmlWeb(); var doc = web.Load(url); var englandPolice = doc.DocumentNode.SelectNodes("//*[@id=\"wsite-content\"]/div/div/div/div/div/div[3]/ul/li/a") .Where(p => !string.IsNullOrWhiteSpace(p.InnerText)) .Select(p => p.InnerText.Trim()); var nationalPolice = doc.DocumentNode.SelectNodes("//*[@id=\"wsite-content\"]/div/div/div/div/div/div[11]/ul/li") .Where(p => !string.IsNullOrWhiteSpace(p.InnerText)) .Select(p => p.InnerText.Trim()); ol.Organisations = englandPolice.Concat(nationalPolice) .Select(x => new PublicSectorOrganisation { Name = x, Sector = "", Source = DataSource.Police }).ToList(); } catch (Exception e) { logger.Error(e, "Cannot get Police organisations, potential format change"); throw; } return ol; } } }
using System; using System.Linq; using HtmlAgilityPack; using SFA.DAS.NLog.Logger; using SFA.DAS.ReferenceData.Domain.Models; using SFA.DAS.ReferenceData.Types.DTO; namespace SFA.DAS.ReferenceData.PublicSectorOrgs.WebJob.Updater { public class PublicSectorOrganisationHtmlScraper : IPublicSectorOrganisationHtmlScraper { public PublicSectorOrganisationLookUp Scrape(string url, ILog logger) { var ol = new PublicSectorOrganisationLookUp(); try { var web = new HtmlWeb(); var doc = web.Load(url); var englandPolice = doc.DocumentNode.SelectNodes("//*[@id=\"content\"]/div[2]/div/section/div[2]/div[4]/div/div/div[1]/div/div[2]/div/ul/li/a/text()") .Where(p => !string.IsNullOrWhiteSpace(p.InnerText)) .Select(p => p.InnerText.Trim()); var nationalPolice = doc.DocumentNode.SelectNodes("//*[@id=\"content\"]/div[2]/div/section/div[2]/div[4]/div/div/div[5]/div/div[2]/div/ul/li/a/text()") .Where(p => !string.IsNullOrWhiteSpace(p.InnerText)) .Select(p => p.InnerText.Trim()); ol.Organisations = englandPolice.Concat(nationalPolice) .Select(x => new PublicSectorOrganisation { Name = x, Sector = "", Source = DataSource.Police }).ToList(); } catch (Exception e) { logger.Error(e, "Cannot get Police organisations, potential format change"); throw; } return ol; } } }
mit
C#
3e67e6fd565892c589abb814ee6b287a6a140bb2
Improve QuotedPrintable test coverage
carbon/Amazon
src/Amazon.Ses.Tests/QuotedPrintableTests.cs
src/Amazon.Ses.Tests/QuotedPrintableTests.cs
 using System.Net.Mail; using Xunit; namespace Amazon.Ses.Tests { public class QuotedPrintableTests { [Fact] public void Decode() { Assert.Equal("Subject", QuotedPrintable.Decode("=?utf-8?Q?Subject?=")); Assert.Equal("☻", QuotedPrintable.Decode("=?UTF-8?Q?=E2=98=BB?=")); Assert.Equal("Як ти поживаєш?", QuotedPrintable.Decode("=?utf-8?Q?=D0=AF=D0=BA_=D1=82=D0=B8_=D0=BF=D0=BE=D0=B6=D0=B8=D0=B2=D0=B0=D1=94=D1=88=3F?=")); } [Fact] public void Encode() { // 309ms per 1M Assert.Equal("=?utf-8?Q?=E2=98=BB?=", QuotedPrintable.Encode("☻")); } [Fact] public void DeodeUtf8Code() { var q = "=?UTF-8?Q?=E0=B8=99=E0=B8=A0=E0=B8=B1=E0=B8=AA=E0=B8=AA=E0=B8=A3?="; var r = QuotedPrintable.Decode(q); Assert.Equal("นภัสสร", r); } [Fact] public void DeodeUtf8Code_WithSpace() { var q = "=?utf-8?Q?\"Jo=C3=A3o\" <x@x>?="; MailAddress.TryCreate(QuotedPrintable.Decode(q), out var r); Assert.Equal("João", r.DisplayName); Assert.Equal("x@x", r.Address); } } }
 using Xunit; namespace Amazon.Ses.Tests { public class QuotedPrintableTests { [Fact] public void Decode() { Assert.Equal("Subject", QuotedPrintable.Decode("=?utf-8?Q?Subject?=")); Assert.Equal("☻", QuotedPrintable.Decode("=?UTF-8?Q?=E2=98=BB?=")); Assert.Equal("Як ти поживаєш?", QuotedPrintable.Decode("=?utf-8?Q?=D0=AF=D0=BA_=D1=82=D0=B8_=D0=BF=D0=BE=D0=B6=D0=B8=D0=B2=D0=B0=D1=94=D1=88=3F?=")); } [Fact] public void Encode() { Assert.Equal("=?utf-8?Q?=E2=98=BB?=", QuotedPrintable.Encode("☻")); } [Fact] public void DeodeUtf8Code() { var q = "=?UTF-8?Q?=E0=B8=99=E0=B8=A0=E0=B8=B1=E0=B8=AA=E0=B8=AA=E0=B8=A3?="; var r = QuotedPrintable.Decode(q); Assert.Equal("นภัสสร", r); } } }
mit
C#
279eef146283d775b8d93a52b39af4b880848015
Update RendererOptions.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Views/Renderer/RendererOptions.cs
src/Core2D/Views/Renderer/RendererOptions.cs
#nullable enable using Avalonia; using Avalonia.Data; using Core2D.Model; using Core2D.Model.Renderer; using Core2D.ViewModels.Data; namespace Core2D.Views.Renderer; public class RendererOptions { public static readonly AttachedProperty<IShapeRenderer?> RendererProperty = AvaloniaProperty.RegisterAttached<RendererOptions, AvaloniaObject, IShapeRenderer?>("Renderer", null, true, BindingMode.TwoWay); public static IShapeRenderer? GetRenderer(AvaloniaObject obj) { return obj.GetValue(RendererProperty); } public static void SetRenderer(AvaloniaObject obj, IShapeRenderer? value) { obj.SetValue(RendererProperty, value); } public static readonly AttachedProperty<ISelection?> SelectionProperty = AvaloniaProperty.RegisterAttached<RendererOptions, AvaloniaObject, ISelection?>("Selection", null, true, BindingMode.TwoWay); public static ISelection? GetSelection(AvaloniaObject obj) { return obj.GetValue(SelectionProperty); } public static void SetSelection(AvaloniaObject obj, ISelection? value) { obj.SetValue(SelectionProperty, value); } public static readonly AttachedProperty<DataFlow?> DataFlowProperty = AvaloniaProperty.RegisterAttached<RendererOptions, AvaloniaObject, DataFlow?>("DataFlow", null, true, BindingMode.TwoWay); public static DataFlow? GetDataFlow(AvaloniaObject obj) { return obj.GetValue(DataFlowProperty); } public static void SetDataFlow(AvaloniaObject obj, DataFlow? value) { obj.SetValue(DataFlowProperty, value); } }
#nullable enable using Avalonia; using Avalonia.Data; using Core2D.Model; using Core2D.Model.Renderer; using Core2D.ViewModels.Data; namespace Core2D.Views.Renderer; public class RendererOptions { public static readonly AttachedProperty<IShapeRenderer> RendererProperty = AvaloniaProperty.RegisterAttached<RendererOptions, AvaloniaObject, IShapeRenderer>("Renderer", null, true, BindingMode.TwoWay); public static IShapeRenderer GetRenderer(AvaloniaObject obj) { return obj.GetValue(RendererProperty); } public static void SetRenderer(AvaloniaObject obj, IShapeRenderer value) { obj.SetValue(RendererProperty, value); } public static readonly AttachedProperty<ISelection> SelectionProperty = AvaloniaProperty.RegisterAttached<RendererOptions, AvaloniaObject, ISelection>("Selection", null, true, BindingMode.TwoWay); public static ISelection GetSelection(AvaloniaObject obj) { return obj.GetValue(SelectionProperty); } public static void SetSelection(AvaloniaObject obj, ISelection value) { obj.SetValue(SelectionProperty, value); } public static readonly AttachedProperty<DataFlow> DataFlowProperty = AvaloniaProperty.RegisterAttached<RendererOptions, AvaloniaObject, DataFlow>("DataFlow", null, true, BindingMode.TwoWay); public static DataFlow GetDataFlow(AvaloniaObject obj) { return obj.GetValue(DataFlowProperty); } public static void SetDataFlow(AvaloniaObject obj, DataFlow value) { obj.SetValue(DataFlowProperty, value); } }
mit
C#
8905c548358564a0d99890d0a359b96b056c147d
Update comment.
swaroop-sridhar/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,jmarolf/roslyn,MichalStrehovsky/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,tmat/roslyn,jcouv/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,nguerrera/roslyn,davkean/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,aelij/roslyn,brettfo/roslyn,eriawan/roslyn,agocke/roslyn,agocke/roslyn,mavasani/roslyn,diryboy/roslyn,abock/roslyn,jcouv/roslyn,tmat/roslyn,mavasani/roslyn,physhi/roslyn,reaction1989/roslyn,swaroop-sridhar/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,VSadov/roslyn,sharwell/roslyn,jmarolf/roslyn,agocke/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,DustinCampbell/roslyn,stephentoub/roslyn,bartdesmet/roslyn,tannergooding/roslyn,heejaechang/roslyn,genlu/roslyn,jcouv/roslyn,tmat/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,heejaechang/roslyn,stephentoub/roslyn,KevinRansom/roslyn,davkean/roslyn,AmadeusW/roslyn,aelij/roslyn,abock/roslyn,weltkante/roslyn,weltkante/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,weltkante/roslyn,davkean/roslyn,mavasani/roslyn,nguerrera/roslyn,DustinCampbell/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,MichalStrehovsky/roslyn,gafter/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,ErikSchierboom/roslyn,aelij/roslyn,stephentoub/roslyn,VSadov/roslyn,reaction1989/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,gafter/roslyn,VSadov/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,reaction1989/roslyn,physhi/roslyn,sharwell/roslyn,eriawan/roslyn,dotnet/roslyn,swaroop-sridhar/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,gafter/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,dotnet/roslyn,DustinCampbell/roslyn,genlu/roslyn,brettfo/roslyn,bartdesmet/roslyn,abock/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn
src/EditorFeatures/Core/Wrapping/IWrapper.cs
src/EditorFeatures/Core/Wrapping/IWrapper.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.Wrapping { /// <summary> /// Interface for types that can wrap some sort of language construct. /// </summary> /// <remarks> /// The main refactoring /// keeps walking up nodes until it finds the first IWrapper that can handle that node. That /// way the user is not inundated with lots of wrapping options for all the nodes their cursor /// is contained within. /// </remarks> /// <seealso cref="AbstractWrappingCodeRefactoringProvider"/> internal interface IWrapper { /// <summary> /// Returns the <see cref="ICodeActionComputer"/> that produces wrapping code actions for the /// node passed in. Returns <see langword="null"/> if this Wrapper cannot wrap this node. /// </summary> Task<ICodeActionComputer> TryCreateComputerAsync( Document document, int position, SyntaxNode node, CancellationToken cancellationToken); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.Wrapping { /// <summary> /// Interface for types that can wrap some sort of language construct. The main refactoring /// keeps walking up nodes until it finds the first IWrapper that can handle that node. That /// way the user is not inundated with lots of wrapping options for all the nodes their cursor /// is contained within. /// </summary> internal interface IWrapper { /// <summary> /// Returns the <see cref="ICodeActionComputer"/> that produces wrapping code actions for the /// node passed in. Returns <see langword="null"/> if this Wrapper cannot wrap this node. /// </summary> Task<ICodeActionComputer> TryCreateComputerAsync( Document document, int position, SyntaxNode node, CancellationToken cancellationToken); } }
mit
C#
404d58c55bac05619801c4cdf392f53c6787f8bf
remove ? at the end of a URL (if no QS parameters are used).
IdentityModel/IdentityModelv2,IdentityModel/IdentityModelv2,IdentityModel/IdentityModel2,IdentityModel/IdentityModel2,IdentityModel/IdentityModel,IdentityModel/IdentityModel
src/IdentityModel/Client/AuthorizeRequest.cs
src/IdentityModel/Client/AuthorizeRequest.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace IdentityModel.Client { /// <summary> /// Helper class for creating authorize request URLs /// </summary> public class AuthorizeRequest { private readonly Uri _authorizeEndpoint; /// <summary> /// Initializes a new instance of the <see cref="AuthorizeRequest"/> class. /// </summary> /// <param name="authorizeEndpoint">The authorize endpoint.</param> public AuthorizeRequest(Uri authorizeEndpoint) { _authorizeEndpoint = authorizeEndpoint; } /// <summary> /// Initializes a new instance of the <see cref="AuthorizeRequest"/> class. /// </summary> /// <param name="authorizeEndpoint">The authorize endpoint.</param> public AuthorizeRequest(string authorizeEndpoint) { _authorizeEndpoint = new Uri(authorizeEndpoint); } /// <summary> /// Creates URL based on key/value input pairs. /// </summary> /// <param name="values">The values.</param> /// <returns></returns> public string Create(IDictionary<string, string> values) { var qs = string.Join("&", values.Select(kvp => string.Format("{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value))).ToArray()); string url; if (_authorizeEndpoint.IsAbsoluteUri) { url = string.Format("{0}?{1}", _authorizeEndpoint.AbsoluteUri, qs); } else { url = string.Format("{0}?{1}", _authorizeEndpoint.OriginalString, qs); } return url.TrimEnd('?'); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace IdentityModel.Client { /// <summary> /// Helper class for creating authorize request URLs /// </summary> public class AuthorizeRequest { private readonly Uri _authorizeEndpoint; /// <summary> /// Initializes a new instance of the <see cref="AuthorizeRequest"/> class. /// </summary> /// <param name="authorizeEndpoint">The authorize endpoint.</param> public AuthorizeRequest(Uri authorizeEndpoint) { _authorizeEndpoint = authorizeEndpoint; } /// <summary> /// Initializes a new instance of the <see cref="AuthorizeRequest"/> class. /// </summary> /// <param name="authorizeEndpoint">The authorize endpoint.</param> public AuthorizeRequest(string authorizeEndpoint) { _authorizeEndpoint = new Uri(authorizeEndpoint); } /// <summary> /// Creates URL based on key/value input pairs. /// </summary> /// <param name="values">The values.</param> /// <returns></returns> public string Create(IDictionary<string, string> values) { var qs = string.Join("&", values.Select(kvp => string.Format("{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value))).ToArray()); if (_authorizeEndpoint.IsAbsoluteUri) { return string.Format("{0}?{1}", _authorizeEndpoint.AbsoluteUri, qs); } else { return string.Format("{0}?{1}", _authorizeEndpoint.OriginalString, qs); } } } }
apache-2.0
C#
457c2fffb9fffd1eb727e8c2b6bf95c5c31a06cf
Update versions before upload
newchild/LegendaryClient-1,semtize/LegendaryClient
LegendaryClient/Properties/AssemblyInfo.cs
LegendaryClient/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("LegendaryClient")] [assembly: AssemblyDescription("League of Legends Client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Legendary Coding")] [assembly: AssemblyProduct("LegendaryClient")] [assembly: AssemblyCopyright("Copyright (c) 2013-2014, Eddy5641/Snowl (Eddy V - legendarycoding.weebly.com)")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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("2.0.1.1")] [assembly: AssemblyFileVersion("2.0.1.1")] [assembly: log4net.Config.XmlConfigurator(ConfigFile="log4net.config",Watch=true)] //switch this to 1.1.0.0 after replay fix
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("LegendaryClient")] [assembly: AssemblyDescription("League of Legends Client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Legendary Coding")] [assembly: AssemblyProduct("LegendaryClient")] [assembly: AssemblyCopyright("Copyright (c) 2013-2014, Eddy5641/Snowl (Eddy V - legendarycoding.weebly.com)")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: log4net.Config.XmlConfigurator(ConfigFile="log4net.config",Watch=true)] //switch this to 1.1.0.0 after replay fix
bsd-2-clause
C#
2a1e4ac128c120117b120fa617ead0b76b1d6c05
Refactor Enemy for derivation
lukehb/ld37
Assets/Scripts/Enemy.cs
Assets/Scripts/Enemy.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Enemy always slowly turns to face players. * Enemy always slowly walks toward the player * **/ public class Enemy : MonoBehaviour { [SerializeField] private float turnSpeed; [SerializeField] private float moveSpeed; [SerializeField] private float attackRadius; [SerializeField] private Animator anim; private static readonly int IsPunchingTriggerId = Animator.StringToHash("IsPunching"); private static readonly string AttackingStateTag = "Attacking"; public Player Target { get; private set; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Target != null) { Turn(); Move(); Attack(); } } protected virtual void Attack() { double dist = Vector3.Distance(Target.transform.position, this.transform.position); if(dist <= attackRadius) { AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0); bool curIsAttacking = stateInfo.IsTag(AttackingStateTag); if (!curIsAttacking) { anim.SetTrigger(IsPunchingTriggerId); } } } protected virtual void Move() { this.transform.position = Vector3.MoveTowards(this.transform.position, this.Target.transform.position, moveSpeed * Time.deltaTime); } protected virtual void Turn() { Vector3 targetDir = Target.transform.position - this.transform.position; float step = Time.deltaTime * turnSpeed; Vector3 newDir = Vector3.RotateTowards(transform.up, targetDir, step, 0.0F); newDir.z = 0; this.transform.up = newDir; } public void GoKillThisGuy(Player player) { this.Target = player; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Enemy always slowly turns to face players. * Enemy always slowly walks toward the player * **/ public class Enemy : MonoBehaviour { [SerializeField] private float turnSpeed; [SerializeField] private float moveSpeed; [SerializeField] private float attackRadius; [SerializeField] private Animator anim; private static readonly int IsPunchingTriggerId = Animator.StringToHash("IsPunching"); private static readonly string AttackingStateTag = "Attacking"; private Player player; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(player != null) { SlowlyFacePlayer(); SlowlyWalkTowardsPlayer(); TryAttack(); } } private void TryAttack() { double dist = Vector3.Distance(player.transform.position, this.transform.position); if(dist <= attackRadius) { AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0); bool curIsAttacking = stateInfo.IsTag(AttackingStateTag); if (!curIsAttacking) { anim.SetTrigger(IsPunchingTriggerId); } } } private void SlowlyWalkTowardsPlayer() { this.transform.position = Vector3.MoveTowards(this.transform.position, this.player.transform.position, moveSpeed * Time.deltaTime); } private void SlowlyFacePlayer() { Vector3 targetDir = player.transform.position - this.transform.position; float step = Time.deltaTime * turnSpeed; Vector3 newDir = Vector3.RotateTowards(transform.up, targetDir, step, 0.0F); newDir.z = 0; this.transform.up = newDir; } public void GoKillThisGuy(Player player) { this.player = player; } }
mit
C#
329868e99ec7455455bae11dfd7246cd0a4fafe3
Change ASN int array to IList
mstrother/BmpListener
BmpListener/Bgp/ASPathSegment.cs
BmpListener/Bgp/ASPathSegment.cs
using System.Collections.Generic; namespace BmpListener.Bgp { public class ASPathSegment { public ASPathSegment(Type type, IList<int> asns) { SegmentType = type; ASNs = asns; } public enum Type { AS_SET = 1, AS_SEQUENCE, AS_CONFED_SEQUENCE, AS_CONFED_SET } public Type SegmentType { get; set; } public IList<int> ASNs { get; set; } } }
namespace BmpListener.Bgp { public class ASPathSegment { public ASPathSegment(Type type, int[] asns) { SegmentType = Type; ASNs = asns; } public enum Type { AS_SET = 1, AS_SEQUENCE, AS_CONFED_SEQUENCE, AS_CONFED_SET } public Type SegmentType { get; set; } public int[] ASNs { get; set; } } }
mit
C#
8adff625b67faf2554e555e068704be297c298d7
Add some properties to the User class
Inumedia/SlackAPI
SlackAPI/User.cs
SlackAPI/User.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public class User { public string id; public bool IsSlackBot { get { return id.Equals("USLACKBOT", StringComparison.CurrentCultureIgnoreCase); } } public string name; public bool deleted; public string color; public UserProfile profile; public bool is_admin; public bool is_owner; public bool is_primary_owner; public bool is_restricted; public bool is_ultra_restricted; public bool has_2fa; public string two_factor_type; public bool has_files; public string presence; public bool is_bot; public string tz; public string tz_label; public int tz_offset; public string team_id; public string real_name; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public class User { public string id; public bool IsSlackBot { get { return id.Equals("USLACKBOT", StringComparison.CurrentCultureIgnoreCase); } } public string name; public bool deleted; public string color; public UserProfile profile; public bool is_admin; public bool is_owner; public bool has_files; public string presence; public bool is_bot; public string tz; public string tz_label; public int tz_offset; } }
mit
C#
8a1842be6910c3240868f75c6e2e4e78062f2b50
set parent to null after removing the tab from the handler
bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,l8s/Eto
Source/Eto/Forms/Controls/TabControl.cs
Source/Eto/Forms/Controls/TabControl.cs
using System; using System.Collections; using System.Linq; #if XAML using System.Windows.Markup; #endif namespace Eto.Forms { public interface ITabControl : IControl { int SelectedIndex { get; set; } void InsertTab (int index, TabPage page); void ClearTabs (); void RemoveTab (int index, TabPage page); } [ContentProperty("TabPages")] public class TabControl : Control { TabPageCollection pages; ITabControl handler; public event EventHandler<EventArgs> SelectedIndexChanged; public virtual void OnSelectedIndexChanged (EventArgs e) { if (SelectedIndexChanged != null) SelectedIndexChanged (this, e); } public TabControl () : this (Generator.Current) { } public TabControl (Generator g) : this (g, typeof(ITabControl)) { } protected TabControl (Generator generator, Type type, bool initialize = true) : base (generator, type, initialize) { pages = new TabPageCollection (this); handler = (ITabControl)base.Handler; } public int SelectedIndex { get { return handler.SelectedIndex; } set { handler.SelectedIndex = value; } } public TabPage SelectedPage { get { return SelectedIndex < 0 ? null : TabPages [SelectedIndex]; } set { SelectedIndex = pages.IndexOf (value); } } public TabPageCollection TabPages { get { return pages; } } internal void InsertTab (int index, TabPage page) { if (Loaded) { page.OnPreLoad (EventArgs.Empty); page.OnLoad (EventArgs.Empty); page.OnLoadComplete (EventArgs.Empty); } page.SetParent (this); handler.InsertTab (index, page); } internal void RemoveTab (int index, TabPage page) { handler.RemoveTab (index, page); page.SetParent (null); } internal void ClearTabs () { handler.ClearTabs (); } public override void OnPreLoad (EventArgs e) { base.OnPreLoad (e); foreach (var page in pages) { page.OnPreLoad (e); } } public override void OnLoad (EventArgs e) { base.OnLoad (e); foreach (var page in pages) { page.OnLoad (e); } } public override void OnLoadComplete (EventArgs e) { base.OnLoadComplete (e); foreach (var page in pages) { page.OnLoadComplete (e); } } internal protected override void OnDataContextChanged (EventArgs e) { base.OnDataContextChanged (e); foreach (var tab in TabPages) { tab.OnDataContextChanged (e); } } public override void UpdateBindings () { base.UpdateBindings (); foreach (var tab in TabPages) { tab.UpdateBindings (); } } } }
using System; using System.Collections; using System.Linq; #if XAML using System.Windows.Markup; #endif namespace Eto.Forms { public interface ITabControl : IControl { int SelectedIndex { get; set; } void InsertTab (int index, TabPage page); void ClearTabs (); void RemoveTab (int index, TabPage page); } [ContentProperty("TabPages")] public class TabControl : Control { TabPageCollection pages; ITabControl handler; public event EventHandler<EventArgs> SelectedIndexChanged; public virtual void OnSelectedIndexChanged (EventArgs e) { if (SelectedIndexChanged != null) SelectedIndexChanged (this, e); } public TabControl () : this (Generator.Current) { } public TabControl (Generator g) : this (g, typeof(ITabControl)) { } protected TabControl (Generator generator, Type type, bool initialize = true) : base (generator, type, initialize) { pages = new TabPageCollection (this); handler = (ITabControl)base.Handler; } public int SelectedIndex { get { return handler.SelectedIndex; } set { handler.SelectedIndex = value; } } public TabPage SelectedPage { get { return SelectedIndex < 0 ? null : TabPages [SelectedIndex]; } set { SelectedIndex = pages.IndexOf (value); } } public TabPageCollection TabPages { get { return pages; } } internal void InsertTab (int index, TabPage page) { if (Loaded) { page.OnPreLoad (EventArgs.Empty); page.OnLoad (EventArgs.Empty); page.OnLoadComplete (EventArgs.Empty); } page.SetParent (this); handler.InsertTab (index, page); } internal void RemoveTab (int index, TabPage page) { page.SetParent (null); handler.RemoveTab (index, page); } internal void ClearTabs () { handler.ClearTabs (); } public override void OnPreLoad (EventArgs e) { base.OnPreLoad (e); foreach (var page in pages) { page.OnPreLoad (e); } } public override void OnLoad (EventArgs e) { base.OnLoad (e); foreach (var page in pages) { page.OnLoad (e); } } public override void OnLoadComplete (EventArgs e) { base.OnLoadComplete (e); foreach (var page in pages) { page.OnLoadComplete (e); } } internal protected override void OnDataContextChanged (EventArgs e) { base.OnDataContextChanged (e); foreach (var tab in TabPages) { tab.OnDataContextChanged (e); } } public override void UpdateBindings () { base.UpdateBindings (); foreach (var tab in TabPages) { tab.UpdateBindings (); } } } }
bsd-3-clause
C#
59fb6ac9b9644effe3503de5d46ba00d7719cfdd
Bump assembly info for 1.2.2 release
NellyHaglund/SurveyMonkeyApi,bcemmett/SurveyMonkeyApi
SurveyMonkey/Properties/AssemblyInfo.cs
SurveyMonkey/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("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [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("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.2.2.0")] [assembly: AssemblyFileVersion("1.2.2.0")]
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("SurveyMonkeyApi")] [assembly: AssemblyDescription("Library for accessing v2 of the Survey Monkey Api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SurveyMonkeyApi")] [assembly: AssemblyCopyright("Copyright © Ben Emmett")] [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("da9e0373-83cd-4deb-87a5-62b313be61ec")] // 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.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")]
mit
C#
99bd9a2bf8a0bb0f0f4897defceaa326e851b5a9
Use inspector for child classes
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MixedRealityToolkit.SDK/Inspectors/Input/Handlers/MixedRealityControllerVisualizerInspector.cs
Assets/MixedRealityToolkit.SDK/Inspectors/Input/Handlers/MixedRealityControllerVisualizerInspector.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Input.Editor { [CustomEditor(typeof(MixedRealityControllerVisualizer), true)] public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Input.Editor { [CustomEditor(typeof(MixedRealityControllerVisualizer))] public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { } }
mit
C#
dfdba1fb6755d9a6998af875c03bb8d67f8074cd
Fix typo in Preset2
BeowulfStratOps/BSU.Sync
FileTypes/BI/Preset2.cs
FileTypes/BI/Preset2.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace BSU.Sync.FileTypes.BI { [XmlRoot(ElementName = "addons-presets")] public class Preset2 { [XmlElement(ElementName = "last-update")] public DateTime LastUpdated; [XmlArray(ElementName = "published-ids")] [XmlArrayItem(ElementName = "id")] public List<String> PublishedId = new List<String>(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace BSU.Sync.FileTypes.BI { [XmlRoot(ElementName = "addons-presets")] public class Preset2 { [XmlElement(ElementName = "last-update5")] public DateTime LastUpdated; [XmlArray(ElementName = "published-ids")] [XmlArrayItem(ElementName = "id")] public List<String> PublishedId = new List<String>(); } }
mit
C#
9b2d4f46b37287e1af748a20b64ed9e49123f802
make PackageKey have equal hashes for equal data
aaronmell/NugetPackageReport
NugetPackageReport/PackageKey.cs
NugetPackageReport/PackageKey.cs
namespace NugetPackageReport { /// <summary> /// a composite key used to uniquely identify a package /// </summary> internal class PackageKey { /// <summary> /// The Name of the Package /// </summary> internal string Id { get; set; } /// <summary> /// The version of the package /// </summary> internal string Version { get; set; } public override bool Equals(object obj) { if (obj == null || !(obj is PackageKey)) return false; var packageKey = (PackageKey)obj; return packageKey.Id == Id && packageKey.Version == Version; } public override int GetHashCode() { return Version.GetHashCode() + Id.GetHashCode(); } } }
namespace NugetPackageReport { /// <summary> /// a composite key used to uniquely identify a package /// </summary> internal class PackageKey { /// <summary> /// The Name of the Package /// </summary> internal string Id { get; set; } /// <summary> /// The version of the package /// </summary> internal string Version { get; set; } } }
mit
C#
6e51a24888092fb5ae19edb4326c03e19758bbe8
use header and body instead of rows in Examples (c#)
amaniak/gherkin3,vincent-psarga/gherkin3,thetutlage/gherkin3,dg-ratiodata/gherkin3,dirkrombauts/gherkin3,chebizarro/gherkin3,amaniak/gherkin3,dirkrombauts/gherkin3,SabotageAndi/gherkin,amaniak/gherkin3,hayd/gherkin3,dirkrombauts/gherkin3,SabotageAndi/gherkin,amaniak/gherkin3,thetutlage/gherkin3,concertman/gherkin3,curzona/gherkin3,thetutlage/gherkin3,thiblahute/gherkin3,araines/gherkin3,thiblahute/gherkin3,thetutlage/gherkin3,curzona/gherkin3,SabotageAndi/gherkin,thetutlage/gherkin3,cucumber/gherkin3,pjlsergeant/gherkin,chebizarro/gherkin3,moreirap/gherkin3,curzona/gherkin3,cucumber/gherkin3,cucumber/gherkin3,Zearin/gherkin3,amaniak/gherkin3,chebizarro/gherkin3,amaniak/gherkin3,concertman/gherkin3,SabotageAndi/gherkin,vincent-psarga/gherkin3,vincent-psarga/gherkin3,dg-ratiodata/gherkin3,vincent-psarga/gherkin3,curzona/gherkin3,cucumber/gherkin3,moreirap/gherkin3,SabotageAndi/gherkin,concertman/gherkin3,SabotageAndi/gherkin,concertman/gherkin3,thiblahute/gherkin3,hayd/gherkin3,hayd/gherkin3,concertman/gherkin3,cucumber/gherkin3,concertman/gherkin3,amaniak/gherkin3,dg-ratiodata/gherkin3,curzona/gherkin3,araines/gherkin3,dirkrombauts/gherkin3,dirkrombauts/gherkin3,amaniak/gherkin3,cucumber/gherkin3,thiblahute/gherkin3,dg-ratiodata/gherkin3,dirkrombauts/gherkin3,hayd/gherkin3,moreirap/gherkin3,curzona/gherkin3,vincent-psarga/gherkin3,thetutlage/gherkin3,thetutlage/gherkin3,dg-ratiodata/gherkin3,chebizarro/gherkin3,Zearin/gherkin3,Zearin/gherkin3,pjlsergeant/gherkin,moreirap/gherkin3,hayd/gherkin3,dg-ratiodata/gherkin3,thiblahute/gherkin3,araines/gherkin3,moreirap/gherkin3,Zearin/gherkin3,SabotageAndi/gherkin,dirkrombauts/gherkin3,vincent-psarga/gherkin3,curzona/gherkin3,pjlsergeant/gherkin,dg-ratiodata/gherkin3,araines/gherkin3,Zearin/gherkin3,thiblahute/gherkin3,concertman/gherkin3,cucumber/gherkin3,hayd/gherkin3,pjlsergeant/gherkin,hayd/gherkin3,dg-ratiodata/gherkin3,SabotageAndi/gherkin,thetutlage/gherkin3,pjlsergeant/gherkin,moreirap/gherkin3,vincent-psarga/gherkin3,cucumber/gherkin3,araines/gherkin3,thiblahute/gherkin3,concertman/gherkin3,curzona/gherkin3,pjlsergeant/gherkin,moreirap/gherkin3,vincent-psarga/gherkin3,hayd/gherkin3,thiblahute/gherkin3,chebizarro/gherkin3,araines/gherkin3,Zearin/gherkin3,SabotageAndi/gherkin,araines/gherkin3,cucumber/gherkin3,pjlsergeant/gherkin,moreirap/gherkin3,pjlsergeant/gherkin,dirkrombauts/gherkin3,chebizarro/gherkin3,chebizarro/gherkin3,araines/gherkin3,chebizarro/gherkin3,Zearin/gherkin3,Zearin/gherkin3,pjlsergeant/gherkin
Gherkin/Ast/Examples.cs
Gherkin/Ast/Examples.cs
using System; using System.Collections.Generic; using System.Linq; namespace Gherkin.Ast { public class Examples : IHasLocation, IHasDescription, IHasRows, IHasTags { public IEnumerable<Tag> Tags { get; private set; } public Location Location { get; private set; } public string Keyword { get; private set; } public string Name { get; private set; } public string Description { get; private set; } public TableRow Header { get; private set; } public IEnumerable<TableRow> Body { get; private set; } public Examples(Tag[] tags, Location location, string keyword, string name, string description, TableRow header, TableRow[] body) { Tags = tags; Location = location; Keyword = keyword; Name = name; Description = description; Header = header; Body = body; } IEnumerable<TableRow> IHasRows.Rows { get { return new TableRow[] {Header}.Concat(Body); } } } }
using System; using System.Collections.Generic; using System.Linq; namespace Gherkin.Ast { public class Examples : IHasLocation, IHasDescription, IHasRows, IHasTags { public IEnumerable<Tag> Tags { get; private set; } public Location Location { get; private set; } public string Keyword { get; private set; } public string Name { get; private set; } public string Description { get; private set; } public TableRow Header { get; private set; } public IEnumerable<TableRow> Rows { get; private set; } public Examples(Tag[] tags, Location location, string keyword, string name, string description, TableRow header, TableRow[] rows) { Tags = tags; Location = location; Keyword = keyword; Name = name; Description = description; //TODO: fix Examples header/rows handling properly Header = null; Rows = new TableRow[] {header}.Concat(rows); } } }
mit
C#
0132d7f91f5ee31b0d771ff249a84c756a08bcbb
fix msg parser test case
tonyqus/toxy
Toxy.Test/MsgEmailParserTest.cs
Toxy.Test/MsgEmailParserTest.cs
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Toxy.Test { [TestFixture] public class MsgEmailParserTest { [Test] public void HtmlMsg_ReadTextTest() { string path = TestDataSample.GetEmailPath("Azure pricing and services updates.msg"); ParserContext context = new ParserContext(path); var parser = ParserFactory.CreateText(context); string result=parser.Parse(); Assert.IsNotNullOrEmpty(result); Assert.IsTrue(result.IndexOf("[From] Azure Team<AzureTeam@e-mail.microsoft.com>") >= 0); Assert.IsTrue(result.IndexOf("[To] tonyqux@hotmail.com")>0); Assert.IsTrue(result.IndexOf("[Subject] Azure pricing and services updates") > 0); Assert.IsFalse(result.IndexOf("[Cc]") > 0); Assert.IsFalse(result.IndexOf("[Bcc]") > 0); } [Test] public void PureTextMsg_ReadTextTest() { string path = TestDataSample.GetEmailPath("raw text mail demo.msg"); ParserContext context = new ParserContext(path); var parser = ParserFactory.CreateText(context); string result = parser.Parse(); Assert.IsNotNullOrEmpty(result); } [Test] public void HtmlMsg_ReadMsgEntityTest() { string path = TestDataSample.GetEmailPath("Azure pricing and services updates.msg"); ParserContext context = new ParserContext(path); var parser = ParserFactory.CreateEmail(context); var result = parser.Parse(); Assert.AreEqual("Azure Team<AzureTeam@e-mail.microsoft.com>",result.From); Assert.AreEqual(1, result.To.Count); Assert.AreEqual(0, result.Cc.Count); Assert.AreEqual(0, result.Bcc.Count); Assert.AreEqual("tonyqux@hotmail.com", result.To[0]); Assert.AreEqual("Azure pricing and services updates", result.Subject); Assert.IsNotNull(result.TextBody); Assert.IsNotNull(result.HtmlBody); } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Toxy.Test { [TestFixture] public class MsgEmailParserTest { [Test] public void HtmlMsg_ReadTextTest() { string path = TestDataSample.GetEmailPath("Azure pricing and services updates.msg"); ParserContext context = new ParserContext(path); var parser = ParserFactory.CreateText(context); string result=parser.Parse(); Assert.IsNotNullOrEmpty(result); Assert.IsTrue(result.IndexOf("[From] Azure Team<AzureTeam@e-mail.microsoft.com>") >= 0); Assert.IsTrue(result.IndexOf("[To] tonyqux@hotmail.com")>0); Assert.IsTrue(result.IndexOf("[Subject] Azure pricing and services updates") > 0); Assert.IsFalse(result.IndexOf("[Cc]") > 0); Assert.IsFalse(result.IndexOf("[Bcc]") > 0); } [Test] public void PureTextMsg_ReadTextTest() { string path = TestDataSample.GetEmailPath("raw text mail demo.msg"); ParserContext context = new ParserContext(path); var parser = ParserFactory.CreateText(context); string result = parser.Parse(); Assert.IsNotNullOrEmpty(result); } [Test] public void HtmlMsg_ReadMsgEntityTest() { string path = TestDataSample.GetEmailPath("Azure pricing and services updates.msg"); ParserContext context = new ParserContext(path); var parser = ParserFactory.CreateEmail(context); var result = parser.Parse(); Assert.AreEqual("Azure Team<AzureTeam@e-mail.microsoft.com>",result.From); Assert.AreEqual(1, result.To.Count); Assert.AreEqual(0, result.Cc.Count); Assert.AreEqual(0, result.Bcc.Count); Assert.AreEqual("tonyqux@hotmail.com", result.To[0]); Assert.AreEqual("Azure pricing and services updates", result.Subject); } } }
apache-2.0
C#
48f5ac2efe2408ad355246d48cbf02cb8ced3001
discard some params
destructurama/attributed
src/Destructurama.Attributed/Util/CacheEntry.cs
src/Destructurama.Attributed/Util/CacheEntry.cs
// Copyright 2015 Destructurama Contributors, Serilog Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Serilog.Core; using Serilog.Events; namespace Destructurama.Util { struct CacheEntry { public CacheEntry(Func<object, ILogEventPropertyValueFactory, LogEventPropertyValue> destructureFunc) { CanDestructure = true; DestructureFunc = destructureFunc ?? throw new ArgumentNullException(nameof(destructureFunc)); } CacheEntry(bool canDestructure, Func<object, ILogEventPropertyValueFactory, LogEventPropertyValue> destructureFunc) { CanDestructure = canDestructure; DestructureFunc = destructureFunc ?? throw new ArgumentNullException(nameof(destructureFunc)); } public bool CanDestructure { get; } public Func<object, ILogEventPropertyValueFactory, LogEventPropertyValue> DestructureFunc { get; } public static CacheEntry Ignore { get; } = new(false, (_, _) => null); } }
// Copyright 2015 Destructurama Contributors, Serilog Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Serilog.Core; using Serilog.Events; namespace Destructurama.Util { struct CacheEntry { public CacheEntry(Func<object, ILogEventPropertyValueFactory, LogEventPropertyValue> destructureFunc) { CanDestructure = true; DestructureFunc = destructureFunc ?? throw new ArgumentNullException(nameof(destructureFunc)); } CacheEntry(bool canDestructure, Func<object, ILogEventPropertyValueFactory, LogEventPropertyValue> destructureFunc) { CanDestructure = canDestructure; DestructureFunc = destructureFunc ?? throw new ArgumentNullException(nameof(destructureFunc)); } public bool CanDestructure { get; } public Func<object, ILogEventPropertyValueFactory, LogEventPropertyValue> DestructureFunc { get; } public static CacheEntry Ignore { get; } = new(false, (o, f) => null); } }
apache-2.0
C#
273519cd092b1fc0408ff61d68448811f7714981
bump version to 2.4.0.0
dwmkerr/sharpshell,dwmkerr/sharpshell,dwmkerr/sharpshell,dwmkerr/sharpshell
SharpShell/SharedAssemblyInfo.cs
SharpShell/SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Shared Assembly Information for all projects in SharpShell. [assembly: AssemblyCompany("Dave Kerr")] [assembly: AssemblyProduct("SharpShell")] [assembly: AssemblyCopyright("Copyright © Dave Kerr 2018")] // 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("2.4.0.0")] [assembly: AssemblyFileVersion("2.4.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Shared Assembly Information for all projects in SharpShell. [assembly: AssemblyCompany("Dave Kerr")] [assembly: AssemblyProduct("SharpShell")] [assembly: AssemblyCopyright("Copyright © Dave Kerr 2018")] // 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("2.3.2.0")] [assembly: AssemblyFileVersion("2.3.2.0")]
mit
C#
2820570e267f5036d50aac3e987c1d828a7ec908
Add a validation warning message. #281
Sitecore/Sitecore-Instance-Manager
src/SIM.Tool.Windows/Dialogs/GridEditor.xaml.cs
src/SIM.Tool.Windows/Dialogs/GridEditor.xaml.cs
using Sitecore.Diagnostics.Base; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SIM.Tool.Windows.Dialogs { /// <summary> /// Interaction logic for GridEditor.xaml /// </summary> public partial class GridEditor : Window { public GridEditor() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { GridEditorContext editContext = this.DataContext as GridEditorContext; Assert.ArgumentNotNull(editContext, nameof(editContext)); this.DescriptionText.Text = editContext.Description; } private void Ok_Click(object sender, RoutedEventArgs e) { var errors = (from c in (from object i in DataGrid.ItemsSource select DataGrid.ItemContainerGenerator.ContainerFromItem(i)) where c != null select Validation.GetHasError(c)) .FirstOrDefault(x => x); if (errors) { if (MessageBox.Show("There are validation errors. Data will not be saved.\nProceed anyway?", "Invalid data", MessageBoxButton.YesNo) == MessageBoxResult.No) { return; } } this.DialogResult = !errors; this.Close(); } private void Button_Click(object sender, RoutedEventArgs e) { Button b = sender as Button; GridEditorContext editContext = this.DataContext as GridEditorContext; editContext.GridItems.Remove(b.DataContext); this.DataGrid.DataContext = null; this.DataGrid.DataContext = editContext; } } internal class GridObjectValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { IValidateable entry = (value as BindingGroup).Items[0] as IValidateable; if (entry == null) { return ValidationResult.ValidResult; } string error = entry.ValidateAndGetError(); if (string.IsNullOrEmpty(error)) { return ValidationResult.ValidResult; } return new ValidationResult(false, error); } } }
using Sitecore.Diagnostics.Base; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace SIM.Tool.Windows.Dialogs { /// <summary> /// Interaction logic for GridEditor.xaml /// </summary> public partial class GridEditor : Window { public GridEditor() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { GridEditorContext editContext = this.DataContext as GridEditorContext; Assert.ArgumentNotNull(editContext, nameof(editContext)); this.DescriptionText.Text = editContext.Description; } private void Ok_Click(object sender, RoutedEventArgs e) { var errors = (from c in (from object i in DataGrid.ItemsSource select DataGrid.ItemContainerGenerator.ContainerFromItem(i)) where c != null select Validation.GetHasError(c)) .FirstOrDefault(x => x); this.DialogResult = !errors; this.Close(); } private void Button_Click(object sender, RoutedEventArgs e) { Button b = sender as Button; GridEditorContext editContext = this.DataContext as GridEditorContext; editContext.GridItems.Remove(b.DataContext); this.DataGrid.DataContext = null; this.DataGrid.DataContext = editContext; } } internal class GridObjectValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { IValidateable entry = (value as BindingGroup).Items[0] as IValidateable; if (entry == null) { return ValidationResult.ValidResult; } string error = entry.ValidateAndGetError(); if (string.IsNullOrEmpty(error)) { return ValidationResult.ValidResult; } return new ValidationResult(false, error); } } }
mit
C#
4bbf6f54cd8768779311db4c88e855ca23402ffd
Refactor MergeMessageParser.TryParse() related tests
openkas/GitVersion,TomGillen/GitVersion,ermshiperete/GitVersion,dazinator/GitVersion,GeertvanHorrik/GitVersion,alexhardwicke/GitVersion,dpurge/GitVersion,dpurge/GitVersion,onovotny/GitVersion,orjan/GitVersion,ermshiperete/GitVersion,Kantis/GitVersion,GitTools/GitVersion,Kantis/GitVersion,MarkZuber/GitVersion,TomGillen/GitVersion,dpurge/GitVersion,Kantis/GitVersion,pascalberger/GitVersion,DanielRose/GitVersion,pascalberger/GitVersion,anobleperson/GitVersion,ParticularLabs/GitVersion,asbjornu/GitVersion,DanielRose/GitVersion,RaphHaddad/GitVersion,onovotny/GitVersion,JakeGinnivan/GitVersion,ParticularLabs/GitVersion,orjan/GitVersion,onovotny/GitVersion,FireHost/GitVersion,anobleperson/GitVersion,distantcam/GitVersion,alexhardwicke/GitVersion,GitTools/GitVersion,Philo/GitVersion,anobleperson/GitVersion,GeertvanHorrik/GitVersion,openkas/GitVersion,asbjornu/GitVersion,gep13/GitVersion,pascalberger/GitVersion,Philo/GitVersion,MarkZuber/GitVersion,dpurge/GitVersion,DanielRose/GitVersion,dazinator/GitVersion,JakeGinnivan/GitVersion,FireHost/GitVersion,JakeGinnivan/GitVersion,gep13/GitVersion,ermshiperete/GitVersion,distantcam/GitVersion,RaphHaddad/GitVersion,JakeGinnivan/GitVersion,ermshiperete/GitVersion
Tests/MergeMessageParserTests.cs
Tests/MergeMessageParserTests.cs
using GitFlowVersion; using NUnit.Framework; [TestFixture] public class MergeMessageParserTests { [Test] public void MergeHotFix() { AssertMergeMessage("0.1.5", "Merge branch 'hotfix-0.1.5'\n"); } [Test] public void MergeHotFixWithLargeNumber() { AssertMergeMessage("10.10.50", "Merge branch 'hotfix-10.10.50'\n"); } [Test] public void MergeRelease() { AssertMergeMessage("0.2.0", "Merge branch 'release-0.2.0'\n"); } [Test] public void MergeReleaseNotStartingWithNumber() { AssertMergeMessage(null, "Merge branch 's'\n"); } [Test] public void MergeReleaseWithLargeNumber() { AssertMergeMessage("10.10.50", "Merge branch 'release-10.10.50'\n"); } [Test] public void MergeBadNamedHotfixBranch() { //TODO: possible make it a config option to support this AssertMergeMessage("4.0.3", "Merge branch '4.0.3'\n"); } [Test] public void TooManyTrailingCharacters() { AssertMergeMessage(null, "Merge branch 'develop' of github.com:Particular/NServiceBus into develop\n"); } private void AssertMergeMessage(string expectedVersion, string message) { string versionPart; var parsed = MergeMessageParser.TryParse(c, out versionPart); if (expectedVersion == null) { Assert.IsFalse(parsed); } else { Assert.IsTrue(parsed); Assert.AreEqual(expectedVersion, versionPart); } } }
using GitFlowVersion; using NUnit.Framework; [TestFixture] public class MergeMessageParserTests { [Test] public void MergeHotFix() { string versionPart; MergeMessageParser.TryParse("Merge branch 'hotfix-0.1.5'\n", out versionPart); Assert.AreEqual("0.1.5", versionPart); } [Test] public void MergeHotFixWithLargeNumber() { string versionPart; MergeMessageParser.TryParse("Merge branch 'hotfix-10.10.50'\n", out versionPart); Assert.AreEqual("10.10.50", versionPart); } [Test] public void MergeRelease() { string versionPart; MergeMessageParser.TryParse("Merge branch 'release-0.2.0'\n", out versionPart); Assert.AreEqual("0.2.0", versionPart); } [Test] public void MergeReleaseNotStartingWithNumber() { string versionPart; Assert.IsFalse(MergeMessageParser.TryParse("Merge branch 's'\n", out versionPart)); } [Test] public void MergeReleaseWithLargeNumber() { string versionPart; MergeMessageParser.TryParse("Merge branch 'release-10.10.50'\n", out versionPart); Assert.AreEqual("10.10.50", versionPart); } [Test] public void MergeBadNamedHotfixBranch() { //TODO: possible make it a config option to support this string versionPart; MergeMessageParser.TryParse("Merge branch '4.0.3'\n", out versionPart); Assert.AreEqual("4.0.3", versionPart); } [Test] public void TooManyTrailingCharacters() { string versionPart; Assert.IsFalse(MergeMessageParser.TryParse("Merge branch 'develop' of github.com:Particular/NServiceBus into develop\n", out versionPart)); } }
mit
C#
25e65cff2892c6e72cdd439e01643bc32ab8b854
Change offsets on stats text.
Sharparam/TetrisXNA
TetrisXNA/TetrisXNA/Constants.cs
TetrisXNA/TetrisXNA/Constants.cs
/* Copyright © 2013 by Adam Hellberg * * 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. */ namespace TetrisXNA { public static class Constants { public const int BlockWidth = 32; public const int BlockHeight = 32; public const int BlockAreaOffsetY = 0; public const int BlockAreaOffsetX = 32; public const int BlockAreaSizeX = 10; public const int BlockAreaSizeY = 24; public const int BlockAreaWidth = BlockAreaSizeX * BlockWidth; public const int BlockAreaHeight = BlockAreaSizeY * BlockHeight; public const int BlockAreaNextFieldX = 13; public const int BlockAreaNextFieldY = 3; public const int StatsOffsetX = 425; public const int StatsTimeOffsetY = 274; public const int StatsLevelOffsetX = 40; public const int StatsLevelOffsetY = 370; public const int StatsScoreOffsetY = 465; public const int StatsHighScoreOffsetY = 560; public const int LineClearPoints = 100; public const int UserDropPoints = 1; public const int GameOverScoreOffsetX = 320; public const int GameOverScoreOffsetY = 340; } }
/* Copyright © 2013 by Adam Hellberg * * 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. */ namespace TetrisXNA { public static class Constants { public const int BlockWidth = 32; public const int BlockHeight = 32; public const int BlockAreaOffsetY = 0; public const int BlockAreaOffsetX = 32; public const int BlockAreaSizeX = 10; public const int BlockAreaSizeY = 24; public const int BlockAreaWidth = BlockAreaSizeX * BlockWidth; public const int BlockAreaHeight = BlockAreaSizeY * BlockHeight; public const int BlockAreaNextFieldX = 13; public const int BlockAreaNextFieldY = 3; public const int StatsOffsetX = 430; public const int StatsTimeOffsetY = 274; public const int StatsLevelOffsetX = 35; public const int StatsLevelOffsetY = 370; public const int StatsScoreOffsetY = 465; public const int StatsHighScoreOffsetY = 560; public const int LineClearPoints = 100; public const int UserDropPoints = 1; public const int GameOverScoreOffsetX = 320; public const int GameOverScoreOffsetY = 340; } }
mit
C#
bf49420a1e08b6b533fe859c6c3b6f6a00389171
Update LoadingScreen more often to try to prevent windows from timing out on us and ghosting us.
AndrewBaker/magecrawl,jeongroseok/magecrawl
Trunk/MageCrawl/LoadingScreen.cs
Trunk/MageCrawl/LoadingScreen.cs
using System.Threading; using libtcodWrapper; using Magecrawl.GameUI; namespace Magecrawl { internal class LoadingScreen : System.IDisposable { private Timer m_timer; private RootConsole m_console; internal LoadingScreen(RootConsole console, string text) { console.DrawFrame(0, 0, UIHelper.ScreenWidth, UIHelper.ScreenHeight, true); console.PrintLineRect(text, UIHelper.ScreenWidth / 2, UIHelper.ScreenHeight / 2, UIHelper.ScreenWidth, UIHelper.ScreenHeight, LineAlignment.Center); console.Flush(); m_console = console; m_timer = new Timer(OnTick, null, 0, 50); } public void Dispose() { if (m_timer != null) m_timer.Dispose(); m_timer = null; } private void OnTick(object o) { m_console.Flush(); } } }
using System.Threading; using libtcodWrapper; using Magecrawl.GameUI; namespace Magecrawl { internal class LoadingScreen : System.IDisposable { private Timer m_timer; private RootConsole m_console; internal LoadingScreen(RootConsole console, string text) { console.DrawFrame(0, 0, UIHelper.ScreenWidth, UIHelper.ScreenHeight, true); console.PrintLineRect(text, UIHelper.ScreenWidth / 2, UIHelper.ScreenHeight / 2, UIHelper.ScreenWidth, UIHelper.ScreenHeight, LineAlignment.Center); console.Flush(); m_console = console; m_timer = new Timer(OnTick, null, 0, 2000); } public void Dispose() { if (m_timer != null) m_timer.Dispose(); m_timer = null; } private void OnTick(object o) { m_console.Flush(); } } }
bsd-2-clause
C#
48ecc237fe63b2e6fe0affd3c8ea879a0d925e69
Bump version.
Faithlife/System.Data.SQLite,Faithlife/System.Data.SQLite
SolutionVersion.cs
SolutionVersion.cs
using System.Reflection; [assembly: AssemblyVersion("2.12.3.0")] [assembly: AssemblyFileVersion("2.12.3.0")] [assembly: AssemblyInformationalVersion("2.12.3")]
using System.Reflection; [assembly: AssemblyVersion("2.12.2.0")] [assembly: AssemblyFileVersion("2.12.2.0")] [assembly: AssemblyInformationalVersion("2.12.2")]
mit
C#
07119b2df7bb7ae2fb660d0293beb8d64a425d2a
Add primary constructor
SICU-Stress-Measurement-System/frontend-cs
StressMeasurementSystem/Models/Patient.cs
StressMeasurementSystem/Models/Patient.cs
using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type {Home, Work, Other} public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private PhoneNumber _phoneNumber; private Email _email; #endregion #region Constructors public Patient(Name name, uint age, Organization organization, PhoneNumber phoneNumber, Email email) { _name = name; _age = age; _organization = organization; _phoneNumber = phoneNumber; _email = email; } #endregion } }
using System.Net.Mail; namespace StressMeasurementSystem.Models { public class Patient { #region Structs public struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } public struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } public struct PhoneNumber { public enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } public struct Email { public enum Type {Home, Work, Other} public MailAddress Address { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private uint _age; private Organization _organization; private PhoneNumber _phoneNumber; private Email _email; #endregion #region Constructors #endregion } }
apache-2.0
C#
59938835d439bbfb3b19b8240bcf310f8dfd7eb9
Update bundle config to match exampe in wiki page
M1chaelTran/T4MVC,jkonecki/T4MVC,payini/T4MVC,T4MVC/T4MVC,scott-xu/T4MVC,jkonecki/T4MVC,scott-xu/T4MVC,payini/T4MVC,T4MVC/T4MVC,M1chaelTran/T4MVC
T4MVCHostMvcApp/App_Start/BundleConfig.cs
T4MVCHostMvcApp/App_Start/BundleConfig.cs
using System.Diagnostics.CodeAnalysis; using System.Web.Optimization; namespace T4MVCHostMvcApp.App_Start { public static class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle(Links.Bundles.Scripts.jquery).Include("~/scripts/jquery-{version}.js")); bundles.Add(new StyleBundle(Links.Bundles.Styles.bootstrap).Include("~/styles/bootstrap*.css")); bundles.Add(new StyleBundle(Links.Bundles.Styles.common).Include(Links.Bundles.Content.Assets.Site_css)); } } } namespace Links { public static partial class Bundles { public static partial class Scripts { public static readonly string jquery = "~/scripts/jquery"; public static readonly string jqueryui = "~/scripts/jqueryui"; } public static partial class Styles { public static readonly string bootstrap = "~/styles/boostrap"; public static readonly string theme = "~/styles/theme"; public static readonly string common = "~/styles/common"; } } }
using System.Diagnostics.CodeAnalysis; using System.Web.Optimization; namespace T4MVCHostMvcApp.App_Start { public static class BundleConfig { // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725 [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0")] public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle(Links.Bundles.Content.Styles).Include( Links.Bundles.Content.Assets.Site_css )); } } } namespace Links { public static partial class Bundles { public static partial class Content { public const string Styles = "~/content/styles"; } } }
apache-2.0
C#
8b24b41ace566c9b55b00f39d98062411cfa41a5
Check the rows and columns
gldraphael/mg-ttt
TicTacToe/Board.cs
TicTacToe/Board.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; namespace TicTacToe { public class Board : DrawableGameComponent { private List<List<Tile>> tiles; public TileValue Winner { get; set; } = TileValue.EMPTY; public Board(Game game) : base(game) { } public override void Initialize() { base.Initialize(); initTiles(); tiles.ForEach(l => l.ForEach(t => Game.Components.Add(t))); } public override void Update(GameTime gameTime) { base.Update(gameTime); // Check the diagonals var gameOver = isSame(tiles[0][0], tiles[1][1], tiles[2][2]) || isSame(tiles[0][2], tiles[1][1], tiles[2][0]); // Check the columns for (int i = 0; i < 3; i++) { gameOver = gameOver || isSame(tiles[i].ToArray()); // Columns } // Check the rows for (int i = 0; i < 3; i++) { gameOver = gameOver || isSame(tiles.Select(x => x[i]).ToArray()); // Rows } if(gameOver) { Winner = GameState.Turn; } } protected override void UnloadContent() { tiles.ForEach(l => l.ForEach(t => Game.Components.Remove(t))); base.UnloadContent(); } public bool IsGameOver() { return Winner != TileValue.EMPTY; } private void initTiles() { tiles = new List<List<Tile>>(); for (int i = 0; i < 3; i++) { tiles.Add(new List<Tile>()); for (int j = 0; j < 3; j++) { tiles[i].Add(new Tile(this.Game) { Position = new Vector2(i * Tile.Width, j * Tile.Width) }); } } } private static bool isSame(params TileValue[] values) { if (values == null) return false; if (values.Length == 0) return true; var first = values[0] == TileValue.EMPTY ? TileValue.X : values[0]; // Condition because we don't want it to quit for all EMPTY values for (int i = 1; i < values.Length; i++) { if (values[i] != first) return false; } return true; } private static bool isSame(params Tile[] values) { return isSame(values.Select(x => x.Value).ToArray()); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; namespace TicTacToe { public class Board : DrawableGameComponent { private List<List<Tile>> tiles; public TileValue Winner { get; set; } = TileValue.EMPTY; public Board(Game game) : base(game) { } public override void Initialize() { base.Initialize(); initTiles(); tiles.ForEach(l => l.ForEach(t => Game.Components.Add(t))); } public override void Update(GameTime gameTime) { base.Update(gameTime); var gameOver = isSame(tiles[0][0], tiles[1][1], tiles[2][2]) // Diagonals || isSame(tiles[0][2], tiles[1][1], tiles[2][0]); if(gameOver) { Winner = GameState.Turn; } } protected override void UnloadContent() { tiles.ForEach(l => l.ForEach(t => Game.Components.Remove(t))); base.UnloadContent(); } public bool IsGameOver() { return Winner != TileValue.EMPTY; } private void initTiles() { tiles = new List<List<Tile>>(); for (int i = 0; i < 3; i++) { tiles.Add(new List<Tile>()); for (int j = 0; j < 3; j++) { tiles[i].Add(new Tile(this.Game) { Position = new Vector2(i * Tile.Width, j * Tile.Width) }); } } } private static bool isSame(params TileValue[] values) { if (values == null) return false; if (values.Length == 0) return true; var first = values[0] == TileValue.EMPTY ? TileValue.X : values[0]; // Condition because we don't want it to quit for all EMPTY values for (int i = 1; i < values.Length; i++) { if (values[i] != first) return false; } return true; } private static bool isSame(params Tile[] values) { return isSame(values.Select(x => x.Value).ToArray()); } } }
mit
C#
3465e2803a6670f99dbedea04667420502f8ff53
Bump verson for release
programcsharp/griddly,programcsharp/griddly,jehhynes/griddly,programcsharp/griddly,jehhynes/griddly,nickdevore/griddly,nickdevore/griddly
Build/CommonAssemblyInfo.cs
Build/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyProduct("Griddly")] [assembly: AssemblyCopyright("Copyright © 2015 Chris Hynes and Data Research Group")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.5.2")] [assembly: AssemblyFileVersion("1.5.2")] //[assembly: AssemblyInformationalVersion("1.4.5-editlyalpha2")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyProduct("Griddly")] [assembly: AssemblyCopyright("Copyright © 2015 Chris Hynes and Data Research Group")] [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.5.1")] [assembly: AssemblyFileVersion("1.5.1")] //[assembly: AssemblyInformationalVersion("1.4.5-editlyalpha2")]
mit
C#
ce3ea56e0c6f4996036558048a60585bf1fbb0a5
remove funky character
agrc/Crash-web,agrc/Crash-web,agrc/Crash-web,agrc/Crash-web
api/chart-function/Models/Row.cs
api/chart-function/Models/Row.cs
namespace chart_function.Models { public class Row { public Row() { } public Row(int occurrences, object label, string type) { Occurrences = occurrences; Label = label; Type = type; } public int Occurrences { get; set; } public object Label { get; set; } = string.Empty; public string Type { get; set; } = string.Empty; } }
namespace chart_function.Models { public class Row { public Row() { } public Row(int occurrences, object label, string type) { Occurrences = occurrences; Label = label; Type = type; } public int Occurrences { get; set; } public object Label { get; set; } = string.Empty; public string Type { get; set; } = string.Empty; } }
mit
C#
81b922ecb73f3c8dda8a08a4826eb4985d4eac9d
Use character class as transition key
jagrem/slang,jagrem/slang,jagrem/slang
slang/Lexing/Trees/Nodes/Transitions.cs
slang/Lexing/Trees/Nodes/Transitions.cs
using System.Collections.Generic; namespace slang.Lexing.Trees.Nodes { public class Transitions : Dictionary<Character,Transition> { } }
using System.Collections.Generic; namespace slang.Lexing.Trees.Nodes { public class Transitions : Dictionary<char,Node> { } }
mit
C#
81209c2697f33891e79e3c43dc5923fd7666c558
Bump version to 0.19.0
ar3cka/Journalist
src/SolutionInfo.cs
src/SolutionInfo.cs
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.19.0")] [assembly: AssemblyInformationalVersionAttribute("0.19.0")] [assembly: AssemblyFileVersionAttribute("0.19.0")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.19.0"; } }
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.18.0")] [assembly: AssemblyInformationalVersionAttribute("0.18.0")] [assembly: AssemblyFileVersionAttribute("0.18.0")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.18.0"; } }
apache-2.0
C#
030f85278c2c9df270d4a5a91f15a63c89c320e4
add internal api resource
bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core
src/Core/IdentityServer/ApiResources.cs
src/Core/IdentityServer/ApiResources.cs
using IdentityModel; using IdentityServer4.Models; using System.Collections.Generic; namespace Bit.Core.IdentityServer { public class ApiResources { public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { new ApiResource("api", new string[] { JwtClaimTypes.Name, JwtClaimTypes.Email, JwtClaimTypes.EmailVerified, "sstamp", // security stamp "premium", "device", "orgowner", "orgadmin", "orguser" }), new ApiResource("internal", new string[] { JwtClaimTypes.Subject }), new ApiResource("api.push", new string[] { JwtClaimTypes.Subject }), new ApiResource("api.licensing", new string[] { JwtClaimTypes.Subject }) }; } } }
using IdentityModel; using IdentityServer4.Models; using System.Collections.Generic; namespace Bit.Core.IdentityServer { public class ApiResources { public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { new ApiResource("api", new string[] { JwtClaimTypes.Name, JwtClaimTypes.Email, JwtClaimTypes.EmailVerified, "sstamp", // security stamp "premium", "device", "orgowner", "orgadmin", "orguser" }), new ApiResource("api.push", new string[] { JwtClaimTypes.Subject }), new ApiResource("api.licensing", new string[] { JwtClaimTypes.Subject }) }; } } }
agpl-3.0
C#
1e14696213a43e4765f2cad90c7f7c5b4f38ca3c
add null check
IdentityModel/IdentityModelv2,IdentityModel/IdentityModelv2,IdentityModel/IdentityModel,IdentityModel/IdentityModel,IdentityModel/IdentityModel2,IdentityModel/IdentityModel2
src/Internal/ClientCredentialsHelper.cs
src/Internal/ClientCredentialsHelper.cs
using IdentityModel.Client; using System; using System.Net.Http; namespace IdentityModel.Internal { internal static class ClientCredentialsHelper { internal static void PopulateClientCredentials( ProtocolRequest request, HttpRequestMessage httpRequest) { if (request.ClientId.IsPresent()) { if (request.ClientCredentialStyle == ClientCredentialStyle.AuthorizationHeader) { if (request.AuthorizationHeaderStyle == BasicAuthenticationHeaderStyle.Rfc6749) { httpRequest.SetBasicAuthenticationOAuth(request.ClientId, request.ClientSecret ?? ""); } else if (request.AuthorizationHeaderStyle == BasicAuthenticationHeaderStyle.Rfc2617) { httpRequest.SetBasicAuthentication(request.ClientId, request.ClientSecret ?? ""); } else { throw new InvalidOperationException("Unsupported basic authentication header style"); } } else if (request.ClientCredentialStyle == ClientCredentialStyle.PostBody) { request.Parameters.AddRequired(OidcConstants.TokenRequest.ClientId, request.ClientId); request.Parameters.AddOptional(OidcConstants.TokenRequest.ClientSecret, request.ClientSecret); } else { throw new InvalidOperationException("Unsupported client credential style"); } } if (request.ClientAssertion != null) { request.Parameters.AddOptional(OidcConstants.TokenRequest.ClientAssertionType, request.ClientAssertion.Type); request.Parameters.AddOptional(OidcConstants.TokenRequest.ClientAssertion, request.ClientAssertion.Value); } } } }
using IdentityModel.Client; using System; using System.Net.Http; namespace IdentityModel.Internal { internal static class ClientCredentialsHelper { internal static void PopulateClientCredentials( ProtocolRequest request, HttpRequestMessage httpRequest) { if (request.ClientId.IsPresent()) { if (request.ClientCredentialStyle == ClientCredentialStyle.AuthorizationHeader) { if (request.AuthorizationHeaderStyle == BasicAuthenticationHeaderStyle.Rfc6749) { httpRequest.SetBasicAuthenticationOAuth(request.ClientId, request.ClientSecret ?? ""); } else if (request.AuthorizationHeaderStyle == BasicAuthenticationHeaderStyle.Rfc2617) { httpRequest.SetBasicAuthentication(request.ClientId, request.ClientSecret ?? ""); } else { throw new InvalidOperationException("Unsupported basic authentication header style"); } } else if (request.ClientCredentialStyle == ClientCredentialStyle.PostBody) { request.Parameters.AddRequired(OidcConstants.TokenRequest.ClientId, request.ClientId); request.Parameters.AddOptional(OidcConstants.TokenRequest.ClientSecret, request.ClientSecret); } else { throw new InvalidOperationException("Unsupported client credential style"); } } request.Parameters.AddOptional(OidcConstants.TokenRequest.ClientAssertionType, request.ClientAssertion.Type); request.Parameters.AddOptional(OidcConstants.TokenRequest.ClientAssertion, request.ClientAssertion.Value); } } }
apache-2.0
C#
fd3705793c56c5bf3dd1941a69eeeee81fe3d771
Fix NH-2340
gliljas/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,lnu/nhibernate-core,hazzik/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ngbrown/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,RogerKratz/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core
src/NHibernate/Type/AbstractCharType.cs
src/NHibernate/Type/AbstractCharType.cs
using System; using System.Data; using NHibernate.SqlTypes; namespace NHibernate.Type { /// <summary> /// Common base class for <see cref="CharType" /> and <see cref="AnsiCharType" />. /// </summary> [Serializable] public abstract class AbstractCharType : PrimitiveType, IDiscriminatorType { public AbstractCharType(SqlType sqlType) : base(sqlType) {} public override object DefaultValue { get { throw new NotSupportedException("not a valid id type"); } } public override object Get(IDataReader rs, int index) { string dbValue = Convert.ToString(rs[index]); // The check of the Length is a workaround see NH-2340 if (dbValue.Length > 0) { return dbValue[0]; } return '\0'; // This line should never be executed } public override object Get(IDataReader rs, string name) { return Get(rs, rs.GetOrdinal(name)); } public override System.Type PrimitiveClass { get { return typeof(char); } } public override System.Type ReturnedClass { get { return typeof(char); } } public override void Set(IDbCommand cmd, object value, int index) { ((IDataParameter)cmd.Parameters[index]).Value = Convert.ToChar(value); } public override string ObjectToSQLString(object value, Dialect.Dialect dialect) { return '\'' + value.ToString() + '\''; } public virtual object StringToObject(string xml) { if (xml.Length != 1) throw new MappingException("multiple or zero characters found parsing string"); return xml[0]; } public override object FromStringValue(string xml) { return xml[0]; } } }
using System; using System.Data; using NHibernate.SqlTypes; namespace NHibernate.Type { /// <summary> /// Common base class for <see cref="CharType" /> and <see cref="AnsiCharType" />. /// </summary> [Serializable] public abstract class AbstractCharType : PrimitiveType, IDiscriminatorType { public AbstractCharType(SqlType sqlType) : base(sqlType) {} public override object DefaultValue { get { throw new NotSupportedException("not a valid id type"); } } public override object Get(IDataReader rs, int index) { string dbValue = Convert.ToString(rs[index]); if (dbValue == null) { return null; } else { return dbValue[0]; } } public override object Get(IDataReader rs, string name) { return Get(rs, rs.GetOrdinal(name)); } public override System.Type PrimitiveClass { get { return typeof(char); } } public override System.Type ReturnedClass { get { return typeof(char); } } public override void Set(IDbCommand cmd, object value, int index) { ((IDataParameter)cmd.Parameters[index]).Value = Convert.ToChar(value); } public override string ObjectToSQLString(object value, Dialect.Dialect dialect) { return '\'' + value.ToString() + '\''; } public virtual object StringToObject(string xml) { if (xml.Length != 1) throw new MappingException("multiple or zero characters found parsing string"); return xml[0]; } public override object FromStringValue(string xml) { return xml[0]; } } }
lgpl-2.1
C#
2e54d6a40682b0175ec796cb4d1f5a008b590956
make GetBaseUrl method virtual
SphtKr/JSONAPI.NET,JSONAPIdotNET/JSONAPI.NET,danshapir/JSONAPI.NET,SathishN/JSONAPI.NET
JSONAPI/Http/BaseUrlService.cs
JSONAPI/Http/BaseUrlService.cs
using System; using System.Net.Http; namespace JSONAPI.Http { /// <summary> /// Default implementation of IBaseUrlService /// </summary> public class BaseUrlService : IBaseUrlService { public virtual string GetBaseUrl(HttpRequestMessage requestMessage) { return new Uri(requestMessage.RequestUri.AbsoluteUri.Replace(requestMessage.RequestUri.PathAndQuery, String.Empty)).ToString(); } } }
using System; using System.Net.Http; namespace JSONAPI.Http { /// <summary> /// Default implementation of IBaseUrlService /// </summary> public class BaseUrlService : IBaseUrlService { public string GetBaseUrl(HttpRequestMessage requestMessage) { return new Uri(requestMessage.RequestUri.AbsoluteUri.Replace(requestMessage.RequestUri.PathAndQuery, String.Empty)).ToString(); } } }
mit
C#
0dc62903399db2dc21a4f1d78c4dae14cf9b3b85
Add a way to get the vendors from the Site entity.
AlexGhiondea/SmugMug.NET
src/SmugMugModel.v2/Types/SiteEntity.cs
src/SmugMugModel.v2/Types/SiteEntity.cs
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using SmugMug.v2.Authentication; using System.Threading.Tasks; namespace SmugMug.v2.Types { public class SiteEntity : SmugMugEntity { public SiteEntity(OAuthToken token) { _oauthToken = token; } public async Task<UserEntity> GetAuthenticatedUserAsync() { // !authuser string requestUri = string.Format("{0}!authuser", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityAsync<UserEntity>(requestUri); } public async Task<CatalogVendorEntity[]> GetVendors() { // /catalog!vendors string requestUri = string.Format("{0}/catalog!vendors", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityArrayAsync<CatalogVendorEntity>(requestUri); } public async Task<UserEntity[]> SearchForUser(string query) { // api/v2/user!search?q= string requestUri = string.Format("{0}/user!search?q={1}", SmugMug.v2.Constants.Addresses.SmugMugApi, query); return await RetrieveEntityArrayAsync<UserEntity>(requestUri); } } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using SmugMug.v2.Authentication; using System.Threading.Tasks; namespace SmugMug.v2.Types { public class SiteEntity : SmugMugEntity { public SiteEntity(OAuthToken token) { _oauthToken = token; } public async Task<UserEntity> GetAuthenticatedUserAsync() { // !authuser string requestUri = string.Format("{0}!authuser", SmugMug.v2.Constants.Addresses.SmugMugApi); return await RetrieveEntityAsync<UserEntity>(requestUri); } public async Task<UserEntity[]> SearchForUser(string query) { // api/v2/user!search?q= string requestUri = string.Format("{0}/user!search?q={1}", SmugMug.v2.Constants.Addresses.SmugMugApi, query); return await RetrieveEntityArrayAsync<UserEntity>(requestUri); } } }
mit
C#
13209028425ad8887ea29600a13c037d9c0b7060
Fix InMemory context for unit tests
jbe2277/waf
src/System.Waf/Samples/BookLibrary/BookLibrary.Library.Applications.Test/Services/MockDBContextService.cs
src/System.Waf/Samples/BookLibrary/BookLibrary.Library.Applications.Test/Services/MockDBContextService.cs
using System.ComponentModel.Composition; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Waf.BookLibrary.Library.Applications.Data; using Waf.BookLibrary.Library.Applications.Services; using Waf.BookLibrary.Library.Domain; namespace Test.BookLibrary.Library.Applications.Services { [Export, Export(typeof(IDBContextService))] public class MockDBContextService : IDBContextService { public DbContext GetBookLibraryContext(out string dataSourcePath) { dataSourcePath = @"C:\Test.db"; var options = new DbContextOptionsBuilder<BookLibraryContext>().UseInMemoryDatabase(databaseName: "TestDatabase", databaseRoot: new InMemoryDatabaseRoot()).Options; var context = new BookLibraryContext(options, modelBuilder => { modelBuilder.Entity<Book>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); modelBuilder.Entity<Person>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); }); return context; } } }
using System.ComponentModel.Composition; using Microsoft.EntityFrameworkCore; using Waf.BookLibrary.Library.Applications.Data; using Waf.BookLibrary.Library.Applications.Services; using Waf.BookLibrary.Library.Domain; namespace Test.BookLibrary.Library.Applications.Services { [Export, Export(typeof(IDBContextService))] public class MockDBContextService : IDBContextService { public DbContext GetBookLibraryContext(out string dataSourcePath) { dataSourcePath = @"C:\Test.db"; var options = new DbContextOptionsBuilder<BookLibraryContext>().UseInMemoryDatabase(databaseName: "TestDatabase").Options; var context = new BookLibraryContext(options, modelBuilder => { modelBuilder.Entity<Book>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); modelBuilder.Entity<Person>().Ignore(x => x.Errors).Ignore(x => x.HasErrors); }); return context; } } }
mit
C#
949ab4aa0c0bf634e6ff1a7156c8445aab6d353b
Remove dispose in destructor #406
mbdavid/LiteDB,masterdidoo/LiteDB,falahati/LiteDB,RytisLT/LiteDB,RytisLT/LiteDB,masterdidoo/LiteDB,falahati/LiteDB,89sos98/LiteDB,89sos98/LiteDB
LiteDB/Utils/LockControl.cs
LiteDB/Utils/LockControl.cs
using System; using System.Threading; namespace LiteDB { /// <summary> /// A class to control locking disposal. Can be a "new lock" - when a lock is not not coming from other lock state /// </summary> public class LockControl : IDisposable { private Action _dispose; internal LockControl(Action dispose) { _dispose = dispose; } public void Dispose() { if (_dispose != null) _dispose(); } } }
using System; using System.Threading; namespace LiteDB { /// <summary> /// A class to control locking disposal. Can be a "new lock" - when a lock is not not coming from other lock state /// </summary> public class LockControl : IDisposable { // dispose based on // https://lostechies.com/chrispatterson/2012/11/29/idisposable-done-right/ private Action _dispose; private bool _disposed; internal LockControl(Action dispose) { _dispose = dispose; } ~LockControl() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_disposed) return; _disposed = true; if (disposing) { } if (_dispose != null) _dispose(); } } }
mit
C#
f9a49930acf8af02eb69eb7c7fbcca71a4c603b4
check group
Trojaner25/Rocket-Safezone,Trojaner25/Rocket-Regions
Model/Flag/Impl/NoEquipFlag.cs
Model/Flag/Impl/NoEquipFlag.cs
using System.Collections.Generic; using Rocket.Unturned.Player; namespace RocketRegions.Model.Flag.Impl { public class NoEquipFlag : BoolFlag { public override string Description => "Allow/Disallow equipping items"; public override void UpdateState(List<UnturnedPlayer> players) { foreach (var player in players) { if(!player.Player.Equipment.isEquipped) continue; if(!GetValue<bool>(Region.GetGroup(player))) continue; player.Player.Equipment.dequip(); } } public override void OnRegionEnter(UnturnedPlayer player) { } public override void OnRegionLeave(UnturnedPlayer player) { } } }
using System.Collections.Generic; using Rocket.Unturned.Player; namespace RocketRegions.Model.Flag.Impl { public class NoEquipFlag : BoolFlag { public override string Description => "Allow/Disallow equipping items"; public override void UpdateState(List<UnturnedPlayer> players) { foreach (var player in players) { if(!player.Player.Equipment.isEquipped) continue; player.Player.Equipment.dequip(); } } public override void OnRegionEnter(UnturnedPlayer player) { } public override void OnRegionLeave(UnturnedPlayer player) { } } }
agpl-3.0
C#
9852165f4a8381c5dc1d8d80c81017b86490d034
Add log message for AppVeyor
laedit/vika
NVika/BuildServers/AppVeyor.cs
NVika/BuildServers/AppVeyor.cs
using System; using System.ComponentModel.Composition; using System.Net.Http; namespace NVika { internal sealed class AppVeyorBuildServer : IBuildServer { private readonly Logger _logger; public string Name { get { return "AppVeyor"; } } [ImportingConstructor] public AppVeyorBuildServer(Logger logger) { _logger = logger; } public bool CanApplyToCurrentContext() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR")); } public void WriteMessage(string message, string category, string details, string filename, string line, string offset, string projectName) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(Environment.GetEnvironmentVariable("APPVEYOR_API_URL")); _logger.Debug("AppVeyor API url: {0}", httpClient.BaseAddress); var responseTask = httpClient.PostAsJsonAsync("api/build/compilationmessages", new { Message = message, Category = category, Details = details, FileName = filename, Line = line, Column = offset, ProjectName = projectName }); responseTask.Wait(); _logger.Debug("AppVeyor CompilationMessage Response: {0}", responseTask.Result.StatusCode); _logger.Debug(responseTask.Result.Content.ReadAsStringAsync().Result); } } } }
using System; using System.ComponentModel.Composition; using System.Net.Http; namespace NVika { internal sealed class AppVeyorBuildServer : IBuildServer { private readonly Logger _logger; public string Name { get { return "AppVeyor"; } } [ImportingConstructor] public AppVeyorBuildServer(Logger logger) { _logger = logger; } public bool CanApplyToCurrentContext() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR")); } public void WriteMessage(string message, string category, string details, string filename, string line, string offset, string projectName) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(Environment.GetEnvironmentVariable("APPVEYOR_API_URL")); var response = httpClient.PostAsJsonAsync("api/build/compilationmessages", new { Message = message, Category = category, Details = details, FileName = filename, Line = line, Column = offset, ProjectName = projectName }).Result; _logger.Debug("AppVeyor CompilationMessage Response: {0}", response.StatusCode); _logger.Debug(response.Content.ReadAsStringAsync().Result); } } } }
apache-2.0
C#
63a42424ba7e4ffc3884c890e308256940b6174a
Remove the await/async
laedit/vika
NVika/BuildServers/AppVeyor.cs
NVika/BuildServers/AppVeyor.cs
using System; using System.ComponentModel.Composition; using System.Net.Http; namespace NVika { internal sealed class AppVeyorBuildServer : IBuildServer { private readonly Logger _logger; public string Name { get { return "AppVeyor"; } } [ImportingConstructor] public AppVeyorBuildServer(Logger logger) { _logger = logger; } public bool CanApplyToCurrentContext() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR")); } public void WriteMessage(string message, string category, string details, string filename, string line, string offset, string projectName) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(Environment.GetEnvironmentVariable("APPVEYOR_API_URL")); var response = httpClient.PostAsJsonAsync("api/build/compilationmessages", new { Message = message, Category = category, Details = details, FileName = filename, Line = line, Column = offset, ProjectName = projectName }).Result; _logger.Debug("AppVeyor CompilationMessage Response: {0}", response.StatusCode); _logger.Debug(response.Content.ReadAsStringAsync().Result); } } } }
using System; using System.ComponentModel.Composition; using System.Net.Http; namespace NVika { internal sealed class AppVeyorBuildServer : IBuildServer { private readonly Logger _logger; public string Name { get { return "AppVeyor"; } } [ImportingConstructor] public AppVeyorBuildServer(Logger logger) { _logger = logger; } public bool CanApplyToCurrentContext() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR")); } public async void WriteMessage(string message, string category, string details, string filename, string line, string offset, string projectName) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(Environment.GetEnvironmentVariable("APPVEYOR_API_URL")); var response = await httpClient.PostAsJsonAsync("api/build/compilationmessages", new { Message = message, Category = category, Details = details, FileName = filename, Line = line, Column = offset, ProjectName = projectName }); _logger.Debug("AppVeyor CompilationMessage Response: {0}", response.StatusCode); _logger.Debug(await response.Content.ReadAsStringAsync()); } } } }
apache-2.0
C#
01ab371c87284a06e04111c59694731635bdfbe4
add "Scroll speed" to ManiaSettingsSubsection
EVAST9919/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,johnneijzen/osu,EVAST9919/osu,smoogipoo/osu,naoey/osu,naoey/osu,ppy/osu,naoey/osu,ZLima12/osu,smoogipooo/osu,UselessToucan/osu,DrabWeb/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,peppy/osu,DrabWeb/osu,2yangk23/osu,johnneijzen/osu,DrabWeb/osu,UselessToucan/osu
osu.Game.Rulesets.Mania/ManiaSettingsSubsection.cs
osu.Game.Rulesets.Mania/ManiaSettingsSubsection.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Mania.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania { public class ManiaSettingsSubsection : RulesetSettingsSubsection { protected override string Header => "osu!mania"; public ManiaSettingsSubsection(ManiaRuleset ruleset) : base(ruleset) { } [BackgroundDependencyLoader] private void load() { var config = (ManiaConfigManager)Config; Children = new Drawable[] { new SettingsEnumDropdown<ManiaScrollingDirection> { LabelText = "Scrolling direction", Bindable = config.GetBindable<ManiaScrollingDirection>(ManiaSetting.ScrollDirection) }, new SettingsSlider<double, TimeSlider> { LabelText = "Scroll speed", TransferValueOnCommit = true, Bindable = config.GetBindable<double>(ManiaSetting.ScrollTime) }, }; } private class TimeSlider : OsuSliderBar<double> { public override string TooltipText => Current.Value.ToString("N0") + "ms"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Overlays.Settings; using osu.Game.Rulesets.Mania.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania { public class ManiaSettingsSubsection : RulesetSettingsSubsection { protected override string Header => "osu!mania"; public ManiaSettingsSubsection(ManiaRuleset ruleset) : base(ruleset) { } [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { new SettingsEnumDropdown<ManiaScrollingDirection> { LabelText = "Scrolling direction", Bindable = ((ManiaConfigManager)Config).GetBindable<ManiaScrollingDirection>(ManiaSetting.ScrollDirection) } }; } } }
mit
C#
9cb9ef5c563316df57f7a49400359463ead3f49b
Refactor the menu's max height to be a property
ppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu
osu.Game/Overlays/Settings/SettingsEnumDropdown.cs
osu.Game/Overlays/Settings/SettingsEnumDropdown.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 osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsEnumDropdown<T> : SettingsDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new DropdownControl(); protected new class DropdownControl : OsuEnumDropdown<T> { protected virtual int MenuMaxHeight => 200; public DropdownControl() { Margin = new MarginPadding { Top = 5 }; RelativeSizeAxes = Axes.X; } protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = MenuMaxHeight); } } }
// 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 osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings { public class SettingsEnumDropdown<T> : SettingsDropdown<T> where T : struct, Enum { protected override OsuDropdown<T> CreateDropdown() => new DropdownControl(); protected new class DropdownControl : OsuEnumDropdown<T> { public DropdownControl() { Margin = new MarginPadding { Top = 5 }; RelativeSizeAxes = Axes.X; } protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 200); } } }
mit
C#
a2ac3bcc7c1f460b539c976328b76d59426ed245
Test commit/push
joemoorhouse/vector-accelerator
VectorAccelerator.Launcher/Program.cs
VectorAccelerator.Launcher/Program.cs
using System; using System.Threading; using VectorAccelerator.Tests; namespace VectorAccelerator.Launcher { class Program { static void Main(string[] args) { var swapAADTest = new BasicSwapAADTest(); swapAADTest.TestEndToEnd(); //var mult = new MultiplyAggregateTests(); //mult.SimpleTest(); } } }
using System; using System.Threading; using VectorAccelerator.Tests; namespace VectorAccelerator.Launcher { class Program { static void Main(string[] args) { var swapAADTest = new BasicSwapAADTest(); swapAADTest.TestEndToEnd(); //var mult = new MultiplyAggregateTests(); //mult.SimpleTest(); } } }
mit
C#
8d78fb8d19c663a9eedea94248db5640ca605145
Revert to DateTime.Now.Ticks instead of Mono internal dependency
spicypixel/cs-concurrency-kit,spicypixel/cs-concurrency-kit,spicypixel/cs-concurrency-kit
System.Threading/System.Threading/Watch.cs
System.Threading/System.Threading/Watch.cs
// Task.cs // // Copyright (c) 2008 Jérémie "Garuma" Laval // // 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. // // #if NET_4_0 using System; using System.Reflection; namespace System.Threading { internal struct Watch { // Do not rely on Mono internals #if false static readonly MethodInfo GetTimeMonotonicMethodInfo = typeof(DateTime).GetMethod("GetTimeMonotonic", BindingFlags.NonPublic | BindingFlags.Static); // Spicy Pixel: This appears to work on AOT too and is much faster than dynamic invoke. static readonly Func<long> GetTimeMonotonic = (Func<long>)Delegate.CreateDelegate( typeof(Func<long>), GetTimeMonotonicMethodInfo); #endif long startTicks; public static Watch StartNew () { Watch watch = new Watch (); watch.Start (); return watch; } public void Start () { startTicks = TicksNow (); } public void Stop () { } public long ElapsedMilliseconds { get { return (TicksNow () - startTicks) / TimeSpan.TicksPerMillisecond; } } static long TicksNow () { // Spicy Pixel: No access to internal Mono method except by reflection. // // Monotonic time cannot be set and represents a time in ticks since // some unspecified starting point. It avoids drift due to system // time updates (which DateTime.Now.Ticks does not). // // return DateTime.GetTimeMonotonic (); return DateTime.Now.Ticks; // return Watch.GetTimeMonotonic(); } } } #endif
// Task.cs // // Copyright (c) 2008 Jérémie "Garuma" Laval // // 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. // // #if NET_4_0 using System; using System.Reflection; namespace System.Threading { internal struct Watch { static readonly MethodInfo GetTimeMonotonicMethodInfo = typeof(DateTime).GetMethod("GetTimeMonotonic", BindingFlags.NonPublic | BindingFlags.Static); // Spicy Pixel: This appears to work on AOT too and is much faster than dynamic invoke. static readonly Func<long> GetTimeMonotonic = (Func<long>)Delegate.CreateDelegate( typeof(Func<long>), GetTimeMonotonicMethodInfo); long startTicks; public static Watch StartNew () { Watch watch = new Watch (); watch.Start (); return watch; } public void Start () { startTicks = TicksNow (); } public void Stop () { } public long ElapsedMilliseconds { get { return (TicksNow () - startTicks) / TimeSpan.TicksPerMillisecond; } } static long TicksNow () { // Spicy Pixel: No access to internal Mono method except by reflection. // // Monotonic time cannot be set and represents a time in ticks since // some unspecified starting point. It avoids drift due to system // time updates (which DateTime.Now.Ticks does not). // // return DateTime.GetTimeMonotonic (); // return DateTime.Now.Ticks; return Watch.GetTimeMonotonic(); } } } #endif
mit
C#
4235ba5fc35fa9cf7fde0791f998df461464de89
Fix PasswordEntry background color
lytico/xwt,TheBrainTech/xwt,hwthomas/xwt,mono/xwt,antmicro/xwt,hamekoz/xwt,residuum/xwt,cra0zy/xwt,akrisiun/xwt
Xwt.XamMac/Xwt.Mac/PasswordEntryBackend.cs
Xwt.XamMac/Xwt.Mac/PasswordEntryBackend.cs
using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; #else using Foundation; using AppKit; #endif namespace Xwt.Mac { public class PasswordEntryBackend : ViewBackend<NSView, IPasswordEntryEventSink>, IPasswordEntryBackend { public PasswordEntryBackend () { } public override void Initialize () { base.Initialize (); var view = new CustomSecureTextField (EventSink, ApplicationContext); ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)view) { DrawsBackground = false }; } protected override void OnSizeToFit () { Container.SizeToFit (); } CustomAlignedContainer Container { get { return (CustomAlignedContainer)base.Widget; } } public new NSSecureTextField Widget { get { return (NSSecureTextField)Container.Child; } } protected override Size GetNaturalSize () { var s = base.GetNaturalSize (); return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height); } public string Password { get { return Widget.StringValue; } set { Widget.StringValue = value ?? string.Empty; } } public System.Security.SecureString SecurePassword { get { return null; } } public string PlaceholderText { get { return ((NSTextFieldCell)Widget.Cell).PlaceholderString; } set { ((NSTextFieldCell)Widget.Cell).PlaceholderString = value ?? string.Empty; } } public override Drawing.Color BackgroundColor { get { return Widget.BackgroundColor.ToXwtColor (); } set { Widget.BackgroundColor = value.ToNSColor (); Widget.Cell.DrawsBackground = true; Widget.Cell.BackgroundColor = value.ToNSColor (); } } } class CustomSecureTextField : NSSecureTextField, IViewObject { IPasswordEntryEventSink eventSink; ApplicationContext context; public CustomSecureTextField (IPasswordEntryEventSink eventSink, ApplicationContext context) { this.context = context; this.eventSink = eventSink; Activated += (sender, e) => context.InvokeUserCode (delegate { eventSink.OnActivated (); }); } public NSView View { get { return this; } } public ViewBackend Backend { get; set; } public override void DidChange (NSNotification notification) { base.DidChange (notification); context.InvokeUserCode (delegate { eventSink.OnChanged (); }); } } }
using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using MonoMac.Foundation; using MonoMac.AppKit; #else using Foundation; using AppKit; #endif namespace Xwt.Mac { public class PasswordEntryBackend : ViewBackend<NSView, IPasswordEntryEventSink>, IPasswordEntryBackend { public PasswordEntryBackend () { } public override void Initialize () { base.Initialize (); var view = new CustomSecureTextField (EventSink, ApplicationContext); ViewObject = new CustomAlignedContainer (EventSink, ApplicationContext, (NSView)view); } protected override void OnSizeToFit () { Container.SizeToFit (); } CustomAlignedContainer Container { get { return (CustomAlignedContainer)base.Widget; } } public new NSSecureTextField Widget { get { return (NSSecureTextField)Container.Child; } } protected override Size GetNaturalSize () { var s = base.GetNaturalSize (); return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height); } public string Password { get { return Widget.StringValue; } set { Widget.StringValue = value ?? string.Empty; } } public System.Security.SecureString SecurePassword { get { return null; } } public string PlaceholderText { get { return ((NSTextFieldCell)Widget.Cell).PlaceholderString; } set { ((NSTextFieldCell)Widget.Cell).PlaceholderString = value ?? string.Empty; } } } class CustomSecureTextField : NSSecureTextField, IViewObject { IPasswordEntryEventSink eventSink; ApplicationContext context; public CustomSecureTextField (IPasswordEntryEventSink eventSink, ApplicationContext context) { this.context = context; this.eventSink = eventSink; Activated += (sender, e) => context.InvokeUserCode (delegate { eventSink.OnActivated (); }); } public NSView View { get { return this; } } public ViewBackend Backend { get; set; } public override void DidChange (NSNotification notification) { base.DidChange (notification); context.InvokeUserCode (delegate { eventSink.OnChanged (); }); } } }
mit
C#
23fa4c35f38e23f43f0a810d5c66381a8a960183
Make sure we set control and shift correctly in Keyboard
jlewin/agg-sharp,larsbrubaker/agg-sharp,MatterHackers/agg-sharp
Gui/Keyboard.cs
Gui/Keyboard.cs
using System.Collections.Generic; namespace MatterHackers.Agg.UI { public static class Keyboard { private static Dictionary<Keys, bool> downStates = new Dictionary<Keys, bool>(); public static bool IsKeyDown(Keys key) { if (downStates.ContainsKey(key)) { return downStates[key]; } return false; } public static void SetKeyDownState(Keys key, bool down) { if (downStates.ContainsKey(key)) { downStates[key] = down; } else { downStates.Add(key, down); } switch(key) { case Keys.LControlKey: case Keys.RControlKey: case Keys.ControlKey: SetKeyDownState(Keys.Control, down); break; case Keys.LShiftKey: case Keys.RShiftKey: case Keys.ShiftKey: SetKeyDownState(Keys.Shift, down); break; } } } }
using System.Collections.Generic; namespace MatterHackers.Agg.UI { public static class Keyboard { private static Dictionary<Keys, bool> downStates = new Dictionary<Keys, bool>(); public static bool IsKeyDown(Keys key) { if (downStates.ContainsKey(key)) { return downStates[key]; } return false; } public static void SetKeyDownState(Keys key, bool down) { if (downStates.ContainsKey(key)) { downStates[key] = down; } else { downStates.Add(key, down); } } } }
bsd-2-clause
C#
01ab6e0572b195a9acc796085dd6a2c3b677d7d9
Reorder fields in the inspector
bartlomiejwolk/HealthBar
HealthBarGUI.cs
HealthBarGUI.cs
// Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com) // // This file is part of the HealthBar extension for Unity. Licensed under the // MIT license. See LICENSE file in the project root folder. Based on HealthBar // component made by Zero3Growlithe (zero3growlithe@gmail.com). using UnityEngine; namespace HealthBarEx { [System.Serializable] // todo encapsulate fields public class HealthBarGUI { [HideInInspector] public float alpha; public bool displayValue = true; public PositionModes positionMode; public Texture texture; public Color addedHealth; public Color availableHealth; public Color displayedValue; public Color drainedHealth; public float animationSpeed = 3f; public float transitionSpeed = 5f; public float transitionDelay = 3f; public float visibility = 1; public int width = 100; public int height = 30; public Vector2 offset = new Vector2(0, 30); public Vector2 valueOffset = new Vector2(0, 30); public GUIStyle textStyle; public enum PositionModes { Fixed, Center }; } }
// Copyright (c) 2015 Bartlomiej Wolk (bartlomiejwolk@gmail.com) // // This file is part of the HealthBar extension for Unity. Licensed under the // MIT license. See LICENSE file in the project root folder. Based on HealthBar // component made by Zero3Growlithe (zero3growlithe@gmail.com). using UnityEngine; namespace HealthBarEx { [System.Serializable] // todo encapsulate fields public class HealthBarGUI { public Color addedHealth; [HideInInspector] public float alpha; public float animationSpeed = 3f; public Color availableHealth; public Color displayedValue; public bool displayValue = true; public Color drainedHealth; public int height = 30; public Vector2 offset = new Vector2(0, 30); public PositionModes positionMode; public GUIStyle textStyle; public Texture texture; public float transitionDelay = 3f; public float transitionSpeed = 5f; public Vector2 valueOffset = new Vector2(0, 30); public float visibility = 1; public int width = 100; public enum PositionModes { Fixed, Center }; } }
mit
C#
117a9802f8208f50fa47aa4aac38f7cc686c01db
add xml comments.
mitchelsellers/Dnn.Platform,robsiera/Dnn.Platform,EPTamminga/Dnn.Platform,valadas/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,bdukes/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,EPTamminga/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,robsiera/Dnn.Platform,nvisionative/Dnn.Platform,RichardHowells/Dnn.Platform,dnnsoftware/Dnn.Platform,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,RichardHowells/Dnn.Platform,EPTamminga/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,nvisionative/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,mitchelsellers/Dnn.Platform,robsiera/Dnn.Platform
src/Dnn.EditBar.Library/Items/BaseMenuItem.cs
src/Dnn.EditBar.Library/Items/BaseMenuItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Dnn.EditBar.Library.Items { [DataContract] public abstract class BaseMenuItem { /// <summary> /// the menu item name /// </summary> [DataMember(Name = "name")] public abstract string Name { get; } /// <summary> /// the content will render as the menu item. /// </summary> [DataMember(Name = "button")] public abstract string Button { get; } /// <summary> /// the css class for menu item. /// </summary> [DataMember(Name = "cssClass")] public abstract string CssClass { get; } /// <summary> /// parent which the menu item will stay in. /// currently we have LeftMenu and RightMenu defined in edit bar. /// if the edit bar modified and add new position, this value can extend with more values. /// </summary> [DataMember(Name = "parent")] public abstract string Parent { get; } /// <summary> /// the menu order. /// </summary> [DataMember(Name = "order")] public virtual int Order { get; } = 0; /// <summary> /// the menu script path, which will handle the button click event. /// </summary> [DataMember(Name = "loader")] public abstract string Loader { get; } /// <summary> /// menu custom settings. /// </summary> [DataMember(Name = "settings")] public virtual IDictionary<string, object> Settings { get; } = new Dictionary<string, object>(); /// <summary> /// whether the menu is visible in current context. /// </summary> /// <returns></returns> public virtual bool Visible() { return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Dnn.EditBar.Library.Items { [DataContract] public abstract class BaseMenuItem { [DataMember(Name = "name")] public abstract string Name { get; } [DataMember(Name = "button")] public abstract string Button { get; } [DataMember(Name = "cssClass")] public abstract string CssClass { get; } [DataMember(Name = "parent")] public abstract string Parent { get; } [DataMember(Name = "order")] public virtual int Order { get; } = 0; [DataMember(Name = "loader")] public abstract string Loader { get; } [DataMember(Name = "settings")] public virtual IDictionary<string, object> Settings { get; } = new Dictionary<string, object>(); public virtual bool Visible() { return true; } } }
mit
C#
095dba97963a65d11127ecddc33185b12ee7e0db
Test QueryDispatcher
ewancoder/ewancoder-ddd
Ewancoder.DDD.Tests/CommandDispatcherTests.cs
Ewancoder.DDD.Tests/CommandDispatcherTests.cs
namespace Ewancoder.DDD.Tests { using Moq; using Xunit; using Exceptions; using Interfaces; public sealed class QueryDispatcherTests { private readonly Mock<IQueryHandlerFactory> _queryHandlerFactory = new Mock<IQueryHandlerFactory>(); private readonly QueryDispatcher _sut; public QueryDispatcherTests() { _sut = new QueryDispatcher(_queryHandlerFactory.Object); } [Fact] public void ShouldThrowIfQueryHandlerNotFound() { Assert.Throws<UnregisteredQueryHandlerException>( () => _sut.Dispatch<TestQuery<object>, object>( new TestQuery<object>())); } [Fact] public void ShouldHandleQuery() { var testQuery = new TestQuery<object>(); object value = new object(); var testQueryHandler = new Mock<IQueryHandler<TestQuery<object>, object>>(); testQueryHandler.Setup(h => h.Handle(testQuery)) .Returns(value); _queryHandlerFactory.Setup(f => f.Resolve<TestQuery<object>, object>()) .Returns(testQueryHandler.Object); var result =_sut.Dispatch<TestQuery<object>, object>(testQuery); Assert.Equal(value, result); } } public sealed class CommandDispatcherTests { private readonly Mock<ICommandHandlerFactory> _commandHandlerFactory = new Mock<ICommandHandlerFactory>(); private readonly CommandDispatcher _sut; public CommandDispatcherTests() { _sut = new CommandDispatcher(_commandHandlerFactory.Object); } [Fact] public void ShouldThrowIfCommandHandlerNotFound() { Assert.Throws<UnregisteredCommandHandlerException>( () => _sut.Dispatch(new TestCommand())); } [Fact] public void ShouldHandleCommand() { var testCommand = new TestCommand(); var testCommandHandler = new TestCommandHandler<TestCommand>(); _commandHandlerFactory.Setup(f => f.Resolve<TestCommand>()) .Returns(testCommandHandler); _sut.Dispatch(testCommand); Assert.Equal(testCommand, testCommandHandler.Command); } } }
namespace Ewancoder.DDD.Tests { using Moq; using Xunit; using Exceptions; using Interfaces; public sealed class CommandDispatcherTests { private readonly Mock<ICommandHandlerFactory> _commandHandlerFactory = new Mock<ICommandHandlerFactory>(); private readonly CommandDispatcher _sut; public CommandDispatcherTests() { _sut = new CommandDispatcher(_commandHandlerFactory.Object); } [Fact] public void ShouldThrowIfCommandHandlerNotFound() { Assert.Throws<UnregisteredCommandHandlerException>( () => _sut.Dispatch(new TestCommand())); } [Fact] public void ShouldHandleCommand() { var testCommand = new TestCommand(); var testCommandHandler = new TestCommandHandler<TestCommand>(); _commandHandlerFactory.Setup(f => f.Resolve<TestCommand>()) .Returns(testCommandHandler); _sut.Dispatch(testCommand); Assert.Equal(testCommand, testCommandHandler.Command); } } }
mit
C#
273ad353b6df229192d8606bd57c608be71f133c
Update ICustomSerializer.cs
tiksn/TIKSN-Framework
TIKSN.Core/Serialization/ICustomSerializer.cs
TIKSN.Core/Serialization/ICustomSerializer.cs
namespace TIKSN.Serialization { /// <summary> /// Custom (specialized or typed) serializer interface /// </summary> /// <typeparam name="TSerial">Type to serialize to, usually string or byte array</typeparam> public interface ICustomSerializer<TSerial, TModel> { /// <summary> /// Serialize <typeparamref name="TModel"/> to <typeparamref name="TSerial"/> type /// </summary> /// <param name="obj"></param> /// <returns></returns> TSerial Serialize(TModel obj); } }
namespace TIKSN.Serialization { /// <summary> /// Custom (specialized or typed) serializer interface /// </summary> /// <typeparam name="TSerial">Type to serialize to, usually string or byte array</typeparam> public interface ICustomSerializer<TSerial, TModel> { /// <summary> /// Serialize <typeparamref name="TModel"/> to <typeparamref name="TSerial"/> type /// </summary> /// <param name="obj"></param> /// <returns></returns> TSerial Serialize(TModel obj); } }
mit
C#
acd21ef8eda89dfc0844576af4263413f2ce9b34
Update GetRelativeTime.cs
BlarghLabs/MoarUtils
commands/time/GetRelativeTime.cs
commands/time/GetRelativeTime.cs
using System; namespace MoarUtils.commands.time { public static class GetRelativeTime { public static string Execute(DateTime dt) { const int SECOND = 1; const int MINUTE = 60 * SECOND; const int HOUR = 60 * MINUTE; const int DAY = 24 * HOUR; const int MONTH = 30 * DAY; var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks); var delta = Math.Abs(ts.TotalSeconds); if (ts.TotalSeconds < 0) return " just now"; if (delta < 1 * MINUTE) return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago"; if (delta < 2 * MINUTE) return "a minute ago"; if (delta < 45 * MINUTE) return ts.Minutes + " minutes ago"; if (delta < 90 * MINUTE) return "an hour ago"; if (delta < 24 * HOUR) return ts.Hours + " hours ago"; if (delta < 48 * HOUR) return "yesterday"; if (delta < 30 * DAY) return ts.Days + " days ago"; if (delta < 12 * MONTH) { var months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); var monthsDouble = (double)ts.Days / (double)30; return monthsDouble <= 1 ? "one month ago" : monthsDouble.ToString("n1") + " months ago" ; } else { var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); var yearDouble = (double)ts.Days / (double)365; return yearDouble <= 1 ? "one year ago" : yearDouble.ToString("n1") + " years ago"; } } public static string ExecuteFromNullable(DateTime? dt) { if (!dt.HasValue) { return ""; } return Execute(dt.Value); } } }
using System; namespace MoarUtils.commands.time { public static class GetRelativeTime { public static string Execute(DateTime dt) { const int SECOND = 1; const int MINUTE = 60 * SECOND; const int HOUR = 60 * MINUTE; const int DAY = 24 * HOUR; const int MONTH = 30 * DAY; var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks); var delta = Math.Abs(ts.TotalSeconds); if (ts.TotalSeconds < 0) return " just now"; if (delta < 1 * MINUTE) return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago"; if (delta < 2 * MINUTE) return "a minute ago"; if (delta < 45 * MINUTE) return ts.Minutes + " minutes ago"; if (delta < 90 * MINUTE) return "an hour ago"; if (delta < 24 * HOUR) return ts.Hours + " hours ago"; if (delta < 48 * HOUR) return "yesterday"; if (delta < 30 * DAY) return ts.Days + " days ago"; if (delta < 12 * MONTH) { var months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1 ? "one month ago" : months + " months ago"; } else { var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1 ? "one year ago" : years + " years ago"; } } public static string ExecuteFromNullable(DateTime? dt) { if (!dt.HasValue) { return ""; } return Execute(dt.Value); } } }
mit
C#
e6fdbdc6e9bb5a63d84440316680aef6741b27d1
remove unused usings
BITechnologies/boo,rmartinho/boo,KingJiangNet/boo,drslump/boo,bamboo/boo,Unity-Technologies/boo,BITechnologies/boo,wbardzinski/boo,rmartinho/boo,KidFashion/boo,BITechnologies/boo,Unity-Technologies/boo,BitPuffin/boo,wbardzinski/boo,boo-lang/boo,drslump/boo,boo-lang/boo,scottstephens/boo,bamboo/boo,hmah/boo,rmartinho/boo,scottstephens/boo,Unity-Technologies/boo,KidFashion/boo,BillHally/boo,rmboggs/boo,wbardzinski/boo,rmboggs/boo,hmah/boo,KidFashion/boo,scottstephens/boo,bamboo/boo,rmboggs/boo,rmartinho/boo,BitPuffin/boo,KingJiangNet/boo,KingJiangNet/boo,drslump/boo,Unity-Technologies/boo,scottstephens/boo,drslump/boo,KingJiangNet/boo,bamboo/boo,rmartinho/boo,wbardzinski/boo,BillHally/boo,BillHally/boo,rmboggs/boo,BitPuffin/boo,hmah/boo,BITechnologies/boo,bamboo/boo,bamboo/boo,rmboggs/boo,BillHally/boo,BITechnologies/boo,KidFashion/boo,drslump/boo,boo-lang/boo,KingJiangNet/boo,rmboggs/boo,hmah/boo,drslump/boo,Unity-Technologies/boo,hmah/boo,drslump/boo,BITechnologies/boo,hmah/boo,boo-lang/boo,scottstephens/boo,KingJiangNet/boo,bamboo/boo,BITechnologies/boo,rmartinho/boo,hmah/boo,boo-lang/boo,BillHally/boo,wbardzinski/boo,wbardzinski/boo,boo-lang/boo,KingJiangNet/boo,boo-lang/boo,wbardzinski/boo,BillHally/boo,KingJiangNet/boo,BitPuffin/boo,rmboggs/boo,rmartinho/boo,scottstephens/boo,scottstephens/boo,BitPuffin/boo,KidFashion/boo,Unity-Technologies/boo,hmah/boo,BitPuffin/boo,boo-lang/boo,Unity-Technologies/boo,BitPuffin/boo,rmartinho/boo,hmah/boo,KidFashion/boo,rmboggs/boo,wbardzinski/boo,BitPuffin/boo,BillHally/boo,KidFashion/boo,Unity-Technologies/boo,BITechnologies/boo,scottstephens/boo
src/Boo.Lang.Compiler/Pipelines/CompileToMemory.cs
src/Boo.Lang.Compiler/Pipelines/CompileToMemory.cs
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Boo.Lang.Compiler.Steps; namespace Boo.Lang.Compiler.Pipelines { public class CompileToMemory : Compile { public CompileToMemory() { Add(new EmitAssembly()); } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion namespace Boo.Lang.Compiler.Pipelines { using System; using Boo.Lang.Compiler.Steps; public class CompileToMemory : Compile { public CompileToMemory() { Add(new EmitAssembly()); } } }
bsd-3-clause
C#
c9cd5eb99be2e1c50b031d2fdc9fbcf2e43dc1cd
fix some invalid parameters
defmys/Unity3D-Raven-CS
Assets/Unity3D-Raven-CS/Scripts/MessagePacket.cs
Assets/Unity3D-Raven-CS/Scripts/MessagePacket.cs
using System; using System.Collections.Generic; using UnityEngine; namespace Unity3DRavenCS { [Serializable] public class MessagePacket { public string event_id; public string message; public string timestamp; public string level; public string logger; public string platform; [Serializable] public struct SDK { public string name; public string version; } public SDK sdk = new SDK(); [Serializable] public struct Device { public string name; public string version; public string build; } public Device device = new Device(); public MessagePacket() { this.event_id = System.Guid.NewGuid().ToString("N"); this.sdk.name = "Unity3D-Raven-CS"; this.sdk.version = "0.0.1"; } public string ToJson() { return JsonUtility.ToJson(this); } } [Serializable] public struct ResponsePacket { public string id; } }
using System; using System.Collections.Generic; using UnityEngine; namespace Unity3DRavenCS { [Serializable] public class MessagePacket { public string eventID; public string message; public string timestamp; public string level; public string logger; public string platform; [Serializable] public struct SDK { public string name; public string version; } public SDK sdk = new SDK(); [Serializable] public struct Device { public string name; public string version; public string build; } public Device device = new Device(); public MessagePacket() { this.eventID = System.Guid.NewGuid().ToString("N"); } public string ToJson() { return JsonUtility.ToJson(this); } } [Serializable] public struct ResponsePacket { public string id; } }
mit
C#
27821ed9ee5f3e9d61c5800e4e3234df994d0261
Update Program.cs
smad2005/ConvertorHexString
HexToString/Program.cs
HexToString/Program.cs
using System; namespace HexToString { internal class Program { private static void Main(string[] args) { Console.WriteLine(convertorHex.HexToString(ConvertorHex.StringToHex("abcdefgh"))); } } }
using System; namespace HexToString { internal class Program { private static void Main(string[] args) { var convertorHex = new ConvertorHex(); Console.WriteLine(convertorHex.HexToString(convertorHex.StringToHex("abcdefgh"))); } } }
mit
C#
64d653ccbb0656906f7975291428ac2f3455e321
fix compile error
kheiakiyama/speech-eng-functions
MarkdownParser/run.csx
MarkdownParser/run.csx
#r "System.Configuration" #load "../QuestionEntity.csx" using System.Net; using System.Net.Http; using System.Configuration; using Newtonsoft.Json; using Microsoft.Azure; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using CommonMark; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("ResultCount function processed a request."); if (req.Method == HttpMethod.Post) return await Post(req, log); else return req.CreateResponse(HttpStatusCode.InternalServerError, "Not implimentation"); } private static async Task<HttpResponseMessage> Post(HttpRequestMessage req, TraceWriter log) { string url = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "url", true) == 0) .Value; dynamic data = await req.Content.ReadAsAsync<object>(); url = url ?? data?.url; if (url == null) return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a url and sentence on the query string or in the request body"); using (HttpClient client = new HttpClient()) { try { var content = await client.GetStringAsync(new Uri(url)); var sentences = DivideSentence(content); foreach (var item in sentences) { log.Info(item); } } catch (HttpRequestException e) { } } return req.CreateResponse(HttpStatusCode.OK, new { }); } private static string[] DivideSentence(string content, TraceWriter log) { var document = CommonMarkConverter.Convert(content); return document .AsEnumerable() .Where(q => q.Block != null || q.Inline != null) .Select(q => q.Block != null ? q.Block.StringContent.ToString() : q.Inline.StringContent.ToString()); }
#r "System.Configuration" #load "../QuestionEntity.csx" using System.Net; using System.Net.Http; using System.Configuration; using Newtonsoft.Json; using Microsoft.Azure; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using CommonMark; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log) { log.Info("ResultCount function processed a request."); if (req.Method == HttpMethod.Post) return await Post(req, log); else return req.CreateResponse(HttpStatusCode.InternalServerError, "Not implimentation"); } private static async Task<HttpResponseMessage> Post(HttpRequestMessage req, TraceWriter log) { string url = req.GetQueryNameValuePairs() .FirstOrDefault(q => string.Compare(q.Key, "url", true) == 0) .Value; dynamic data = await req.Content.ReadAsAsync<object>(); url = url ?? data?.url; if (url == null) return req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a url and sentence on the query string or in the request body"); using (HttpClient client = new HttpClient()) { try { var content = await client.GetStringAsync(new Uri(url)); var sentences = DivideSentence(content); foreach (var item in sentences) { log.Info(item); } } catch (HttpRequestException e) { } } return req.CreateResponse(HttpStatusCode.OK, new { }); } private static async Task<string[]> DivideSentence(string content, TraceWriter log) { var markdown = CommonMarkConverter.Convert(content); return document .AsEnumerable() .Where(q.Block != null || q.Inline != null) .Select(q => q.Block != null ? q.Block.StringContent.ToString() : q.Inline.StringContent.ToString()); }
mit
C#
0049417b9440467d00450c232488d7f3ba5aba36
fix sequence point test
shanselman/Fody,shanselman/Fody,furesoft/Fody,PKRoma/Fody,shanselman/Fody,distantcam/Fody,huoxudong125/Fody,ColinDabritzViewpoint/Fody,GeertvanHorrik/Fody,ichengzi/Fody,Fody/Fody,jasonholloway/Fody
Weavers/ModuleWeaver.cs
Weavers/ModuleWeaver.cs
using System; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; public class ModuleWeaver { public ModuleDefinition ModuleDefinition { get; set; } public Action<string> LogInfo { get; set; } public Action<string, SequencePoint> LogWarningPoint { get; set; } public Action<string, SequencePoint> LogErrorPoint { get; set; } public void Execute() { LogInfo("Hello"); var class1 = ModuleDefinition.Types.First(x => x.Name == "Class1"); var method1 = class1.Methods.First(x => x.Name == "Method1"); var sequencePoints = method1.Body.Instructions .Select(x => x.SequencePoint) .Where(x => x != null).ToList(); LogWarningPoint("Nav to sequencePoint", sequencePoints[0]); ModuleDefinition.Types.Add(new TypeDefinition("MyNamespace", "MyType", TypeAttributes.Public, ModuleDefinition.Import(typeof(object)))); } }
using System; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; public class ModuleWeaver { public ModuleDefinition ModuleDefinition { get; set; } public Action<string> LogInfo { get; set; } public Action<string, SequencePoint> LogWarningPoint { get; set; } public Action<string, SequencePoint> LogErrorPoint { get; set; } public void Execute() { LogInfo("Hello"); var class1 = ModuleDefinition.Types.First(x => x.Name == "Class1"); var method1 = class1.Methods.First(x => x.Name == "Method1"); var sequencePoints = method1.Body.Instructions .Select(x => x.SequencePoint) .Where(x => x != null).ToList(); LogWarningPoint("Nav to sequencePoint", sequencePoints[1]); ModuleDefinition.Types.Add(new TypeDefinition("MyNamespace", "MyType", TypeAttributes.Public, ModuleDefinition.Import(typeof(object)))); } }
mit
C#
7a78c00a12d5cae65961ff0aa07fc4284752b880
添加 EnableRequestRewindMiddleware 注释 @lishewen https://github.com/JeffreySu/WeiXinMPSDK/commit/ef7fc31fdeb518d79eb29af91d57d61c06b5ff53
mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,mc7246/WeiXinMPSDK
src/Senparc.Weixin.MP.MvcExtension/Senparc.Weixin.MP.MvcExtension/Utilities/HttpUtility/EnableRequestRewind.cs
src/Senparc.Weixin.MP.MvcExtension/Senparc.Weixin.MP.MvcExtension/Utilities/HttpUtility/EnableRequestRewind.cs
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. 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. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2018 Senparc ļEnableRequestRewindMiddleware.cs ļEnableRequestRewindм.net core 2 е RequestRewindģʽRequest.BodyԶζȡ ijЩnetcoreĬϻƵµRequest.Body ΪնWeixinSDK⡣ https://github.com/JeffreySu/WeiXinMPSDK/issues/1090 ʶlishewen - 20180516 ----------------------------------------------------------------*/ #if NETSTANDARD2_0 || NETCOREAPP2_0 || NETCOREAPP2_1 using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; namespace Microsoft.AspNetCore.Http { /// <summary> /// <para>EnableRequestRewindм.net core 2 еRequestRewindģʽRequest.BodyԶζȡ</para> /// <para>ԽijЩnetcoreĬϻƵµRequest.BodyΪնWeixinSDK⡣</para> /// <para>https://github.com/JeffreySu/WeiXinMPSDK/issues/1090</para> /// </summary> public class EnableRequestRewindMiddleware { private readonly RequestDelegate _next; /// <summary> /// EnableRequestRewindMiddleware /// </summary> /// <param name="next"></param> public EnableRequestRewindMiddleware(RequestDelegate next) { _next = next; } /// <summary> /// Invoke /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Invoke(HttpContext context) { context.Request.EnableRewind(); await _next(context); } } /// <summary> /// EnableRequestRewindExtension /// </summary> public static class EnableRequestRewindExtension { /// <summary> /// UseEnableRequestRewind /// </summary> /// <param name="builder"></param> /// <returns></returns> public static IApplicationBuilder UseEnableRequestRewind(this IApplicationBuilder builder) { return builder.UseMiddleware<EnableRequestRewindMiddleware>(); } } } #endif
#if NETSTANDARD2_0 using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; namespace Microsoft.AspNetCore.Http { public class EnableRequestRewindMiddleware { private readonly RequestDelegate _next; public EnableRequestRewindMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { context.Request.EnableRewind(); await _next(context); } } public static class EnableRequestRewindExtension { public static IApplicationBuilder UseEnableRequestRewind(this IApplicationBuilder builder) { return builder.UseMiddleware<EnableRequestRewindMiddleware>(); } } } #endif
apache-2.0
C#
2a6c98335ff7375731675d876eddd9278f79d04d
Bump version for nuget package
g0t4/Rx-FileSystemWatcher,g0t4/Rx-FileSystemWatcher
src/RxFileSystemWatcher/Properties/AssemblyInfo.cs
src/RxFileSystemWatcher/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RxFileSystemWatcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RxFileSystemWatcher")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("8ac26a3f-ea94-44ca-8131-e3a63ad35bfa")] [assembly: AssemblyVersion("0.1.2.1")] [assembly: AssemblyFileVersion("0.1.2.1")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RxFileSystemWatcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RxFileSystemWatcher")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("8ac26a3f-ea94-44ca-8131-e3a63ad35bfa")] [assembly: AssemblyVersion("0.1.2")] [assembly: AssemblyFileVersion("0.1.2")]
mit
C#
95198940ee510ff0e8e56f00aedb50c6348f9ef6
Update the logger to reflect configured Authentication Type.
versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla,versionone/VersionOne.Integration.Bugzilla
VersionOne.ServiceHost.Core/Logging/Logger.cs
VersionOne.ServiceHost.Core/Logging/Logger.cs
using System; using System.Xml; using VersionOne.ServiceHost.Core.Configuration; using VersionOne.ServiceHost.Eventing; namespace VersionOne.ServiceHost.Core.Logging { public class Logger : ILogger { private readonly IEventManager eventManager; public Logger(IEventManager eventManager) { this.eventManager = eventManager; } public void Log(string message) { Log(LogMessage.SeverityType.Info, message, null); } public void Log(string message, Exception exception) { Log(LogMessage.SeverityType.Error, message, exception); } public void Log(LogMessage.SeverityType severity, string message) { Log(severity, message, null); } public void Log(LogMessage.SeverityType severity, string message, Exception exception) { eventManager.Publish(new LogMessage(severity, message, exception)); } public void LogVersionOneConfiguration(LogMessage.SeverityType severity, XmlElement config) { try { var entity = VersionOneSettings.FromXmlElement(config); Log(severity, " VersionOne URL: " + entity.Url); Log(severity, string.Format(" Using proxy server: {0}, Authentication Type: {1}", entity.ProxySettings != null && entity.ProxySettings.Enabled, entity.AuthenticationType)); } catch(Exception ex) { Log(LogMessage.SeverityType.Warning, "Failed to log VersionOne configuration data.", ex); } } public void LogVersionOneConnectionInformation(LogMessage.SeverityType severity, string metaVersion, string memberOid, string defaultMemberRole) { Log(severity, " VersionOne Meta version: " + metaVersion); Log(severity, " VersionOne Member OID: " + memberOid); Log(severity, " VersionOne Member default role: " + defaultMemberRole); } } }
using System; using System.Xml; using VersionOne.ServiceHost.Core.Configuration; using VersionOne.ServiceHost.Eventing; namespace VersionOne.ServiceHost.Core.Logging { public class Logger : ILogger { private readonly IEventManager eventManager; public Logger(IEventManager eventManager) { this.eventManager = eventManager; } public void Log(string message) { Log(LogMessage.SeverityType.Info, message, null); } public void Log(string message, Exception exception) { Log(LogMessage.SeverityType.Error, message, exception); } public void Log(LogMessage.SeverityType severity, string message) { Log(severity, message, null); } public void Log(LogMessage.SeverityType severity, string message, Exception exception) { eventManager.Publish(new LogMessage(severity, message, exception)); } public void LogVersionOneConfiguration(LogMessage.SeverityType severity, XmlElement config) { try { var entity = VersionOneSettings.FromXmlElement(config); Log(severity, " VersionOne URL: " + entity.Url); Log(severity, string.Format(" Using proxy server: {0}, Integrated authentication: {1}", entity.ProxySettings != null && entity.ProxySettings.Enabled, entity.IntegratedAuth)); } catch(Exception ex) { Log(LogMessage.SeverityType.Warning, "Failed to log VersionOne configuration data.", ex); } } public void LogVersionOneConnectionInformation(LogMessage.SeverityType severity, string metaVersion, string memberOid, string defaultMemberRole) { Log(severity, " VersionOne Meta version: " + metaVersion); Log(severity, " VersionOne Member OID: " + memberOid); Log(severity, " VersionOne Member default role: " + defaultMemberRole); } } }
bsd-3-clause
C#
5d56280397551c4c47f4439e68925999cc04d838
修复验证异常消息缺失的问题。 :mega:
Zongsoft/Zongsoft.CoreLibrary
src/Security/Membership/AuthenticationException.cs
src/Security/Membership/AuthenticationException.cs
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2003-2015 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.CoreLibrary. * * Zongsoft.CoreLibrary is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Zongsoft.CoreLibrary is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.CoreLibrary; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Runtime.Serialization; namespace Zongsoft.Security.Membership { /// <summary> /// 身份验证失败时引发的异常。 /// </summary> [Serializable] public class AuthenticationException : System.ApplicationException { #region 构造函数 public AuthenticationException() { this.Reason = AuthenticationReason.Unknown; } public AuthenticationException(string message) : base(message, null) { this.Reason = AuthenticationReason.Unknown; } public AuthenticationException(string message, Exception innerException) : base(message, innerException) { this.Reason = AuthenticationReason.Unknown; } public AuthenticationException(AuthenticationReason reason) : this(reason, string.Empty, null) { } public AuthenticationException(AuthenticationReason reason, string message) : this(reason, message, null) { } public AuthenticationException(AuthenticationReason reason, string message, Exception innerException) : base(message, innerException) { this.Reason = reason; } protected AuthenticationException(SerializationInfo info, StreamingContext context) : base(info, context) { this.Reason = (AuthenticationReason)info.GetInt32(nameof(Reason)); } #endregion #region 公共属性 /// <summary> /// 获取验证失败的原因。 /// </summary> public AuthenticationReason Reason { get; } public override string Message { get { var message = base.Message; if(string.IsNullOrEmpty(message)) return Common.EnumUtility.GetEnumDescription(this.Reason); return message; } } #endregion #region 重写方法 public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(Reason), this.Reason); } #endregion } }
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2003-2015 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.CoreLibrary. * * Zongsoft.CoreLibrary is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Zongsoft.CoreLibrary is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.CoreLibrary; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Runtime.Serialization; namespace Zongsoft.Security.Membership { /// <summary> /// 身份验证失败时引发的异常。 /// </summary> [Serializable] public class AuthenticationException : System.ApplicationException { #region 构造函数 public AuthenticationException() { this.Reason = AuthenticationReason.Unknown; } public AuthenticationException(string message) : base(message, null) { this.Reason = AuthenticationReason.Unknown; } public AuthenticationException(string message, Exception innerException) : base(message, innerException) { this.Reason = AuthenticationReason.Unknown; } public AuthenticationException(AuthenticationReason reason) : this(reason, string.Empty, null) { } public AuthenticationException(AuthenticationReason reason, string message) : this(reason, message, null) { } public AuthenticationException(AuthenticationReason reason, string message, Exception innerException) : base(message, innerException) { this.Reason = reason; } protected AuthenticationException(SerializationInfo info, StreamingContext context) : base(info, context) { this.Reason = (AuthenticationReason)info.GetInt32(nameof(Reason)); } #endregion #region 公共属性 /// <summary> /// 获取验证失败的原因。 /// </summary> public AuthenticationReason Reason { get; } #endregion #region 重写方法 public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(Reason), this.Reason); } #endregion } }
lgpl-2.1
C#
68e426bb818be4dcc2557f736180cc847601da40
Fix unsetting attemptLoginRefresh
tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
src/Tgstation.Server.Client/ServerClientFactory.cs
src/Tgstation.Server.Client/ServerClientFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Api; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Client { /// <inheritdoc /> public sealed class ServerClientFactory : IServerClientFactory { /// <summary> /// The <see cref="IApiClientFactory"/> for the <see cref="ServerClientFactory"/> /// </summary> static readonly IApiClientFactory ApiClientFactory = new ApiClientFactory(); /// <summary> /// The <see cref="ProductHeaderValue"/> for the <see cref="ServerClientFactory"/> /// </summary> readonly ProductHeaderValue productHeaderValue; /// <summary> /// Construct a <see cref="ServerClientFactory"/> /// </summary> /// <param name="productHeaderValue">The value of <see cref="productHeaderValue"/></param> public ServerClientFactory(ProductHeaderValue productHeaderValue) { this.productHeaderValue = productHeaderValue ?? throw new ArgumentNullException(nameof(productHeaderValue)); } /// <inheritdoc /> public async Task<IServerClient> CreateFromLogin( Uri host, string username, string password, IEnumerable<IRequestLogger>? requestLoggers = null, TimeSpan? timeout = null, bool attemptLoginRefresh = true, CancellationToken cancellationToken = default) { if (host == null) throw new ArgumentNullException(nameof(host)); if (username == null) throw new ArgumentNullException(nameof(username)); if (password == null) throw new ArgumentNullException(nameof(password)); requestLoggers ??= Enumerable.Empty<IRequestLogger>(); Token token; var loginHeaders = new ApiHeaders(productHeaderValue, username, password); using (var api = ApiClientFactory.CreateApiClient(host, loginHeaders, null)) { foreach (var requestLogger in requestLoggers) api.AddRequestLogger(requestLogger); if (timeout.HasValue) api.Timeout = timeout.Value; token = await api.Update<Token>(Routes.Root, cancellationToken).ConfigureAwait(false); } if (!attemptLoginRefresh) loginHeaders = null; var apiHeaders = new ApiHeaders(productHeaderValue, token.Bearer!); var client = new ServerClient(ApiClientFactory.CreateApiClient(host, apiHeaders, loginHeaders), token); if (timeout.HasValue) client.Timeout = timeout.Value; foreach (var requestLogger in requestLoggers) client.AddRequestLogger(requestLogger); return client; } /// <inheritdoc /> public IServerClient CreateFromToken(Uri host, Token token) { if (host == null) throw new ArgumentNullException(nameof(host)); if (token == null) throw new ArgumentNullException(nameof(token)); if (token.Bearer == null) throw new ArgumentException("token.Bearer should not be null!", nameof(token)); return new ServerClient(ApiClientFactory.CreateApiClient(host, new ApiHeaders(productHeaderValue, token.Bearer), null), token); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Api; using Tgstation.Server.Api.Models; namespace Tgstation.Server.Client { /// <inheritdoc /> public sealed class ServerClientFactory : IServerClientFactory { /// <summary> /// The <see cref="IApiClientFactory"/> for the <see cref="ServerClientFactory"/> /// </summary> static readonly IApiClientFactory ApiClientFactory = new ApiClientFactory(); /// <summary> /// The <see cref="ProductHeaderValue"/> for the <see cref="ServerClientFactory"/> /// </summary> readonly ProductHeaderValue productHeaderValue; /// <summary> /// Construct a <see cref="ServerClientFactory"/> /// </summary> /// <param name="productHeaderValue">The value of <see cref="productHeaderValue"/></param> public ServerClientFactory(ProductHeaderValue productHeaderValue) { this.productHeaderValue = productHeaderValue ?? throw new ArgumentNullException(nameof(productHeaderValue)); } /// <inheritdoc /> public async Task<IServerClient> CreateFromLogin( Uri host, string username, string password, IEnumerable<IRequestLogger>? requestLoggers = null, TimeSpan? timeout = null, bool attemptLoginRefresh = true, CancellationToken cancellationToken = default) { if (host == null) throw new ArgumentNullException(nameof(host)); if (username == null) throw new ArgumentNullException(nameof(username)); if (password == null) throw new ArgumentNullException(nameof(password)); requestLoggers ??= Enumerable.Empty<IRequestLogger>(); Token token; var loginHeaders = new ApiHeaders(productHeaderValue, username, password); using (var api = ApiClientFactory.CreateApiClient(host, loginHeaders, null)) { foreach (var requestLogger in requestLoggers) api.AddRequestLogger(requestLogger); if (timeout.HasValue) api.Timeout = timeout.Value; token = await api.Update<Token>(Routes.Root, cancellationToken).ConfigureAwait(false); } var apiHeaders = new ApiHeaders(productHeaderValue, token.Bearer!); var client = new ServerClient(ApiClientFactory.CreateApiClient(host, apiHeaders, loginHeaders), token); if (timeout.HasValue) client.Timeout = timeout.Value; foreach (var requestLogger in requestLoggers) client.AddRequestLogger(requestLogger); return client; } /// <inheritdoc /> public IServerClient CreateFromToken(Uri host, Token token) { if (host == null) throw new ArgumentNullException(nameof(host)); if (token == null) throw new ArgumentNullException(nameof(token)); if (token.Bearer == null) throw new ArgumentException("token.Bearer should not be null!", nameof(token)); return new ServerClient(ApiClientFactory.CreateApiClient(host, new ApiHeaders(productHeaderValue, token.Bearer), null), token); } } }
agpl-3.0
C#
4e8099942745615708a4b207a13e5d27743b87e8
fix conflict
KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog
src/StructuredLogViewer.Core/SearchResult.cs
src/StructuredLogViewer.Core/SearchResult.cs
using System; using System.Collections.Generic; using Microsoft.Build.Logging.StructuredLogger; namespace StructuredLogViewer { public class SearchResult { public BaseNode Node { get; } public List<(string field, string match)> WordsInFields = new List<(string, string)>(); public bool MatchedByType { get; private set; } public TimeSpan Duration { get; set; } public SearchResult(BaseNode node, bool includeDuration = false) { Node = node; if (includeDuration && node is TimedNode timedNode) { Duration = timedNode.Duration; } } public void AddMatch(string field, string word, bool addAtBeginning = false) { if (addAtBeginning) { WordsInFields.Insert(0, (field, word)); } else { WordsInFields.Add((field, word)); } } public void AddMatchByNodeType() { MatchedByType = true; } } }
using System; using System.Collections.Generic; using Microsoft.Build.Logging.StructuredLogger; namespace StructuredLogViewer { public class SearchResult { public BaseNode Node { get; } public List<(string field, string match)> WordsInFields = new List<(string, string)>(); public bool MatchedByType { get; private set; } public TimeSpan Duration { get; set; } public SearchResult(BaseNode node, bool includeDuration = false) { Node = node; if (includeDuration && node is TimedNode timedNode) { Duration = timedNode.Duration; } } <<<<<<< HEAD public void AddMatch(string field, string word, bool addAtBeginning = false) ======= public void AddMatch(string field, string word, string notHighlightedText = "", bool addAtBeginning = false) >>>>>>> master { if (addAtBeginning) { WordsInFields.Insert(0, (field, word)); } else { WordsInFields.Add((field, word)); <<<<<<< HEAD } ======= } if (!string.IsNullOrEmpty(notHighlightedText)) { SearchResultPair.Add((field, notHighlightedText)); } >>>>>>> master } public void AddMatchByNodeType() { MatchedByType = true; } } }
mit
C#