commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
6e08b1db1d342c584bc2899cb6dc0e175219dcee
osu!StreamCompanion/Code/Modules/ModParser/ModParserSettings.cs
osu!StreamCompanion/Code/Modules/ModParser/ModParserSettings.cs
using System; using System.Windows.Forms; using osu_StreamCompanion.Code.Core; using osu_StreamCompanion.Code.Helpers; namespace osu_StreamCompanion.Code.Modules.ModParser { public partial class ModParserSettings : UserControl { private Settings _settings; private bool init = true; public ModParserSettings(Settings settings) { _settings = settings; _settings.SettingUpdated+= SettingUpdated; this.Enabled = _settings.Get("EnableMemoryScanner", true); InitializeComponent(); textBox_Mods.Text = _settings.Get("NoModsDisplayText", "None"); radioButton_longMods.Checked = _settings.Get("UseLongMods", false); radioButton_shortMods.Checked = !radioButton_longMods.Checked; init = false; } private void SettingUpdated(object sender, SettingUpdated settingUpdated) { this.BeginInvoke((MethodInvoker) (() => { if (settingUpdated.Name == "EnableMemoryScanner") this.Enabled = _settings.Get("EnableMemoryScanner", true); })); } private void textBox_Mods_TextChanged(object sender, EventArgs e) { if (init) return; _settings.Add("NoModsDisplayText", textBox_Mods.Text); } private void radioButton_longMods_CheckedChanged(object sender, EventArgs e) { if (init) return; if (((RadioButton)sender).Checked) { _settings.Add("UseLongMods", radioButton_longMods.Checked); } } } }
using System; using System.Windows.Forms; using osu_StreamCompanion.Code.Core; using osu_StreamCompanion.Code.Helpers; namespace osu_StreamCompanion.Code.Modules.ModParser { public partial class ModParserSettings : UserControl { private Settings _settings; private bool init = true; public ModParserSettings(Settings settings) { _settings = settings; _settings.SettingUpdated += SettingUpdated; this.Enabled = _settings.Get("EnableMemoryScanner", true); InitializeComponent(); textBox_Mods.Text = _settings.Get("NoModsDisplayText", "None"); radioButton_longMods.Checked = _settings.Get("UseLongMods", false); radioButton_shortMods.Checked = !radioButton_longMods.Checked; init = false; } private void SettingUpdated(object sender, SettingUpdated settingUpdated) { if (this.IsHandleCreated) this.BeginInvoke((MethodInvoker)(() => { if (settingUpdated.Name == "EnableMemoryScanner") this.Enabled = _settings.Get("EnableMemoryScanner", true); })); } private void textBox_Mods_TextChanged(object sender, EventArgs e) { if (init) return; _settings.Add("NoModsDisplayText", textBox_Mods.Text); } private void radioButton_longMods_CheckedChanged(object sender, EventArgs e) { if (init) return; if (((RadioButton)sender).Checked) { _settings.Add("UseLongMods", radioButton_longMods.Checked); } } } }
Make sure that beginInvoke target exists
Make sure that beginInvoke target exists
C#
mit
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
c27a20bc2a0ed3562a7782e47be9386727c0791c
Anagrams/Global.asax.cs
Anagrams/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Anagrams.Models; namespace Anagrams { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); DictionaryCache.Reader = new DictionaryReader(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Anagrams.Models; namespace Anagrams { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); DictionaryCache.Reader = new DictionaryReader(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); DictionaryCache.SetPath(HttpContext.Current.Server.MapPath(@"Content/wordlist.txt")); } } }
Use API to override the location of the dictionary file in the dictionary cache from our Web applicatoin
Use API to override the location of the dictionary file in the dictionary cache from our Web applicatoin
C#
mit
TheChimni/Anagrams,TheChimni/Anagrams
1f65aa4bf3c0863c3d36865401209c94f97f06c4
WalletWasabi.Gui/Converters/CoinStatusForegroundConverter.cs
WalletWasabi.Gui/Converters/CoinStatusForegroundConverter.cs
using Avalonia.Data.Converters; using Avalonia.Media; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using WalletWasabi.Gui.Controls.WalletExplorer; using WalletWasabi.Gui.Models; using WalletWasabi.Models.ChaumianCoinJoin; namespace WalletWasabi.Gui.Converters { public class CoinStatusForegroundConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is SmartCoinStatus status) { switch (status) { case SmartCoinStatus.MixingOutputRegistration: case SmartCoinStatus.MixingSigning: case SmartCoinStatus.MixingInputRegistration: case SmartCoinStatus.MixingOnWaitingList: case SmartCoinStatus.MixingWaitingForConfirmation: return Brushes.Black; default: return Brushes.White; } } throw new InvalidOperationException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
using Avalonia.Data.Converters; using Avalonia.Media; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using WalletWasabi.Gui.Controls.WalletExplorer; using WalletWasabi.Gui.Models; using WalletWasabi.Models.ChaumianCoinJoin; namespace WalletWasabi.Gui.Converters { public class CoinStatusForegroundConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is SmartCoinStatus status) { switch (status) { case SmartCoinStatus.MixingInputRegistration: case SmartCoinStatus.MixingOnWaitingList: case SmartCoinStatus.MixingWaitingForConfirmation: return Brushes.Black; default: return Brushes.White; } } throw new InvalidOperationException(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
Make round states foreground white
[skip ci] Make round states foreground white
C#
mit
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
27e182ef94e9f8a0de44c57f77ce53940c490d00
Mond/Libraries/Async/Scheduler.cs
Mond/Libraries/Async/Scheduler.cs
using System.Collections.Generic; using System.Threading.Tasks; namespace Mond.Libraries.Async { internal class Scheduler : TaskScheduler { private List<Task> _tasks; public Scheduler() { _tasks = new List<Task>(); } public void Run() { int count; lock (_tasks) { count = _tasks.Count; } if (count == 0) return; while (--count >= 0) { Task task; lock (_tasks) { if (_tasks.Count == 0) return; task = _tasks[0]; _tasks.RemoveAt(0); } if (!TryExecuteTask(task)) _tasks.Add(task); } } protected override IEnumerable<Task> GetScheduledTasks() { lock (_tasks) { return _tasks.ToArray(); } } protected override void QueueTask(Task task) { lock (_tasks) { _tasks.Add(task); } } protected override bool TryDequeue(Task task) { lock (_tasks) { return _tasks.Remove(task); } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return false; } } }
using System.Collections.Generic; using System.Threading.Tasks; namespace Mond.Libraries.Async { internal class Scheduler : TaskScheduler { private List<Task> _tasks; public Scheduler() { _tasks = new List<Task>(); } public void Run() { int count; lock (_tasks) { count = _tasks.Count; } if (count == 0) return; while (--count >= 0) { Task task; lock (_tasks) { if (_tasks.Count == 0) return; task = _tasks[0]; _tasks.RemoveAt(0); } if (TryExecuteTask(task)) continue; lock (_tasks) { _tasks.Add(task); } } } protected override IEnumerable<Task> GetScheduledTasks() { lock (_tasks) { return _tasks.ToArray(); } } protected override void QueueTask(Task task) { lock (_tasks) { _tasks.Add(task); } } protected override bool TryDequeue(Task task) { lock (_tasks) { return _tasks.Remove(task); } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (taskWasPreviouslyQueued) { if (TryDequeue(task)) return TryExecuteTask(task); return false; } return TryExecuteTask(task); } } }
Fix async deadlock on Mono
Fix async deadlock on Mono
C#
mit
Rohansi/Mond,SirTony/Mond,SirTony/Mond,Rohansi/Mond,Rohansi/Mond,SirTony/Mond
f25ea9fe0ef80f547136df434e1ff8d1dde76432
Properties/AssemblyInfo.cs
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("FreenetTray")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FreenetTray")] [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("220ea49e-e109-4bb4-86c6-ef477f1584e7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // 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("FreenetTray")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FreenetTray")] [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("220ea49e-e109-4bb4-86c6-ef477f1584e7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en")]
Set neutral language to English
Set neutral language to English
C#
mit
freenet/wintray,freenet/wintray
615fe0e6b6f4c087fe89a168601d3d5fb004f178
Source/MTW_AncestorSpirits/AncestorUtils.cs
Source/MTW_AncestorSpirits/AncestorUtils.cs
using RimWorld; using UnityEngine; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { public static class AncestorUtils { public static int DaysToTicks(float days) { return Mathf.RoundToInt(days * GenDate.TicksPerDay); } public static int HoursToTicks(float hours) { return Mathf.RoundToInt(hours * GenDate.TicksPerHour); } } }
using Verse; using RimWorld; using UnityEngine; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MTW_AncestorSpirits { public static class AncestorUtils { public static int DaysToTicks(float days) { return Mathf.RoundToInt(days * GenDate.TicksPerDay); } public static int HoursToTicks(float hours) { return Mathf.RoundToInt(hours * GenDate.TicksPerHour); } public static long EstStartOfSeasonAt(long ticks) { var currentDayTicks = (int)(GenDate.CurrentDayPercent * GenDate.TicksPerDay); var dayOfSeason = GenDate.DayOfSeasonZeroBasedAt(ticks); var currentSeasonDayTicks = DaysToTicks(dayOfSeason); return ticks - currentDayTicks - currentSeasonDayTicks; } } }
Add function to get start of season
Add function to get start of season
C#
mit
MoyTW/MTW_AncestorSpirits
cedd703faad81a8462b3e4353a1545de8fe01a49
Source/Hypermedia.Client/Reader/ProblemJson/ProblemJsonReader.cs
Source/Hypermedia.Client/Reader/ProblemJson/ProblemJsonReader.cs
namespace Hypermedia.Client.Reader.ProblemJson { using System; using System.Net.Http; using global::Hypermedia.Client.Exceptions; using global::Hypermedia.Client.Resolver; using Newtonsoft.Json; public static class ProblemJsonReader { public static bool TryReadProblemJson(HttpResponseMessage result, out ProblemDescription problemDescription) { problemDescription = null; if (result.Content == null) { return false; } try { var content = result.Content.ReadAsStringAsync().Result; problemDescription = JsonConvert.DeserializeObject<ProblemDescription>(content); // TODO inject deserializer } catch (Exception) { return false; } return true; } } }
namespace Hypermedia.Client.Reader.ProblemJson { using System; using System.Net.Http; using global::Hypermedia.Client.Exceptions; using global::Hypermedia.Client.Resolver; using Newtonsoft.Json; public static class ProblemJsonReader { public static bool TryReadProblemJson(HttpResponseMessage result, out ProblemDescription problemDescription) { problemDescription = null; if (result.Content == null) { return false; } try { var content = result.Content.ReadAsStringAsync().Result; problemDescription = JsonConvert.DeserializeObject<ProblemDescription>(content); // TODO inject deserializer } catch (Exception) { return false; } return problemDescription != null; } } }
Fix TryReadProblemJson: ensure problem json could be read and an object was created
Fix TryReadProblemJson: ensure problem json could be read and an object was created
C#
mit
bluehands/WebApiHypermediaExtensions,bluehands/WebApiHypermediaExtensions
d7d786f60c4490ddc72ca4ad0ad67cb3fa51a98c
Deblocus/Program.cs
Deblocus/Program.cs
// // Program.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using Xwt; using Deblocus.Views; namespace Deblocus { public static class Program { [STAThread] public static void Main() { Application.Initialize(ToolkitType.Gtk); var mainWindow = new MainWindow(); mainWindow.Show(); Application.Run(); mainWindow.Dispose(); Application.Dispose(); } } }
// // Program.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using Xwt; using Deblocus.Views; namespace Deblocus { public static class Program { [STAThread] public static void Main() { Application.Initialize(ToolkitType.Gtk); Application.UnhandledException += ApplicationException; var mainWindow = new MainWindow(); mainWindow.Show(); Application.Run(); mainWindow.Dispose(); Application.Dispose(); } private static void ApplicationException (object sender, ExceptionEventArgs e) { MessageDialog.ShowError("Unknown error. Please contact with the developer.\n" + e.ErrorException); } } }
Add error message on exception
Add error message on exception
C#
agpl-3.0
pleonex/deblocus,pleonex/deblocus
199300be1d7b565ea174562ff778fa7d46837ae7
Library/Properties/AssemblyInfo.cs
Library/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("Recurly Client Library")] [assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Recurly, Inc.")] [assembly: AssemblyProduct("Recurly")] [assembly: AssemblyCopyright("")] [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("25932cc0-45c7-4db4-b8d5-dd172555522c")] // 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.4.2.2")] [assembly: AssemblyFileVersion("1.4.2.2")]
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("Recurly Client Library")] [assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Recurly, Inc.")] [assembly: AssemblyProduct("Recurly")] [assembly: AssemblyCopyright("")] [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("25932cc0-45c7-4db4-b8d5-dd172555522c")] // 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.4.2.3")] [assembly: AssemblyFileVersion("1.4.2.3")]
Increase client version to 1.4.2.3
Increase client version to 1.4.2.3
C#
mit
jvalladolid/recurly-client-net
0aee46701a778a6f6044bc53c41fe50c1400f3a8
src/Sitecore.DataBlaster/Load/Processors/SyncHistoryTable.cs
src/Sitecore.DataBlaster/Load/Processors/SyncHistoryTable.cs
using System.Diagnostics; using Sitecore.Configuration; using Sitecore.DataBlaster.Load.Sql; namespace Sitecore.DataBlaster.Load.Processors { public class SyncHistoryTable : ISyncInTransaction { public void Process(BulkLoadContext loadContext, BulkLoadSqlContext sqlContext) { if (!loadContext.UpdateHistory.GetValueOrDefault()) return; if (loadContext.ItemChanges.Count == 0) return; // In Sitecore 9, history engine is disabled by default if (!HistoryEngineEnabled(loadContext)) { loadContext.Log.Warn($"Skipped updating history because history engine is not enabled"); return; } var stopwatch = Stopwatch.StartNew(); var sql = sqlContext.GetEmbeddedSql(loadContext, "Sql.09.UpdateHistory.sql"); sqlContext.ExecuteSql(sql, commandProcessor: cmd => cmd.Parameters.AddWithValue("@UserName", Sitecore.Context.User.Name)); loadContext.Log.Info($"Updated history: {(int) stopwatch.Elapsed.TotalSeconds}s"); } private bool HistoryEngineEnabled(BulkLoadContext context) { var db = Factory.GetDatabase(context.Database, true); return db.Engines.HistoryEngine.Storage != null; } } }
using System.Diagnostics; using Sitecore.Configuration; using Sitecore.DataBlaster.Load.Sql; namespace Sitecore.DataBlaster.Load.Processors { public class SyncHistoryTable : ISyncInTransaction { public void Process(BulkLoadContext loadContext, BulkLoadSqlContext sqlContext) { if (!loadContext.UpdateHistory.GetValueOrDefault()) return; if (loadContext.ItemChanges.Count == 0) return; // In Sitecore 9, history engine is disabled by default if (!HistoryEngineEnabled(loadContext)) { loadContext.Log.Info($"Skipped updating history because history engine is not enabled."); return; } var stopwatch = Stopwatch.StartNew(); var sql = sqlContext.GetEmbeddedSql(loadContext, "Sql.09.UpdateHistory.sql"); sqlContext.ExecuteSql(sql, commandProcessor: cmd => cmd.Parameters.AddWithValue("@UserName", Sitecore.Context.User.Name)); loadContext.Log.Info($"Updated history: {(int) stopwatch.Elapsed.TotalSeconds}s"); } private bool HistoryEngineEnabled(BulkLoadContext context) { var db = Factory.GetDatabase(context.Database, true); return db.Engines.HistoryEngine.Storage != null; } } }
Change log lvl for history engine disable logging
Change log lvl for history engine disable logging
C#
mit
delawarePro/sitecore-data-blaster
0d70429cf04813f571a9cc1b4b05ce5a0d44d15b
GUI/Utils/Settings.cs
GUI/Utils/Settings.cs
using System.Collections.Generic; using System.Drawing; using System.IO; namespace GUI.Utils { internal static class Settings { public static List<string> GameSearchPaths { get; } = new List<string>(); public static Color BackgroundColor { get; set; } = Color.Black; public static void Load() { // TODO: Be dumb about it for now. if (!File.Exists("gamepaths.txt")) { return; } GameSearchPaths.AddRange(File.ReadAllLines("gamepaths.txt")); } public static void Save() { File.WriteAllLines("gamepaths.txt", GameSearchPaths); } } }
using System.Collections.Generic; using System.Drawing; using System.IO; namespace GUI.Utils { internal static class Settings { public static List<string> GameSearchPaths { get; } = new List<string>(); public static Color BackgroundColor { get; set; } public static void Load() { BackgroundColor = Color.FromArgb(60, 60, 60); // TODO: Be dumb about it for now. if (!File.Exists("gamepaths.txt")) { return; } GameSearchPaths.AddRange(File.ReadAllLines("gamepaths.txt")); } public static void Save() { File.WriteAllLines("gamepaths.txt", GameSearchPaths); } } }
Change default background color to be more grey
Change default background color to be more grey
C#
mit
SteamDatabase/ValveResourceFormat
fb0685dee75cba5cf25b6c4a5971c4b6ad8f8470
src/Micro+/Entity/EntityInfo.cs
src/Micro+/Entity/EntityInfo.cs
using System.Collections.Generic; using System; namespace MicroORM.Entity { internal sealed class EntityInfo { internal EntityInfo() { this.EntityState = EntityState.None; this.EntityHashSet = new Dictionary<string, string>(); this.LastCallTime = DateTime.Now; } internal bool CanBeRemoved { get { return DateTime.Now.Subtract(this.LastCallTime) > TimeSpan.FromMinutes(2); } } internal EntityState EntityState { get; set; } internal Dictionary<string, string> EntityHashSet { get; set; } internal DateTime LastCallTime { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using MicroORM.Materialization; using MicroORM.Reflection; using MicroORM.Mapping; namespace MicroORM.Entity { internal sealed class EntityInfo { internal EntityInfo() { this.EntityState = EntityState.None; this.ValueSnapshot = new Dictionary<string, int>(); this.ChangesSnapshot = new Dictionary<string, int>(); this.LastCallTime = DateTime.Now; } internal bool CanBeRemoved { get { return DateTime.Now.Subtract(this.LastCallTime) > TimeSpan.FromMinutes(2); } } internal EntityState EntityState { get; set; } internal Dictionary<string, int> ValueSnapshot { get; set; } internal Dictionary<string, int> ChangesSnapshot { get; set; } internal DateTime LastCallTime { get; set; } internal void ClearChanges() { this.ChangesSnapshot.Clear(); } internal void MergeChanges() { foreach (var change in this.ChangesSnapshot) { this.ValueSnapshot[change.Key] = change.Value; } ClearChanges(); } internal void ComputeSnapshot<TEntity>(TEntity entity) { this.ValueSnapshot = EntityHashSetManager.ComputeEntityHashSet(entity); } internal KeyValuePair<string, object>[] ComputeUpdateValues<TEntity>(TEntity entity) { Dictionary<string, int> entityHashSet = EntityHashSetManager.ComputeEntityHashSet(entity); KeyValuePair<string, object>[] entityValues = RemoveUnusedPropertyValues<TEntity>(entity); Dictionary<string, object> valuesToUpdate = new Dictionary<string, object>(); foreach (var kvp in entityHashSet) { var oldHash = this.ValueSnapshot[kvp.Key]; if (oldHash.Equals(kvp.Value) == false) { valuesToUpdate.Add(kvp.Key, entityValues.FirstOrDefault(kvp1 => kvp1.Key == kvp.Key).Value); this.ChangesSnapshot.Add(kvp.Key, kvp.Value); } } return valuesToUpdate.ToArray(); } private KeyValuePair<string, object>[] RemoveUnusedPropertyValues<TEntity>(TEntity entity) { KeyValuePair<string, object>[] entityValues = ParameterTypeDescriptor.ToKeyValuePairs(new object[] { entity }); TableInfo tableInfo = TableInfo<TEntity>.GetTableInfo; return entityValues.Where(kvp => tableInfo.DbTable.DbColumns.Any(column => column.Name == kvp.Key)).ToArray(); } } }
Rollback functionality and hash computing
Rollback functionality and hash computing Added the functionality to compute the hash by himself and save or rollback changes made to entity.
C#
apache-2.0
PowerMogli/Rabbit.Db
f3b8a8a440116bd0153a58dc6c8d2178445bf26c
src/DslPackage/CustomCode/Messages.cs
src/DslPackage/CustomCode/Messages.cs
using System; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Sawczyn.EFDesigner.EFModel { internal static class Messages { private static readonly string MessagePaneTitle = "Entity Framework Designer"; private static IVsOutputWindow _outputWindow; private static IVsOutputWindow OutputWindow => _outputWindow ?? (_outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow); private static IVsOutputWindowPane _outputWindowPane; private static IVsOutputWindowPane OutputWindowPane { get { if (_outputWindowPane == null) { Guid paneGuid = new Guid(Constants.EFDesignerOutputPane); OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane); if (_outputWindowPane == null) { OutputWindow?.CreatePane(ref paneGuid, MessagePaneTitle, 1, 1); OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane); } } return _outputWindowPane; } } public static void AddError(string message) { OutputWindowPane?.OutputString($"Error: {message}"); OutputWindowPane?.Activate(); } public static void AddWarning(string message) { OutputWindowPane?.OutputString($"Warning: {message}"); OutputWindowPane?.Activate(); } public static void AddMessage(string message) { OutputWindowPane?.OutputString(message); OutputWindowPane?.Activate(); } } }
using System; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace Sawczyn.EFDesigner.EFModel { internal static class Messages { private static readonly string MessagePaneTitle = "Entity Framework Designer"; private static IVsOutputWindow _outputWindow; private static IVsOutputWindow OutputWindow => _outputWindow ?? (_outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow); private static IVsOutputWindowPane _outputWindowPane; private static IVsOutputWindowPane OutputWindowPane { get { if (_outputWindowPane == null) { Guid paneGuid = new Guid(Constants.EFDesignerOutputPane); OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane); if (_outputWindowPane == null) { OutputWindow?.CreatePane(ref paneGuid, MessagePaneTitle, 1, 1); OutputWindow?.GetPane(ref paneGuid, out _outputWindowPane); } } return _outputWindowPane; } } public static void AddError(string message) { AddMessage(message, "Error"); } public static void AddWarning(string message) { AddMessage(message, "Warning"); } public static void AddMessage(string message, string prefix = null) { OutputWindowPane?.OutputString($"{(string.IsNullOrWhiteSpace(prefix) ? "" : prefix + ": ")}{message}{(message.EndsWith("\n") ? "" : "\n")}"); OutputWindowPane?.Activate(); } } }
Format for output window message changed
Format for output window message changed
C#
mit
msawczyn/EFDesigner,msawczyn/EFDesigner,msawczyn/EFDesigner
0082d559145649066e3c16370f609f9fc94fef15
src/Orchard.Web/Core/Common/Shapes.cs
src/Orchard.Web/Core/Common/Shapes.cs
using System; using System.Web; using System.Web.Mvc; using Orchard.DisplayManagement; using Orchard.DisplayManagement.Descriptors; using Orchard.Localization; using Orchard.Mvc.Html; namespace Orchard.Core.Common { public class Shapes : IShapeTableProvider { public Shapes() { T = NullLocalizer.Instance; } public Localizer T { get; set; } public void Discover(ShapeTableBuilder builder) { builder.Describe("Body_Editor") .OnDisplaying(displaying => { string flavor = displaying.Shape.EditorFlavor; displaying.ShapeMetadata.Alternates.Add("Body_Editor__" + flavor); }); } [Shape] public IHtmlString PublishedState(dynamic Display, DateTime createdDateTimeUtc, DateTime? publisheddateTimeUtc) { if (!publisheddateTimeUtc.HasValue) { return T("Draft"); } return Display.DateTime(DateTimeUtc: createdDateTimeUtc); } [Shape] public IHtmlString PublishedWhen(dynamic Display, DateTime? dateTimeUtc) { if (dateTimeUtc == null) return T("as a Draft"); return Display.DateTimeRelative(DateTimeUtc: dateTimeUtc); } } }
using System; using System.Web; using System.Web.Mvc; using Orchard.DisplayManagement; using Orchard.DisplayManagement.Descriptors; using Orchard.Localization; using Orchard.Mvc.Html; namespace Orchard.Core.Common { public class Shapes : IShapeTableProvider { public Shapes() { T = NullLocalizer.Instance; } public Localizer T { get; set; } public void Discover(ShapeTableBuilder builder) { builder.Describe("Body_Editor") .OnDisplaying(displaying => { string flavor = displaying.Shape.EditorFlavor; displaying.ShapeMetadata.Alternates.Add("Body_Editor__" + flavor); }); } [Shape] public IHtmlString PublishedState(dynamic Display, DateTime createdDateTimeUtc, DateTime? publisheddateTimeUtc, LocalizedString customDateFormat) { if (!publisheddateTimeUtc.HasValue) { return T("Draft"); } return Display.DateTime(DateTimeUtc: createdDateTimeUtc, CustomFormat: customDateFormat); } [Shape] public IHtmlString PublishedWhen(dynamic Display, DateTime? dateTimeUtc) { if (dateTimeUtc == null) return T("as a Draft"); return Display.DateTimeRelative(DateTimeUtc: dateTimeUtc); } } }
Allow custom date format when displaying published state
Allow custom date format when displaying published state Wen overriding the Parts.Common.Metadata.cshtml in a theme, this will allow for changing the date format used to display the date.
C#
bsd-3-clause
rtpHarry/Orchard,omidnasri/Orchard,LaserSrl/Orchard,fassetar/Orchard,OrchardCMS/Orchard,yersans/Orchard,bedegaming-aleksej/Orchard,AdvantageCS/Orchard,gcsuk/Orchard,yersans/Orchard,Serlead/Orchard,ehe888/Orchard,Serlead/Orchard,Dolphinsimon/Orchard,hbulzy/Orchard,AdvantageCS/Orchard,LaserSrl/Orchard,hbulzy/Orchard,fassetar/Orchard,ehe888/Orchard,gcsuk/Orchard,Fogolan/OrchardForWork,omidnasri/Orchard,AdvantageCS/Orchard,aaronamm/Orchard,omidnasri/Orchard,omidnasri/Orchard,omidnasri/Orchard,Lombiq/Orchard,omidnasri/Orchard,AdvantageCS/Orchard,jimasp/Orchard,Serlead/Orchard,LaserSrl/Orchard,IDeliverable/Orchard,jersiovic/Orchard,rtpHarry/Orchard,bedegaming-aleksej/Orchard,hbulzy/Orchard,aaronamm/Orchard,aaronamm/Orchard,gcsuk/Orchard,IDeliverable/Orchard,aaronamm/Orchard,omidnasri/Orchard,hbulzy/Orchard,rtpHarry/Orchard,rtpHarry/Orchard,jimasp/Orchard,Lombiq/Orchard,rtpHarry/Orchard,bedegaming-aleksej/Orchard,jimasp/Orchard,omidnasri/Orchard,Fogolan/OrchardForWork,OrchardCMS/Orchard,Lombiq/Orchard,ehe888/Orchard,Dolphinsimon/Orchard,ehe888/Orchard,OrchardCMS/Orchard,Lombiq/Orchard,Fogolan/OrchardForWork,Lombiq/Orchard,jimasp/Orchard,yersans/Orchard,Serlead/Orchard,aaronamm/Orchard,LaserSrl/Orchard,bedegaming-aleksej/Orchard,Serlead/Orchard,yersans/Orchard,IDeliverable/Orchard,fassetar/Orchard,bedegaming-aleksej/Orchard,OrchardCMS/Orchard,jimasp/Orchard,gcsuk/Orchard,Dolphinsimon/Orchard,fassetar/Orchard,Fogolan/OrchardForWork,Dolphinsimon/Orchard,hbulzy/Orchard,jersiovic/Orchard,ehe888/Orchard,IDeliverable/Orchard,Fogolan/OrchardForWork,AdvantageCS/Orchard,gcsuk/Orchard,omidnasri/Orchard,fassetar/Orchard,jersiovic/Orchard,Dolphinsimon/Orchard,jersiovic/Orchard,OrchardCMS/Orchard,yersans/Orchard,jersiovic/Orchard,LaserSrl/Orchard,IDeliverable/Orchard
fad460d69e4a133b05de63d502288eca3066a56b
ArduinoWindowsRemoteControl/Services/RemoteCommandParserService.cs
ArduinoWindowsRemoteControl/Services/RemoteCommandParserService.cs
using Arduino; using ArduinoWindowsRemoteControl.Repositories; using Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArduinoWindowsRemoteControl.Services { /// <summary> /// Service that returns parsers for different remote input devices /// </summary> public class RemoteCommandParserService { #region Private Fields private DictionaryRepository _dictionaryRepository; #endregion #region Constructor public RemoteCommandParserService() { _dictionaryRepository = new DictionaryRepository(); } #endregion #region Public Methods public ArduinoRemoteCommandParser LoadArduinoCommandParser(string filename) { var dictionary = _dictionaryRepository.Load<int, RemoteCommand>(filename); return new ArduinoRemoteCommandParser(dictionary); } public void SaveArduinoCommandParser(ArduinoRemoteCommandParser commandParser, string filename) { } #endregion } }
using Arduino; using ArduinoWindowsRemoteControl.Repositories; using Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArduinoWindowsRemoteControl.Services { /// <summary> /// Service that returns parsers for different remote input devices /// </summary> public class RemoteCommandParserService { #region Private Fields private DictionaryRepository _dictionaryRepository; #endregion #region Constructor public RemoteCommandParserService() { _dictionaryRepository = new DictionaryRepository(); } #endregion #region Public Methods public ArduinoRemoteCommandParser LoadArduinoCommandParser(string filename) { var dictionary = _dictionaryRepository.Load<int, RemoteCommand>(filename); return new ArduinoRemoteCommandParser(dictionary); } public void SaveArduinoCommandParser(ArduinoRemoteCommandParser commandParser, string filename) { _dictionaryRepository.Save(commandParser.CommandsMapping, filename); } #endregion } }
Add ability to save commands mapping
Add ability to save commands mapping
C#
mit
StanislavUshakov/ArduinoWindowsRemoteControl
e6ec883084899f368847d3367f7000f409844b68
osu.Game.Rulesets.Osu/Objects/SliderTailCircle.cs
osu.Game.Rulesets.Osu/Objects/SliderTailCircle.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.Bindables; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { /// <summary> /// Note that this should not be used for timing correctness. /// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information. /// </summary> public class SliderTailCircle : SliderCircle { private readonly IBindable<int> pathVersion = new Bindable<int>(); public SliderTailCircle(Slider slider) { pathVersion.BindTo(slider.Path.Version); pathVersion.BindValueChanged(_ => Position = slider.EndPosition); } protected override HitWindows CreateHitWindows() => HitWindows.Empty; public override Judgement CreateJudgement() => new SliderRepeat.SliderRepeatJudgement(); } }
// 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.Bindables; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Judgements; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Osu.Objects { /// <summary> /// Note that this should not be used for timing correctness. /// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information. /// </summary> public class SliderTailCircle : SliderCircle { private readonly IBindable<int> pathVersion = new Bindable<int>(); public SliderTailCircle(Slider slider) { pathVersion.BindTo(slider.Path.Version); pathVersion.BindValueChanged(_ => Position = slider.EndPosition); } protected override HitWindows CreateHitWindows() => HitWindows.Empty; public override Judgement CreateJudgement() => new SliderTailJudgement(); public class SliderTailJudgement : OsuJudgement { protected override int NumericResultFor(HitResult result) => 0; public override bool AffectsCombo => false; } } }
Remove slider tail circle judgement requirements
Remove slider tail circle judgement requirements
C#
mit
peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu-new
f6d4108eb0e68db4fa3281335c44ab88e5dca71d
osu.Framework/Threading/AudioThread.cs
osu.Framework/Threading/AudioThread.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.Statistics; using System; using System.Collections.Generic; using osu.Framework.Audio; namespace osu.Framework.Threading { public class AudioThread : GameThread { public AudioThread() : base(name: "Audio") { OnNewFrame = onNewFrame; } internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[] { StatisticsCounterType.TasksRun, StatisticsCounterType.Tracks, StatisticsCounterType.Samples, StatisticsCounterType.SChannels, StatisticsCounterType.Components, }; private readonly List<AudioManager> managers = new List<AudioManager>(); private void onNewFrame() { lock (managers) { for (var i = 0; i < managers.Count; i++) { var m = managers[i]; m.Update(); } } } public void RegisterManager(AudioManager manager) { lock (managers) { if (managers.Contains(manager)) throw new InvalidOperationException($"{manager} was already registered"); managers.Add(manager); } } public void UnregisterManager(AudioManager manager) { lock (managers) managers.Remove(manager); } protected override void PerformExit() { base.PerformExit(); lock (managers) { // AudioManager's disposal triggers an un-registration while (managers.Count > 0) managers[0].Dispose(); } ManagedBass.Bass.Free(); } } }
// 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.Statistics; using System; using System.Collections.Generic; using osu.Framework.Audio; namespace osu.Framework.Threading { public class AudioThread : GameThread { public AudioThread() : base(name: "Audio") { OnNewFrame = onNewFrame; } internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[] { StatisticsCounterType.TasksRun, StatisticsCounterType.Tracks, StatisticsCounterType.Samples, StatisticsCounterType.SChannels, StatisticsCounterType.Components, }; private readonly List<AudioManager> managers = new List<AudioManager>(); private void onNewFrame() { lock (managers) { for (var i = 0; i < managers.Count; i++) { var m = managers[i]; m.Update(); } } } public void RegisterManager(AudioManager manager) { lock (managers) { if (managers.Contains(manager)) throw new InvalidOperationException($"{manager} was already registered"); managers.Add(manager); } } public void UnregisterManager(AudioManager manager) { lock (managers) managers.Remove(manager); } protected override void PerformExit() { base.PerformExit(); lock (managers) { foreach (var manager in managers) manager.Dispose(); managers.Clear(); } ManagedBass.Bass.Free(); } } }
Fix audio thread not exiting correctly
Fix audio thread not exiting correctly
C#
mit
ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework
d29bcefb9c0d27b78aab12ba978f51e3c2cff547
src/Persistence.RavenDB/RavenDBViewModelHelper.cs
src/Persistence.RavenDB/RavenDBViewModelHelper.cs
// <copyright file="RavenDBViewModelHelper.cs" company="Cognisant"> // Copyright (c) Cognisant. All rights reserved. // </copyright> namespace CR.ViewModels.Persistence.RavenDB { /// <summary> /// Helper class used for code shared between <see cref="RavenDBViewModelReader"/> and <see cref="RavenDBViewModelWriter"/>. /// </summary> // ReSharper disable once InconsistentNaming internal static class RavenDBViewModelHelper { /// <summary> /// Helper method used to generate the ID of the RavenDB document that a view model of type TEntity with specified key should be stored. /// </summary> /// <typeparam name="TEntity">The type of the View Model.</typeparam> /// <param name="key">The key of the view model.</param> /// <returns>The ID of the RavenDB document.</returns> internal static string MakeId<TEntity>(string key) => $"{typeof(TEntity).FullName}/{key}"; } }
// <copyright file="RavenDBViewModelHelper.cs" company="Cognisant"> // Copyright (c) Cognisant. All rights reserved. // </copyright> namespace CR.ViewModels.Persistence.RavenDB { /// <summary> /// Helper class used for code shared between <see cref="RavenDBViewModelReader"/> and <see cref="RavenDBViewModelWriter"/>. /// </summary> // ReSharper disable once InconsistentNaming internal static class RavenDBViewModelHelper { /// <summary> /// Helper method used to generate the ID of the RavenDB document that a view model of type TEntity with specified key should be stored. /// </summary> /// <typeparam name="TEntity">The type of the View Model.</typeparam> /// <param name="key">The key of the view model.</param> /// <returns>The ID of the RavenDB document.</returns> // ReSharper disable once InconsistentNaming internal static string MakeID<TEntity>(string key) => $"{typeof(TEntity).FullName}/{key}"; } }
Add missing changes for last commit
Add missing changes for last commit
C#
bsd-3-clause
cognisant/cr-viewmodels
80aad36f9a523c42b401e76f4a7f192de14f7388
CkanDotNet.Web/Views/Shared/Package/_Disqus.cshtml
CkanDotNet.Web/Views/Shared/Package/_Disqus.cshtml
@using CkanDotNet.Web.Models.Helpers <div class="container"> <h2 class="container-title">Comments</h2> <div class="container-content"> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = '@SettingsHelper.GetDisqusForumShortName()'; // required: replace example with your forum shortname @if (SettingsHelper.GetDisqusDeveloperModeEnabled()) { <text>var disqus_developer = 1; // developer mode is on</text> } /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </div>
@using CkanDotNet.Web.Models.Helpers <div class="container"> <h2 class="container-title">Comments</h2> <div class="container-content"> <div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = '@SettingsHelper.GetDisqusForumShortName()'; // required: replace example with your forum shortname @if (SettingsHelper.GetDisqusDeveloperModeEnabled()) { <text>var disqus_developer = 1; // developer mode is on</text> } @if (SettingsHelper.GetIframeEnabled()) { <text> function disqus_config() { this.callbacks.onNewComment = [function() { resizeFrame() }]; this.callbacks.onReady = [function() { resizeFrame() }]; } </text> } /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </div>
Add support for dynamic resizing of iframe when disqus forum loads
Add support for dynamic resizing of iframe when disqus forum loads
C#
apache-2.0
DenverDev/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,DenverDev/.NET-Wrapper-for-CKAN-API
d8559f1ad7670279438d12daabd8eefffee55fdd
uhttpsharp-demo/Program.cs
uhttpsharp-demo/Program.cs
/* * Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp * * This library 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. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using uhttpsharp.Embedded; namespace uhttpsharpdemo { class Program { static void Main(string[] args) { HttpServer.Instance.StartUp(); Console.ReadLine(); } } }
/* * Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp * * This library 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. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using uhttpsharp.Embedded; namespace uhttpsharpdemo { class Program { static void Main(string[] args) { HttpServer.Instance.Port = 8000; HttpServer.Instance.StartUp(); Console.ReadLine(); } } }
Change the port to 8000 so we can run as non-admin.
Change the port to 8000 so we can run as non-admin.
C#
lgpl-2.1
Code-Sharp/uHttpSharp,habibmasuro/uhttpsharp,int6/uhttpsharp,raistlinthewiz/uhttpsharp,lstefano71/uhttpsharp,lstefano71/uhttpsharp,raistlinthewiz/uhttpsharp,int6/uhttpsharp,habibmasuro/uhttpsharp,Code-Sharp/uHttpSharp
b9f0cb1205f0269aac53387c44c474dab5a1d0d0
AddIn/Command/MakeGridCommand.cs
AddIn/Command/MakeGridCommand.cs
namespace ExcelX.AddIn.Command { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExcelX.AddIn.Config; using Excel = Microsoft.Office.Interop.Excel; /// <summary> /// 「方眼紙」コマンド /// </summary> public class MakeGridCommand : ICommand { /// <summary> /// コマンドを実行します。 /// </summary> public void Execute() { // グリッドサイズはピクセル指定 var size = ConfigDocument.Current.Edit.Grid.Size; // ワークシートを取得 var application = Globals.ThisAddIn.Application; Excel.Workbook book = application.ActiveWorkbook; Excel.Worksheet sheet = book.ActiveSheet; // すべてのセルサイズを同一に設定 Excel.Range all = sheet.Cells; all.ColumnWidth = size * 0.118; all.RowHeight = size * 0.75; } } }
namespace ExcelX.AddIn.Command { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ExcelX.AddIn.Config; using Excel = Microsoft.Office.Interop.Excel; /// <summary> /// 「方眼紙」コマンド /// </summary> public class MakeGridCommand : ICommand { /// <summary> /// コマンドを実行します。 /// </summary> public void Execute() { // グリッドサイズはピクセル指定 var size = ConfigDocument.Current.Edit.Grid.Size; // ワークシートを取得 var application = Globals.ThisAddIn.Application; Excel.Workbook book = application.ActiveWorkbook; Excel.Worksheet sheet = book.ActiveSheet; // 環境値の取得 var cell = sheet.Range["A1"]; double x1 = 10, x2 = 20, y1, y2, a, b; cell.ColumnWidth = x1; y1 = cell.Width; cell.ColumnWidth = x2; y2 = cell.Width; a = (y2 - y1) / (x2 - x1); b = y2 - (y2 - y1) / (x2 - x1) * x2; // すべてのセルサイズを同一に設定 Excel.Range all = sheet.Cells; all.ColumnWidth = (size * 0.75 - b) / a; all.RowHeight = size * 0.75; } } }
Fix dependency of environment gap
Fix dependency of environment gap
C#
mit
garafu/ExcelExtension
094dfc698fc994fa24f75e3fe272453de853b026
GitTfs/GitTfsConstants.cs
GitTfs/GitTfsConstants.cs
using System.Text.RegularExpressions; namespace Sep.Git.Tfs { public static class GitTfsConstants { public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase); public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase); public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$"); public const string DefaultRepositoryId = "default"; // e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123 public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}"; public static readonly Regex TfsCommitInfoRegex = new Regex("^\\s*" + "git-tfs-id:\\s+" + "\\[(?<url>.+)\\]" + "(?<repository>.+);" + "C(?<changeset>\\d+)" + "\\s*$"); } }
using System.Text.RegularExpressions; namespace Sep.Git.Tfs { public static class GitTfsConstants { public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase); public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase); public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$"); public const string DefaultRepositoryId = "default"; public const string GitTfsPrefix = "git-tfs"; // e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123 public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}"; public static readonly Regex TfsCommitInfoRegex = new Regex("^\\s*" + GitTfsPrefix + "-id:\\s+" + "\\[(?<url>.+)\\]" + "(?<repository>.+);" + "C(?<changeset>\\d+)" + "\\s*$"); } }
Create a prefix for Git-Tfs metadata
Create a prefix for Git-Tfs metadata
C#
apache-2.0
NathanLBCooper/git-tfs,WolfVR/git-tfs,kgybels/git-tfs,modulexcite/git-tfs,irontoby/git-tfs,steveandpeggyb/Public,bleissem/git-tfs,guyboltonking/git-tfs,adbre/git-tfs,TheoAndersen/git-tfs,modulexcite/git-tfs,bleissem/git-tfs,andyrooger/git-tfs,timotei/git-tfs,kgybels/git-tfs,allansson/git-tfs,timotei/git-tfs,jeremy-sylvis-tmg/git-tfs,codemerlin/git-tfs,TheoAndersen/git-tfs,timotei/git-tfs,WolfVR/git-tfs,spraints/git-tfs,spraints/git-tfs,kgybels/git-tfs,pmiossec/git-tfs,jeremy-sylvis-tmg/git-tfs,vzabavnov/git-tfs,allansson/git-tfs,modulexcite/git-tfs,git-tfs/git-tfs,hazzik/git-tfs,codemerlin/git-tfs,guyboltonking/git-tfs,codemerlin/git-tfs,spraints/git-tfs,steveandpeggyb/Public,TheoAndersen/git-tfs,NathanLBCooper/git-tfs,TheoAndersen/git-tfs,irontoby/git-tfs,adbre/git-tfs,allansson/git-tfs,allansson/git-tfs,bleissem/git-tfs,hazzik/git-tfs,PKRoma/git-tfs,irontoby/git-tfs,jeremy-sylvis-tmg/git-tfs,NathanLBCooper/git-tfs,adbre/git-tfs,hazzik/git-tfs,guyboltonking/git-tfs,steveandpeggyb/Public,WolfVR/git-tfs,hazzik/git-tfs
375c88a2512fa55f4ec505ce1132b613a735b224
VkNet/Model/AudioAlbum.cs
VkNet/Model/AudioAlbum.cs
using VkNet.Utils; namespace VkNet.Model { /// <summary> /// Информация об аудиоальбоме. /// </summary> /// <remarks> /// Страница документации ВКонтакте <see href="http://vk.com/dev/audio.getAlbums"/>. /// </remarks> public class AudioAlbum { /// <summary> /// Идентификатор владельца альбома. /// </summary> public long? OwnerId { get; set; } /// <summary> /// Идентификатор альбома. /// </summary> public long? AlbumId { get; set; } /// <summary> /// Название альбома. /// </summary> public string Title { get; set; } #region Методы /// <summary> /// Разобрать из json. /// </summary> /// <param name="response">Ответ сервера.</param> /// <returns></returns> internal static AudioAlbum FromJson(VkResponse response) { var album = new AudioAlbum { OwnerId = response["owner_id"], AlbumId = response["id"], Title = response["title"] }; return album; } #endregion } }
using VkNet.Utils; namespace VkNet.Model { /// <summary> /// Информация об аудиоальбоме. /// </summary> /// <remarks> /// Страница документации ВКонтакте <see href="http://vk.com/dev/audio.getAlbums"/>. /// </remarks> public class AudioAlbum { /// <summary> /// Идентификатор владельца альбома. /// </summary> public long? OwnerId { get; set; } /// <summary> /// Идентификатор альбома. /// </summary> public long? AlbumId { get; set; } /// <summary> /// Название альбома. /// </summary> public string Title { get; set; } #region Методы /// <summary> /// Разобрать из json. /// </summary> /// <param name="response">Ответ сервера.</param> /// <returns></returns> internal static AudioAlbum FromJson(VkResponse response) { var album = new AudioAlbum { OwnerId = response["owner_id"], AlbumId = response["album_id"] ?? response["id"], Title = response["title"] }; return album; } #endregion } }
Add support for older versions API
Add support for older versions API
C#
mit
mainefremov/vk,Soniclev/vk,vknet/vk,kadkin/vk,kkohno/vk,rassvet85/vk,vknet/vk
04fc6b261c54226c9d8a4f91c9b35cdde5bed1d9
src/NQuery.Authoring/Completion/Providers/TypeCompletionProvider.cs
src/NQuery.Authoring/Completion/Providers/TypeCompletionProvider.cs
using System; using System.Collections.Generic; using System.Linq; using NQuery.Syntax; namespace NQuery.Authoring.Completion.Providers { internal sealed class TypeCompletionProvider : ICompletionProvider { public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position) { var syntaxTree = semanticModel.Compilation.SyntaxTree; var token = syntaxTree.Root.FindTokenOnLeft(position); var castExpression = token.Parent.AncestorsAndSelf() .OfType<CastExpressionSyntax>() .FirstOrDefault(c => c.AsKeyword.Span.End <= position); if (castExpression == null) return Enumerable.Empty<CompletionItem>(); return from typeName in SyntaxFacts.GetTypeNames() select GetCompletionItem(typeName); } private static CompletionItem GetCompletionItem(string typeName) { return new CompletionItem(typeName, typeName, typeName, NQueryGlyph.Type); } } }
using System; using System.Collections.Generic; using System.Linq; using NQuery.Syntax; namespace NQuery.Authoring.Completion.Providers { internal sealed class TypeCompletionProvider : ICompletionProvider { public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position) { var syntaxTree = semanticModel.Compilation.SyntaxTree; var token = syntaxTree.Root.FindTokenOnLeft(position); var castExpression = token.Parent.AncestorsAndSelf() .OfType<CastExpressionSyntax>() .FirstOrDefault(c => !c.AsKeyword.IsMissing && c.AsKeyword.Span.End <= position); if (castExpression == null) return Enumerable.Empty<CompletionItem>(); return from typeName in SyntaxFacts.GetTypeNames() select GetCompletionItem(typeName); } private static CompletionItem GetCompletionItem(string typeName) { return new CompletionItem(typeName, typeName, typeName, NQueryGlyph.Type); } } }
Fix handling of CAST in type completion provider
Fix handling of CAST in type completion provider When we are in a CAST expression, we shouldn't return types unless the position is after the AS keyword. This implies that the AS keyword must exist.
C#
mit
terrajobst/nquery-vnext
824fdc7c2db8a2f92a38e800ba67881478e4a461
ReportObject.cs
ReportObject.cs
using Microsoft.Office365.ReportingWebServiceClient.Utils; using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Microsoft.Office365.ReportingWebServiceClient { /// <summary> /// This is representing an object of the RWS Report returned /// </summary> public class ReportObject { protected Dictionary<string, string> properties = new Dictionary<string, string>(); public DateTime Date { get; set; } public virtual void LoadFromXml(XmlNode node) { properties = new Dictionary<string, string>(); foreach (XmlNode p in node) { string key = p.Name.Replace("d:", ""); properties[key] = p.InnerText.ToString(); } this.Date = StringUtil.TryParseDateTime(TryGetValue("Date"), DateTime.MinValue); } public string ConvertToXml() { string retval = null; StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true })) { new XmlSerializer(this.GetType()).Serialize(writer, this); } retval = sb.ToString(); return retval; } protected string TryGetValue(string key) { if (properties.ContainsKey(key)) { return properties[key]; } return null; } } }
using Microsoft.Office365.ReportingWebServiceClient.Utils; using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; namespace Microsoft.Office365.ReportingWebServiceClient { /// <summary> /// This is representing an object of the RWS Report returned /// </summary> public class ReportObject { protected Dictionary<string, string> properties = new Dictionary<string, string>(); // This is a Date property public DateTime Date { get; set; } public virtual void LoadFromXml(XmlNode node) { properties = new Dictionary<string, string>(); foreach (XmlNode p in node) { string key = p.Name.Replace("d:", ""); properties[key] = p.InnerText.ToString(); } this.Date = StringUtil.TryParseDateTime(TryGetValue("Date"), DateTime.MinValue); } public string ConvertToXml() { string retval = null; StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true })) { new XmlSerializer(this.GetType()).Serialize(writer, this); } retval = sb.ToString(); return retval; } protected string TryGetValue(string key) { if (properties.ContainsKey(key)) { return properties[key]; } return null; } } }
Test Commit for a GitHub from VS2015
Test Commit for a GitHub from VS2015
C#
mit
Microsoft/o365rwsclient
766e7a1d582e58e8f7e9ea2e9e38a8c549deccc8
cslatest/Csla.Test/LazyLoad/AParent.cs
cslatest/Csla.Test/LazyLoad/AParent.cs
using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.LazyLoad { [Serializable] public class AParent : Csla.BusinessBase<AParent> { private Guid _id; public Guid Id { get { return _id; } set { _id = value; PropertyHasChanged(); } } private AChildList _children; public AChildList ChildList { get { if (_children == null) { _children = new AChildList(); for (int count = 0; count < EditLevel; count++) ((Csla.Core.IUndoableObject)_children).CopyState(EditLevel); } return _children; } } public AChildList GetChildList() { return _children; } public int EditLevel { get { return base.EditLevel; } } protected override object GetIdValue() { return _id; } public AParent() { _id = Guid.NewGuid(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.LazyLoad { [Serializable] public class AParent : Csla.BusinessBase<AParent> { private Guid _id; public Guid Id { get { return _id; } set { _id = value; PropertyHasChanged(); } } private static PropertyInfo<AChildList> ChildListProperty = RegisterProperty<AChildList>(typeof(AParent), new PropertyInfo<AChildList>("ChildList", "Child list")); public AChildList ChildList { get { if (!FieldManager.FieldExists(ChildListProperty)) LoadProperty<AChildList>(ChildListProperty, new AChildList()); return GetProperty<AChildList>(ChildListProperty); } } //private AChildList _children; //public AChildList ChildList //{ // get // { // if (_children == null) // { // _children = new AChildList(); // for (int count = 0; count < EditLevel; count++) // ((Csla.Core.IUndoableObject)_children).CopyState(EditLevel); // } // return _children; // } //} public AChildList GetChildList() { if (FieldManager.FieldExists(ChildListProperty)) return ReadProperty<AChildList>(ChildListProperty); else return null; //return _children; } public int EditLevel { get { return base.EditLevel; } } protected override object GetIdValue() { return _id; } public AParent() { _id = Guid.NewGuid(); } } }
Fix bug with n-level undo of child objects.
Fix bug with n-level undo of child objects.
C#
mit
rockfordlhotka/csla,JasonBock/csla,JasonBock/csla,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,MarimerLLC/csla,ronnymgm/csla-light,BrettJaner/csla,MarimerLLC/csla,MarimerLLC/csla,BrettJaner/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light,jonnybee/csla,ronnymgm/csla-light,BrettJaner/csla
014be649834ed7973de4eca31d1ced814a63dc6c
ExoWeb/Templates/MicrosoftAjax/AjaxPage.cs
ExoWeb/Templates/MicrosoftAjax/AjaxPage.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace ExoWeb.Templates.MicrosoftAjax { /// <summary> /// Microsoft AJAX specific implementation of <see cref="ExoWeb.Templates.Page"/> that supports /// parsing and loading templates using the Microsoft AJAX syntax. /// </summary> internal class AjaxPage : Page { internal AjaxPage() { IsIE = HttpContext.Current != null && HttpContext.Current.Request.Browser.IsBrowser("IE"); } int nextControlId; internal string NextControlId { get { return "exo" + nextControlId++; } } internal bool IsIE { get; private set; } public override ITemplate Parse(string name, string template) { return Template.Parse(name, template); } public override IEnumerable<ITemplate> ParseTemplates(string source, string template) { return Block.Parse(source, template).OfType<ITemplate>(); } public override IEnumerable<ITemplate> LoadTemplates(string path) { return Template.Load(path).Cast<ITemplate>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace ExoWeb.Templates.MicrosoftAjax { /// <summary> /// Microsoft AJAX specific implementation of <see cref="ExoWeb.Templates.Page"/> that supports /// parsing and loading templates using the Microsoft AJAX syntax. /// </summary> internal class AjaxPage : Page { internal AjaxPage() { IsIE = HttpContext.Current != null && (HttpContext.Current.Request.Browser.IsBrowser("IE") || (!string.IsNullOrEmpty(HttpContext.Current.Request.UserAgent) && HttpContext.Current.Request.UserAgent.Contains("Trident"))); } int nextControlId; internal string NextControlId { get { return "exo" + nextControlId++; } } internal bool IsIE { get; private set; } public override ITemplate Parse(string name, string template) { return Template.Parse(name, template); } public override IEnumerable<ITemplate> ParseTemplates(string source, string template) { return Block.Parse(source, template).OfType<ITemplate>(); } public override IEnumerable<ITemplate> LoadTemplates(string path) { return Template.Load(path).Cast<ITemplate>(); } } }
Check the user-agent string for "Trident" in order to identify IE11 as an IE browser. This is only needed for a workaround for comments within select elements in IE below version 10 and should be abandoned when possible.
Check the user-agent string for "Trident" in order to identify IE11 as an IE browser. This is only needed for a workaround for comments within select elements in IE below version 10 and should be abandoned when possible.
C#
mit
vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb
aeeaaf0e8fd9f32e8178e406481c11dfd72184a5
samples/MusicStore/Program.cs
samples/MusicStore/Program.cs
using System; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.HttpSys; using Microsoft.Extensions.Configuration; namespace MusicStore { public static class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); var builder = new WebHostBuilder() .UseConfiguration(config) .UseIISIntegration() .UseStartup("MusicStore"); if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal)) { var environment = builder.GetSetting("environment") ?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal)) { // Set up NTLM authentication for WebListener like below. // For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or // modify the applicationHost.config to enable NTLM. builder.UseHttpSys(options => { options.Authentication.Schemes = AuthenticationSchemes.NTLM; options.Authentication.AllowAnonymous = false; }); } else { builder.UseHttpSys(); } } else { builder.UseKestrel(); } var host = builder.Build(); host.Run(); } } }
using System; using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.HttpSys; using Microsoft.Extensions.Configuration; namespace MusicStore { public static class Program { public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); var builder = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(config) .UseIISIntegration() .UseStartup("MusicStore"); if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal)) { var environment = builder.GetSetting("environment") ?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal)) { // Set up NTLM authentication for WebListener like below. // For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or // modify the applicationHost.config to enable NTLM. builder.UseHttpSys(options => { options.Authentication.Schemes = AuthenticationSchemes.NTLM; options.Authentication.AllowAnonymous = false; }); } else { builder.UseHttpSys(); } } else { builder.UseKestrel(); } var host = builder.Build(); host.Run(); } } }
Add missing call to set content root on WebHostBuilder
Add missing call to set content root on WebHostBuilder
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
c90bc0e39b124ec57604fc8727548f475faa81e8
Alexa.NET/Request/Type/Converters/DefaultRequestTypeConverter.cs
Alexa.NET/Request/Type/Converters/DefaultRequestTypeConverter.cs
namespace Alexa.NET.Request.Type { public class DefaultRequestTypeConverter : IRequestTypeConverter { public bool CanConvert(string requestType) { return requestType == "IntentRequest" || requestType == "LaunchRequest" || requestType == "SessionEndedRequest"; } public Request Convert(string requestType) { switch (requestType) { case "IntentRequest": return new IntentRequest(); case "LaunchRequest": return new LaunchRequest(); case "SessionEndedRequest": return new SessionEndedRequest(); case "System.ExceptionEncountered": return new SystemExceptionRequest(); } return null; } } }
namespace Alexa.NET.Request.Type { public class DefaultRequestTypeConverter : IRequestTypeConverter { public bool CanConvert(string requestType) { return requestType == "IntentRequest" || requestType == "LaunchRequest" || requestType == "SessionEndedRequest" || requestType == "System.ExceptionEncountered"; } public Request Convert(string requestType) { switch (requestType) { case "IntentRequest": return new IntentRequest(); case "LaunchRequest": return new LaunchRequest(); case "SessionEndedRequest": return new SessionEndedRequest(); case "System.ExceptionEncountered": return new SystemExceptionRequest(); } return null; } } }
Update default converter to handle exception type
Update default converter to handle exception type
C#
mit
stoiveyp/alexa-skills-dotnet,timheuer/alexa-skills-dotnet
0b638d87c7339e914d6c0b6fdfd74575c482c0ad
NET/Demos/Console/SoftPwm/Program.cs
NET/Demos/Console/SoftPwm/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Treehopper.Demos.SoftPwm { class Program { static void Main(string[] args) { Run(); } static TreehopperUsb board; static async void Run() { int pinNumber = 10; Console.Write("Looking for board..."); board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Board found."); Console.WriteLine(String.Format("Connecting to {0} and starting SoftPwm on Pin{1}", board, pinNumber)); await board.ConnectAsync(); board[pinNumber].SoftPwm.Enabled = true; int step = 10; int rate = 25; while (true) { for (int i = 0; i < 256; i = i + step) { board[pinNumber].SoftPwm.DutyCycle = i / 255.0; await Task.Delay(rate); } for (int i = 255; i > 0; i = i - step) { board[pinNumber].SoftPwm.DutyCycle = i / 255.0; await Task.Delay(rate); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Treehopper.Demos.SoftPwm { class Program { static void Main(string[] args) { Run(); } static TreehopperUsb board; static async void Run() { Console.Write("Looking for board..."); board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Board found."); await board.ConnectAsync(); var pin = board[1]; pin.SoftPwm.Enabled = true; pin.SoftPwm.DutyCycle = 0.8; int step = 10; int rate = 25; while (true) { for (int i = 0; i < 256; i = i + step) { pin.SoftPwm.DutyCycle = i / 255.0; await Task.Delay(rate); } for (int i = 255; i > 0; i = i - step) { pin.SoftPwm.DutyCycle = i / 255.0; await Task.Delay(rate); } } } } }
Use Pins, not ints. We ain't Arduino!
Use Pins, not ints. We ain't Arduino!
C#
mit
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
0afdf5b343941ea59f936f5692b097c23200998a
Rainy/WebService/Admin/StatusService.cs
Rainy/WebService/Admin/StatusService.cs
using ServiceStack.ServiceHost; using Rainy.Db; using ServiceStack.OrmLite; using System; using ServiceStack.Common.Web; namespace Rainy.WebService.Admin { [Route("/api/admin/status/","GET, OPTIONS", Summary = "Get status information about the server.")] [AdminPasswordRequired] public class StatusRequest : IReturn<Status> { } public class StatusService : ServiceBase { public StatusService (IDbConnectionFactory fac) : base (fac) { } public Status Get (StatusRequest req) { var s = new Status (); s.Uptime = MainClass.Uptime; s.NumberOfRequests = MainClass.ServedRequests; // determine number of users using (var conn = connFactory.OpenDbConnection ()) { s.NumberOfUser = conn.Scalar<int>("SELECT COUNT(*) FROM DBUser"); s.TotalNumberOfNotes = conn.Scalar<int>("SELECT COUNT(*) FROM DBNote"); if (s.NumberOfUser > 0) s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser; }; return s; } } public class Status { public DateTime Uptime { get; set; } public int NumberOfUser { get; set; } public long NumberOfRequests { get; set; } public int TotalNumberOfNotes { get; set; } public float AverageNotesPerUser { get; set; } } }
using ServiceStack.ServiceHost; using Rainy.Db; using ServiceStack.OrmLite; using System; using ServiceStack.Common.Web; using Tomboy.Db; namespace Rainy.WebService.Admin { [Route("/api/admin/status/","GET, OPTIONS", Summary = "Get status information about the server.")] [AdminPasswordRequired] public class StatusRequest : IReturn<Status> { } public class StatusService : ServiceBase { public StatusService (IDbConnectionFactory fac) : base (fac) { } public Status Get (StatusRequest req) { var s = new Status (); s.Uptime = MainClass.Uptime; s.NumberOfRequests = MainClass.ServedRequests; // determine number of users using (var conn = connFactory.OpenDbConnection ()) { s.NumberOfUser = (int)conn.Count<DBUser> (); s.TotalNumberOfNotes = (int)conn.Count<DBNote> (); if (s.NumberOfUser > 0) s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser; }; return s; } } public class Status { public DateTime Uptime { get; set; } public int NumberOfUser { get; set; } public long NumberOfRequests { get; set; } public int TotalNumberOfNotes { get; set; } public float AverageNotesPerUser { get; set; } } }
Use ORM instead of open-coded SQL
Use ORM instead of open-coded SQL
C#
agpl-3.0
Dynalon/Rainy,Dynalon/Rainy,Dynalon/Rainy,Dynalon/Rainy
9999830b506028ef9c1b25cce697bbcd70552875
src/Abc.Zebus/Util/TcpUtil.cs
src/Abc.Zebus/Util/TcpUtil.cs
using System; using System.Net; using System.Net.Sockets; namespace Abc.Zebus.Util { internal static class TcpUtil { public static int GetRandomUnusedPort() { var listener = new TcpListener(IPAddress.Any, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } public static bool IsPortUnused(int port) { var listener = new TcpListener(IPAddress.Any, port); try { listener.Start(); } catch (Exception) { return false; } listener.Stop(); return true; } } }
using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; namespace Abc.Zebus.Util { internal static class TcpUtil { public static int GetRandomUnusedPort() { var listener = new TcpListener(IPAddress.Any, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } public static bool IsPortUnused(int port) { var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); var activeTcpListeners = ipGlobalProperties.GetActiveTcpListeners(); return activeTcpListeners.All(endpoint => endpoint.Port != port); } } }
Change IsPortUnused() implementation because of SO_REUSEPORT on Linux
Change IsPortUnused() implementation because of SO_REUSEPORT on Linux
C#
mit
Abc-Arbitrage/Zebus
3b42e9fd8746d7475ed699cac6394e617e8083ae
CEComms/ClassLibrary1/Communications/Twilio/User/Usage.cs
CEComms/ClassLibrary1/Communications/Twilio/User/Usage.cs
using CommentEverythingCryptography.Encryption; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Twilio; namespace CEComms.Communications.Twilio.User { public class Usage { public double GetUsageThisMonth() { IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES); TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER)); UsageResult totalPrice = twilio.ListUsage("totalprice", "ThisMonth"); UsageRecord record = totalPrice.UsageRecords[0]; return record.Usage; } public double GetSMSCountToday() { IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES); TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER)); UsageResult totalSent = twilio.ListUsage("sms", "Today"); UsageRecord record = totalSent.UsageRecords[0]; return record.Usage; } } }
using CommentEverythingCryptography.Encryption; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Twilio; namespace CEComms.Communications.Twilio.User { public class Usage { public decimal GetUsageThisMonth() { IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES); TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER)); UsageResult totalPrice = twilio.ListUsage("totalprice", "ThisMonth"); UsageRecord record = totalPrice.UsageRecords[0]; return (decimal) record.Usage; } public int GetSMSCountToday() { IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES); TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER)); UsageResult totalSent = twilio.ListUsage("sms", "Today"); UsageRecord record = totalSent.UsageRecords[0]; return (int) Math.Round(record.Usage); } } }
Return int or decimal for usage stats
Return int or decimal for usage stats
C#
mit
MasterOfSomeTrades/CommentEverythingCommunications
bed5e857df7d2af44ae5f4bbfa304f04be741da1
osu.Game/Rulesets/Mods/IApplicableToAudio.cs
osu.Game/Rulesets/Mods/IApplicableToAudio.cs
using System; using System.Collections.Generic; using System.Text; namespace osu.Game.Rulesets.Mods { public interface IApplicableToAudio : IApplicableToTrack, IApplicableToSample { } }
// 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. namespace osu.Game.Rulesets.Mods { public interface IApplicableToAudio : IApplicableToTrack, IApplicableToSample { } }
Add missing license header and remove unused usings
Add missing license header and remove unused usings
C#
mit
peppy/osu-new,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu
1488a3767c77ce533f095a9e220773d099c99e61
src/Glimpse.Common/Reflection/ReflectionDiscoverableCollection.cs
src/Glimpse.Common/Reflection/ReflectionDiscoverableCollection.cs
using System; using System.Collections; using System.Collections.Generic; namespace Glimpse { public class ReflectionDiscoverableCollection<T> : List<T>, IDiscoverableCollection<T> { private readonly ITypeService _typeService; public ReflectionDiscoverableCollection(ITypeService typeService) { _typeService = typeService; CoreLibarary = "Glimpse"; } public string CoreLibarary { get; set; } public void Discover() { var instances = _typeService.Resolve<T>(CoreLibarary); AddRange(instances); } } }
using System; using System.Collections; using System.Collections.Generic; namespace Glimpse { public class ReflectionDiscoverableCollection<T> : List<T>, IDiscoverableCollection<T> { private readonly ITypeService _typeService; public ReflectionDiscoverableCollection(ITypeService typeService) { _typeService = typeService; CoreLibarary = "Glimpse.Common"; } public string CoreLibarary { get; set; } public void Discover() { var instances = _typeService.Resolve<T>(CoreLibarary); AddRange(instances); } } }
Update root lib to Glimpse.Common
Update root lib to Glimpse.Common
C#
mit
Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype
0bd8ea6968155e7a43865413149ad13c40159873
NFig/DefaultValueAttribute.cs
NFig/DefaultValueAttribute.cs
using System; namespace NFig { [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public abstract class DefaultSettingValueAttribute : Attribute { public object DefaultValue { get; protected set; } public object SubApp { get; protected set; } public object Tier { get; protected set; } public object DataCenter { get; protected set; } public bool AllowOverrides { get; protected set; } = true; } }
using System; namespace NFig { /// <summary> /// This is the base class for all NFig attributes which specify default values, except for the <see cref="SettingAttribute"/> itself. This attribute is /// abstract because you should provide the attributes which make sense for your individual setup. The subApp/tier/dataCenter parameters in inheriting /// attributes should be strongly typed (rather than using "object"), and match the generic parameters used for the NFigStore and Settings object. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] public abstract class DefaultSettingValueAttribute : Attribute { /// <summary> /// The value of the default being applied. This must be either a convertable string, or a literal value whose type matches that of the setting. For /// encrypted settings, a default value must always be an encrypted string. /// </summary> public object DefaultValue { get; protected set; } /// <summary> /// The sub-app which the default is applicable to. If null or the zero-value, it is considered applicable to the "Global" app, as well as any sub-app /// which does not have another default applied. If your application only uses the Global app (no sub-apps), then you should not include this parameter /// in inheriting attributes. /// </summary> public object SubApp { get; protected set; } /// <summary> /// The deployment tier (e.g. local/dev/prod) which the default is applicable to. If null or the zero-value, the default is applicable to any tier. /// </summary> public object Tier { get; protected set; } /// <summary> /// The data center which the default is applicable to. If null or the zero-value, the default is applicable to any data center. /// </summary> public object DataCenter { get; protected set; } /// <summary> /// Specifies whether NFig should accept runtime overrides for this default. Note that this only applies to environments where this particular default /// is the active default. For example, if you set an default for Tier=Prod/DataCenter=Any which DOES NOT allow defaults, and another default for /// Tier=Prod/DataCenter=East which DOES allow overrides, then you will be able to set overrides in Prod/East, but you won't be able to set overrides /// in any other data center. /// </summary> public bool AllowOverrides { get; protected set; } = true; } }
Add XML docs for DefaultSettingValueAttribute
Add XML docs for DefaultSettingValueAttribute
C#
mit
NFig/NFig
c12c7de949d6b7cd680ec3c75edc4b2b6e410fae
SteamShutdown/App.cs
SteamShutdown/App.cs
using System; namespace SteamShutdown { public class App { public int ID { get; set; } public string Name { get; set; } public int State { get; set; } /// <summary> /// Returns a value indicating whether the game is being downloaded. Includes games in queue for download. /// </summary> public bool IsDownloading { get { return CheckDownloading(State); } } /// <summary> /// Returns a value indicating whether the game is being downloaded. Includes games in queue for download. /// </summary> /// <param name="appState"></param> /// <returns></returns> public static bool CheckDownloading(int appState) { // 6: In queue for update // 1026: In queue // 1042: download running return appState == 6 || appState == 1026 || appState == 1042 || appState == 1062 || appState == 1030; } public override string ToString() { return Name; } } }
namespace SteamShutdown { public class App { public int ID { get; set; } public string Name { get; set; } public int State { get; set; } /// <summary> /// Returns a value indicating whether the game is being downloaded. /// </summary> public bool IsDownloading => CheckDownloading(State); /// <summary> /// Returns a value indicating whether the game is being downloaded. /// </summary> public static bool CheckDownloading(int appState) { // The second bit defines if anything for the app needs to be downloaded // Doesn't matter if queued, download running and so on return IsBitSet(appState, 1); } public override string ToString() { return Name; } private static bool IsBitSet(int b, int pos) { return (b & (1 << pos)) != 0; } } }
Check for specific bit now to check if a game is downloaded at the moment
Check for specific bit now to check if a game is downloaded at the moment
C#
mit
akorb/SteamShutdown
2a35aec7a66d63c3298d2d89304148b8c8b9b5dc
src/StructuredLogger/BinaryLog.cs
src/StructuredLogger/BinaryLog.cs
using System.Diagnostics; using System.IO; namespace Microsoft.Build.Logging.StructuredLogger { public class BinaryLog { public static Build ReadBuild(string filePath) { var eventSource = new BinaryLogReplayEventSource(); byte[] sourceArchive = null; eventSource.OnBlobRead += (kind, bytes) => { if (kind == BinaryLogRecordKind.ProjectImportArchive) { sourceArchive = bytes; } }; StructuredLogger.SaveLogToDisk = false; StructuredLogger.CurrentBuild = null; var structuredLogger = new StructuredLogger(); structuredLogger.Parameters = "build.buildlog"; structuredLogger.Initialize(eventSource); var sw = Stopwatch.StartNew(); eventSource.Replay(filePath); var elapsed = sw.Elapsed; var build = StructuredLogger.CurrentBuild; StructuredLogger.CurrentBuild = null; if (build == null) { build = new Build() { Succeeded = false }; build.AddChild(new Error() { Text = "Error when opening the file: " + filePath }); } var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip"); if (sourceArchive == null && File.Exists(projectImportsZip)) { sourceArchive = File.ReadAllBytes(projectImportsZip); } build.SourceFilesArchive = sourceArchive; // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() }); return build; } } }
using System.Diagnostics; using System.IO; namespace Microsoft.Build.Logging.StructuredLogger { public class BinaryLog { public static Build ReadBuild(string filePath) { var eventSource = new BinaryLogReplayEventSource(); byte[] sourceArchive = null; eventSource.OnBlobRead += (kind, bytes) => { if (kind == BinaryLogRecordKind.ProjectImportArchive) { sourceArchive = bytes; } }; StructuredLogger.SaveLogToDisk = false; StructuredLogger.CurrentBuild = null; var structuredLogger = new StructuredLogger(); structuredLogger.Parameters = "build.buildlog"; structuredLogger.Initialize(eventSource); var sw = Stopwatch.StartNew(); eventSource.Replay(filePath); var elapsed = sw.Elapsed; structuredLogger.Shutdown(); var build = StructuredLogger.CurrentBuild; StructuredLogger.CurrentBuild = null; if (build == null) { build = new Build() { Succeeded = false }; build.AddChild(new Error() { Text = "Error when opening the file: " + filePath }); } var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip"); if (sourceArchive == null && File.Exists(projectImportsZip)) { sourceArchive = File.ReadAllBytes(projectImportsZip); } build.SourceFilesArchive = sourceArchive; // build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() }); return build; } } }
Fix a bug where it didn't read .binlog files correctly.
Fix a bug where it didn't read .binlog files correctly.
C#
mit
KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog
8db9c9714facaba021d5e2c3126cef7566fcfad0
src/Wave.ServiceHosting.IIS/IISQueueNameResolver.cs
src/Wave.ServiceHosting.IIS/IISQueueNameResolver.cs
/* Copyright 2014 Jonathan Holland. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Diagnostics; using Wave.Defaults; namespace Wave.ServiceHosting.IIS { /// <summary> /// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue. /// </summary> public class IISQueueNameResolver : DefaultQueueNameResolver { public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { } public override string GetPrimaryQueueName() { return String.Format("{0}_{1}", base.GetPrimaryQueueName(), Environment.MachineName); } } }
/* Copyright 2014 Jonathan Holland. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Diagnostics; using Wave.Defaults; namespace Wave.ServiceHosting.IIS { /// <summary> /// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue. /// </summary> public class IISQueueNameResolver : DefaultQueueNameResolver { public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { } public override string GetPrimaryQueueName() { return String.Format("{0}_{1}_{2}", base.GetPrimaryQueueName(), Environment.MachineName, Process.GetCurrentProcess().Id ); } } }
Append IIS queues with worker PID.
Append IIS queues with worker PID.
C#
apache-2.0
WaveServiceBus/WaveServiceBus
c0062d84fc51ba07392e9146e2dabc115e0aa8e1
src/core/JustCli/Commands/CommandLineHelpCommand.cs
src/core/JustCli/Commands/CommandLineHelpCommand.cs
namespace JustCli.Commands { public class CommandLineHelpCommand : ICommand { public ICommandRepository CommandRepository { get; set; } public IOutput Output { get; set; } public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output) { CommandRepository = commandRepository; Output = output; } public bool Execute() { var commandsInfo = CommandRepository.GetCommandsInfo(); Output.WriteInfo("Command list:"); foreach (var commandInfo in commandsInfo) { Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description)); } return true; } } }
namespace JustCli.Commands { public class CommandLineHelpCommand : ICommand { public ICommandRepository CommandRepository { get; set; } public IOutput Output { get; set; } public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output) { CommandRepository = commandRepository; Output = output; } public bool Execute() { var commandsInfo = CommandRepository.GetCommandsInfo(); if (commandsInfo.Count == 0) { Output.WriteInfo("There are no commands."); return true; } Output.WriteInfo("Command list:"); foreach (var commandInfo in commandsInfo) { Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description)); } return true; } } }
Add "There are no commands".
Add "There are no commands".
C#
mit
jden123/JustCli
a5f9202d5a95d9f1a1766948a68682dd8897b459
src/jmespath.net/Utils/JTokens.cs
src/jmespath.net/Utils/JTokens.cs
using System; using Newtonsoft.Json.Linq; namespace DevLab.JmesPath.Utils { public static class JTokens { public static JToken Null = JToken.Parse("null"); public static JToken True = JToken.Parse("true"); public static JToken False = JToken.Parse("false"); public static bool IsFalse(JToken token) { // A false value corresponds to any of the following conditions: // Empty list: ``[]`` // Empty object: ``{}`` // Empty string: ``""`` // False boolean: ``false`` // Null value: ``null`` var array = token as JArray; if (array != null && array.Count == 0) return true; var @object = token as JObject; if (@object != null && @object.Count == 0) return true; var value = token as JValue; if (value != null) { switch (token.Type) { case JTokenType.Bytes: case JTokenType.Date: case JTokenType.Guid: case JTokenType.String: return token.Value<String>() == ""; case JTokenType.Boolean: return token.Value<Boolean>() == false; case JTokenType.Null: return true; } } return false; } } }
using System; using Newtonsoft.Json.Linq; namespace DevLab.JmesPath.Utils { public static class JTokens { public static JToken Null = JToken.Parse("null"); public static JToken True = JToken.Parse("true"); public static JToken False = JToken.Parse("false"); public static bool IsFalse(JToken token) { // A false value corresponds to any of the following conditions: // Empty list: ``[]`` // Empty object: ``{}`` // Empty string: ``""`` // False boolean: ``false`` // Null value: ``null`` var array = token as JArray; if (array != null && array.Count == 0) return true; var @object = token as JObject; if (@object != null && @object.Count == 0) return true; var value = token as JValue; if (value != null) { switch (token.Type) { case JTokenType.Bytes: case JTokenType.Date: case JTokenType.Guid: case JTokenType.String: case JTokenType.TimeSpan: case JTokenType.Uri: return token.Value<String>() == ""; case JTokenType.Boolean: return token.Value<Boolean>() == false; case JTokenType.Null: return true; } } return false; } } }
Fix - Included some missing cases for JSON string types.
Fix - Included some missing cases for JSON string types.
C#
apache-2.0
jdevillard/JmesPath.Net
7d190a1befe14eb848db18dfbbea797c56d3d45a
src/Plugins/Torrents/Hadouken.Plugins.Torrents/Rpc/TorrentsServices.cs
src/Plugins/Torrents/Hadouken.Plugins.Torrents/Rpc/TorrentsServices.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Hadouken.Framework.Rpc; using Hadouken.Plugins.Torrents.BitTorrent; namespace Hadouken.Plugins.Torrents.Rpc { public class TorrentsServices : IJsonRpcService { private readonly IBitTorrentEngine _torrentEngine; public TorrentsServices(IBitTorrentEngine torrentEngine) { _torrentEngine = torrentEngine; } [JsonRpcMethod("torrents.start")] public bool Start(string infoHash) { var manager = _torrentEngine.Get(infoHash); if (manager == null) return false; manager.Start(); return true; } [JsonRpcMethod("torrents.stop")] public bool Stop(string infoHash) { var manager = _torrentEngine.Get(infoHash); if (manager == null) return false; manager.Stop(); return true; } [JsonRpcMethod("torrents.list")] public object List() { var torrents = _torrentEngine.TorrentManagers; return (from t in torrents select new { t.Torrent.Name, t.Torrent.Size }).ToList(); } [JsonRpcMethod("torrents.addFile")] public object AddFile(byte[] data, string savePath, string label) { var torrent = _torrentEngine.Add(data, savePath, label); return torrent; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Hadouken.Framework.Rpc; using Hadouken.Plugins.Torrents.BitTorrent; namespace Hadouken.Plugins.Torrents.Rpc { public class TorrentsServices : IJsonRpcService { private readonly IBitTorrentEngine _torrentEngine; public TorrentsServices(IBitTorrentEngine torrentEngine) { _torrentEngine = torrentEngine; } [JsonRpcMethod("torrents.start")] public bool Start(string infoHash) { var manager = _torrentEngine.Get(infoHash); if (manager == null) return false; manager.Start(); return true; } [JsonRpcMethod("torrents.stop")] public bool Stop(string infoHash) { var manager = _torrentEngine.Get(infoHash); if (manager == null) return false; manager.Stop(); return true; } [JsonRpcMethod("torrents.list")] public object List() { var torrents = _torrentEngine.TorrentManagers; return (from t in torrents select new { t.Torrent.Name, t.Torrent.Size }).ToList(); } [JsonRpcMethod("torrents.addFile")] public object AddFile(byte[] data, string savePath, string label) { var manager = _torrentEngine.Add(data, savePath, label); return new { manager.Torrent.Name, manager.Torrent.Size }; } } }
Return simple object representing the torrent.
Return simple object representing the torrent.
C#
mit
yonglehou/hadouken,vktr/hadouken,Robo210/hadouken,vktr/hadouken,yonglehou/hadouken,Robo210/hadouken,vktr/hadouken,Robo210/hadouken,vktr/hadouken,yonglehou/hadouken,Robo210/hadouken
52127b123c745bb50239809ab61f2128e052ddc5
src/VisualStudio/PowershellScripts.cs
src/VisualStudio/PowershellScripts.cs
namespace NuGet.VisualStudio { public class PowerShellScripts { public static readonly string Install = "install.ps1"; public static readonly string Uninstall = "uninstall.ps1"; public static readonly string Init = "init.ps1"; } }
namespace NuGet.VisualStudio { public static class PowerShellScripts { public static readonly string Install = "install.ps1"; public static readonly string Uninstall = "uninstall.ps1"; public static readonly string Init = "init.ps1"; } }
Make PowerShellScripts class static per review.
Make PowerShellScripts class static per review.
C#
apache-2.0
mdavid/nuget,mdavid/nuget
e7471bcc9e8d1e69a13ee51be180241358f11e7f
1-hello-world/Startup.cs
1-hello-world/Startup.cs
// Copyright(c) 2015 Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; namespace GoogleCloudSamples { public class Startup { // This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
// Copyright(c) 2015 Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // [START sample] using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; namespace GoogleCloudSamples { public class Startup { // This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } } // [END sample]
Add a regionTag for document inclusion.
Add a regionTag for document inclusion. Change-Id: Ia86062b8fbf5afd1c455ea848da47be0e22d5b43
C#
apache-2.0
GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet
0b43545ae0f4dd71ecfd8c270512bc47634f47d5
src/Discord.Net.Commands/ModuleBase.cs
src/Discord.Net.Commands/ModuleBase.cs
using System.Threading.Tasks; namespace Discord.Commands { public abstract class ModuleBase { public CommandContext Context { get; internal set; } protected virtual async Task ReplyAsync(string message, bool isTTS = false, RequestOptions options = null) { await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false); } } }
using System.Threading.Tasks; namespace Discord.Commands { public abstract class ModuleBase { public CommandContext Context { get; internal set; } protected virtual async Task<IUserMessage> ReplyAsync(string message, bool isTTS = false, RequestOptions options = null) { return await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false); } } }
Update ReplyAsync Task to return the sent message.
Update ReplyAsync Task to return the sent message.
C#
mit
RogueException/Discord.Net,Confruggy/Discord.Net,AntiTcb/Discord.Net,LassieME/Discord.Net
7a7309b48b8f929eb5e2e321c01c1515879d041c
Proto/Assets/Scripts/UI/SceneSelector.cs
Proto/Assets/Scripts/UI/SceneSelector.cs
using UnityEngine; using UnityEngine.UI; public class SceneSelector : MonoBehaviour { [SerializeField] private Text _levelName; [SerializeField] private string[] _levels; [SerializeField] private Button _leftArrow; [SerializeField] private Button _rightArrow; private int pos = 0; private LeaderboardUI _leaderboardUI; private void Start() { _leaderboardUI = FindObjectOfType<LeaderboardUI>(); _levelName.text = _levels[pos]; _leftArrow.gameObject.SetActive(false); if (_levels.Length <= 1) _rightArrow.gameObject.SetActive(false); } public void LeftArrowClick() { _levelName.text = _levels[--pos]; if (pos == 0) _leftArrow.gameObject.SetActive(false); if (_levels.Length > 1) _rightArrow.gameObject.SetActive(true); _leaderboardUI.LoadScene(_levels[pos]); } public void RightArrowClick() { _levelName.text = _levels[++pos]; if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false); _leftArrow.gameObject.SetActive(true); _leaderboardUI.LoadScene(_levels[pos]); } }
using System; using UnityEngine; using UnityEngine.UI; public class SceneSelector : MonoBehaviour { [SerializeField] private Text _levelName; [SerializeField] private string[] _levels; [SerializeField] private Button _leftArrow; [SerializeField] private Button _rightArrow; private int pos = 0; private LeaderboardUI _leaderboardUI; private void Start() { _leaderboardUI = FindObjectOfType<LeaderboardUI>(); var levelShown = FindObjectOfType<LevelToLoad>().GetLevelToLoad(); pos = GetPosOfLevelShown(levelShown); _levelName.text = _levels[pos]; UpdateArrows(); } private int GetPosOfLevelShown(string levelShown) { for (var i = 0; i < _levels.Length; ++i) { var level = _levels[i]; if (level.IndexOf(levelShown, StringComparison.InvariantCultureIgnoreCase) > -1) return i; } //Defaults at loading the first entry if nothing found return 0; } public void LeftArrowClick() { _levelName.text = _levels[--pos]; _leaderboardUI.LoadScene(_levels[pos]); UpdateArrows(); } public void RightArrowClick() { _levelName.text = _levels[++pos]; _leaderboardUI.LoadScene(_levels[pos]); UpdateArrows(); } private void UpdateArrows() { _leftArrow.gameObject.SetActive(true); _rightArrow.gameObject.SetActive(true); if (pos == 0) _leftArrow.gameObject.SetActive(false); if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false); } }
Update the level selector input at the bottom of the leaderboard
Update the level selector input at the bottom of the leaderboard
C#
mit
DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17
7e7d6b14a6331db71e9e574f480342eb391a10ad
AngleSharp/Foundation/TaskEx.cs
AngleSharp/Foundation/TaskEx.cs
namespace AngleSharp { using System.Collections.Generic; using System.Threading.Tasks; /// <summary> /// Simple wrapper for static methods of Task, which are missing in older /// versions of the .NET-Framework. /// </summary> static class TaskEx { /// <summary> /// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to /// same naming as TaskEx in BCL.Async. /// </summary> public static Task WhenAll(params Task[] tasks) { return Task.WhenAll(tasks); } /// <summary> /// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to /// same naming as TaskEx in BCL.Async. /// </summary> public static Task WhenAll(IEnumerable<Task> tasks) { return Task.WhenAll(tasks); } /// <summary> /// Wrapper for Task.FromResult, but also works with .NET 4 and SL due /// to same naming as TaskEx in BCL.Async. /// </summary> public static Task<TResult> FromResult<TResult>(TResult result) { return Task.FromResult(result); } } }
namespace System.Threading.Tasks { using System.Collections.Generic; /// <summary> /// Simple wrapper for static methods of Task, which are missing in older /// versions of the .NET-Framework. /// </summary> static class TaskEx { /// <summary> /// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to /// same naming as TaskEx in BCL.Async. /// </summary> public static Task WhenAll(params Task[] tasks) { return Task.WhenAll(tasks); } /// <summary> /// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to /// same naming as TaskEx in BCL.Async. /// </summary> public static Task WhenAll(IEnumerable<Task> tasks) { return Task.WhenAll(tasks); } /// <summary> /// Wrapper for Task.FromResult, but also works with .NET 4 and SL due /// to same naming as TaskEx in BCL.Async. /// </summary> public static Task<TResult> FromResult<TResult>(TResult result) { return Task.FromResult(result); } } }
Use official namespace (better for fallback)
Use official namespace (better for fallback)
C#
mit
FlorianRappl/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,FlorianRappl/AngleSharp
6ab86212e3150cfed1ae1b1a6ffef027ff0c3b09
Battery-Commander.Web/Services/UnitService.cs
Battery-Commander.Web/Services/UnitService.cs
using BatteryCommander.Web.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Services { public class UnitService { public static async Task<Unit> Get(Database db, int unitId) { return (await List(db, includeIgnored: true)).Single(unit => unit.Id == unitId); } public static async Task<IEnumerable<Unit>> List(Database db, Boolean includeIgnored = false) { return await db .Units .Include(unit => unit.Vehicles) .Include(unit => unit.Soldiers) .ThenInclude(soldier => soldier.ABCPs) .Include(unit => unit.Soldiers) .ThenInclude(soldier => soldier.APFTs) .Include(unit => unit.Soldiers) .ThenInclude(soldier => soldier.SSDSnapshots) .Where(unit => includeIgnored || !unit.IgnoreForReports) .OrderBy(unit => unit.Name) .ToListAsync(); } } }
using BatteryCommander.Web.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Services { public class UnitService { public static async Task<Unit> Get(Database db, int unitId) { return (await List(db)).Single(unit => unit.Id == unitId); } public static async Task<IEnumerable<Unit>> List(Database db) { return await db .Units .Include(unit => unit.Vehicles) .Include(unit => unit.Soldiers) .ThenInclude(soldier => soldier.ABCPs) .Include(unit => unit.Soldiers) .ThenInclude(soldier => soldier.APFTs) .Include(unit => unit.Soldiers) .ThenInclude(soldier => soldier.SSDSnapshots) .OrderBy(unit => unit.Name) .ToListAsync(); } } }
Remove unit service reference to ignore for reporting
Remove unit service reference to ignore for reporting
C#
mit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
1f7582b57d63e5fcbea2370f25daa2b1bf1869f4
PackageExplorer/PublishUrlValidationRule.cs
PackageExplorer/PublishUrlValidationRule.cs
using System; using System.Windows.Controls; namespace PackageExplorer { public class PublishUrlValidationRule : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string stringValue = (string)value; Uri url; if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) { if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)) { return ValidationResult.ValidResult; } else { return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address."); } } else { return new ValidationResult(false, "Invalid publish url."); } } } }
using System; using System.Windows.Controls; namespace PackageExplorer { public class PublishUrlValidationRule : ValidationRule { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string stringValue = (string)value; Uri url; if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) { if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) || url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { return ValidationResult.ValidResult; } else { return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address."); } } else { return new ValidationResult(false, "Invalid publish url."); } } } }
Fix binding validation which disallow publishing to HTTPS addresses.
Fix binding validation which disallow publishing to HTTPS addresses.
C#
mit
campersau/NuGetPackageExplorer,dsplaisted/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,BreeeZe/NuGetPackageExplorer
c434a9587743ed71a9ab76a0f92811df27c3a4f9
DDSReader/DDSReader.Console/Program.cs
DDSReader/DDSReader.Console/Program.cs
using System; namespace DDSReader.Console { class Program { static void Main(string[] args) { var dds = new DDSImage(args[0]); dds.Save(args[1]); } } }
using System; using System.IO; namespace DDSReader.Console { class Program { static void Main(string[] args) { if (args.Length != 2) { System.Console.WriteLine("ERROR: input and output file required\n"); Environment.Exit(1); } var input = args[0]; var output = args[1]; if (!File.Exists(input)) { System.Console.WriteLine("ERROR: input file does not exist\n"); Environment.Exit(1); } try { var dds = new DDSImage(input); dds.Save(output); } catch (Exception e) { System.Console.WriteLine("ERROR: failed to convert DDS file\n"); System.Console.WriteLine(e); Environment.Exit(1); } if (File.Exists(output)) { System.Console.WriteLine("Successfully created " + output); } else { System.Console.WriteLine("ERROR: something went wrong!\n"); Environment.Exit(1); } } } }
Add exception handling to console
Add exception handling to console
C#
mit
andburn/dds-reader
394970a1e138139eb78ab8f9494c6649dccdf26d
CIV.Ccs/Processes/PrefixProcess.cs
CIV.Ccs/Processes/PrefixProcess.cs
using System; using System.Collections.Generic; using CIV.Common; namespace CIV.Ccs { class PrefixProcess : CcsProcess { public String Label { get; set; } public CcsProcess Inner { get; set; } protected override IEnumerable<Transition> EnumerateTransitions() { return new List<Transition>{ new Transition{ Label = Label, Process = Inner } }; } protected override string BuildRepr() { return $"{Label}{Const.prefix}{Inner}"; } } }
using System; using System.Collections.Generic; using CIV.Common; namespace CIV.Ccs { class PrefixProcess : CcsProcess { public String Label { get; set; } public CcsProcess Inner { get; set; } protected override IEnumerable<Transition> EnumerateTransitions() { yield return new Transition { Label = Label, Process = Inner }; } protected override string BuildRepr() { return $"{Label}{Const.prefix}{Inner}"; } } }
Use “yield” instead of List for GetTransitions
Use “yield” instead of List for GetTransitions
C#
mit
lou1306/CIV,lou1306/CIV
2680454fda31eb6cdc1f105e595775a53331770c
FluentMetacritic/Net/HttpClientWrapper.cs
FluentMetacritic/Net/HttpClientWrapper.cs
using System.Net.Http; using System.Threading.Tasks; namespace FluentMetacritic.Net { public class HttpClientWrapper : IHttpClient { private static readonly HttpClient Client = new HttpClient(); public async Task<string> GetContentAsync(string address) { return await Client.GetStringAsync(address); } } }
using System.Net.Http; using System.Threading.Tasks; namespace FluentMetacritic.Net { public class HttpClientWrapper : IHttpClient { private static readonly HttpClient Client; static HttpClientWrapper() { Client = new HttpClient(); Client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36"); } public async Task<string> GetContentAsync(string address) { return await Client.GetStringAsync(address); } } }
Set UserAgent on HTTP Client.
Set UserAgent on HTTP Client.
C#
mit
lewishenson/FluentMetacritic,lewishenson/FluentMetacritic
3edcea6e8c5607bd1a4964201f4df60ac8583e61
AgileMapper/ObjectPopulation/ExistingOrDefaultValueDataSourceFactory.cs
AgileMapper/ObjectPopulation/ExistingOrDefaultValueDataSourceFactory.cs
namespace AgileObjects.AgileMapper.ObjectPopulation { using System.Linq.Expressions; using DataSources; using Extensions; using Members; internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory { public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory(); public IDataSource Create(IMemberMappingData mappingData) => mappingData.MapperData.TargetMember.IsReadable ? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData) : DefaultValueDataSourceFactory.Instance.Create(mappingData); private class ExistingMemberValueOrEmptyDataSource : DataSourceBase { public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData) : base(mapperData.SourceMember, GetValue(mapperData), mapperData) { } private static Expression GetValue(IMemberMapperData mapperData) { var existingValue = mapperData.GetTargetMemberAccess(); if (!mapperData.TargetMember.IsEnumerable) { return existingValue; } var existingValueNotNull = existingValue.GetIsNotDefaultComparison(); var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation(); return Expression.Condition( existingValueNotNull, existingValue, emptyEnumerable, existingValue.Type); } } } }
namespace AgileObjects.AgileMapper.ObjectPopulation { using System.Linq.Expressions; using DataSources; using Members; internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory { public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory(); public IDataSource Create(IMemberMappingData mappingData) => mappingData.MapperData.TargetMember.IsReadable ? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData) : DefaultValueDataSourceFactory.Instance.Create(mappingData); private class ExistingMemberValueOrEmptyDataSource : DataSourceBase { public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData) : base(mapperData.SourceMember, GetValue(mapperData), mapperData) { } private static Expression GetValue(IMemberMapperData mapperData) { var existingValue = mapperData.GetTargetMemberAccess(); if (!mapperData.TargetMember.IsEnumerable) { return existingValue; } var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation(); return Expression.Coalesce(existingValue, emptyEnumerable); } } } }
Revert "Using ternary instead of coalesce in fallback enumerable value selection"
Revert "Using ternary instead of coalesce in fallback enumerable value selection" This reverts commit 1f2b459fd70323866b9443e388a77368e194e5ed.
C#
mit
agileobjects/AgileMapper
6c723d3788fe0420e6a09607031068928c96de91
IntegrationEngine.Tests/JobProcessor/MessageQueueListenerManagerTest.cs
IntegrationEngine.Tests/JobProcessor/MessageQueueListenerManagerTest.cs
using BeekmanLabs.UnitTesting; using IntegrationEngine.JobProcessor; using NUnit.Framework; using Moq; using System; using System.Threading; namespace IntegrationEngine.Tests.JobProcessor { public class MessageQueueListenerManagerTest : TestBase<MessageQueueListenerManager> { public Mock<MessageQueueListenerFactory> MockMessageQueueListenerFactory { get; set; } [SetUp] public void Setup() { MockMessageQueueListenerFactory = new Mock<MessageQueueListenerFactory>(); MockMessageQueueListenerFactory.Setup(x => x.CreateRabbitMQListener()) .Returns<IMessageQueueListener>(null); Subject.MessageQueueListenerFactory = MockMessageQueueListenerFactory.Object; } [Test] public void ShouldStartListener() { Subject.ListenerTaskCount = 1; Subject.StartListener(); MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Once); } [Test] public void ShouldStartMultipleListeners() { var listenerTaskCount = 3; Subject.ListenerTaskCount = listenerTaskCount; Subject.StartListener(); MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Exactly(listenerTaskCount)); } [Test] public void ShouldSetCancellationTokenOnDispose() { Subject.CancellationTokenSource = new CancellationTokenSource(); Subject.Dispose(); Assert.That(Subject.CancellationTokenSource.IsCancellationRequested, Is.True); } } }
using BeekmanLabs.UnitTesting; using IntegrationEngine.JobProcessor; using NUnit.Framework; using Moq; using System; using System.Threading; namespace IntegrationEngine.Tests.JobProcessor { public class MessageQueueListenerManagerTest : TestBase<MessageQueueListenerManager> { public Mock<MessageQueueListenerFactory> MockMessageQueueListenerFactory { get; set; } [SetUp] public void Setup() { MockMessageQueueListenerFactory = new Mock<MessageQueueListenerFactory>(); MockMessageQueueListenerFactory.Setup(x => x.CreateRabbitMQListener()) .Returns<IMessageQueueListener>(null); Subject.MessageQueueListenerFactory = MockMessageQueueListenerFactory.Object; } [Test] public void ShouldStartListener() { Subject.ListenerTaskCount = 1; Subject.StartListener(); MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Once); } [Test] public void ShouldStartMultipleListeners() { var listenerTaskCount = 10; Subject.ListenerTaskCount = listenerTaskCount; Subject.StartListener(); MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Exactly(listenerTaskCount)); } [Test] public void ShouldSetCancellationTokenOnDispose() { Subject.CancellationTokenSource = new CancellationTokenSource(); Subject.Dispose(); Assert.That(Subject.CancellationTokenSource.IsCancellationRequested, Is.True); } } }
Test launching 10 listeners in CI
Test launching 10 listeners in CI
C#
mit
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
fdf7189ab90abd138a1b2e629a0f807f60fc0ca2
Source/Lib/TraktApiSharp/Objects/Get/Shows/Seasons/TraktSeasonImages.cs
Source/Lib/TraktApiSharp/Objects/Get/Shows/Seasons/TraktSeasonImages.cs
namespace TraktApiSharp.Objects.Get.Shows.Seasons { using Basic; using Newtonsoft.Json; /// <summary> /// A collection of images for a Trakt season. /// </summary> public class TraktSeasonImages { /// <summary> /// A poster image set for various sizes. /// </summary> [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } /// <summary> /// A thumbnail image. /// </summary> [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
namespace TraktApiSharp.Objects.Get.Shows.Seasons { using Basic; using Newtonsoft.Json; /// <summary>A collection of images and image sets for a Trakt season.</summary> public class TraktSeasonImages { /// <summary>Gets or sets the screenshot image set.</summary> [JsonProperty(PropertyName = "poster")] public TraktImageSet Poster { get; set; } /// <summary>Gets or sets the thumb image.</summary> [JsonProperty(PropertyName = "thumb")] public TraktImage Thumb { get; set; } } }
Add get best id method for season images.
Add get best id method for season images.
C#
mit
henrikfroehling/TraktApiSharp
c3c881149049c58982e282269ecd6cbcc0314b33
resharper/resharper-yaml/test/src/TestEnvironment.cs
resharper/resharper-yaml/test/src/TestEnvironment.cs
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.TestFramework; using JetBrains.TestFramework; using JetBrains.TestFramework.Application.Zones; using NUnit.Framework; [assembly: RequiresSTA] namespace JetBrains.ReSharper.Plugins.Yaml.Tests { [ZoneDefinition] public interface IYamlTestZone : ITestsEnvZone, IRequire<PsiFeatureTestZone> { } [SetUpFixture] public class TestEnvironment : ExtensionTestEnvironmentAssembly<IYamlTestZone> { } }
using JetBrains.Application.BuildScript.Application.Zones; using JetBrains.ReSharper.TestFramework; using JetBrains.TestFramework; using JetBrains.TestFramework.Application.Zones; using NUnit.Framework; [assembly: RequiresSTA] // This attribute is marked obsolete but is still supported. Use is discouraged in preference to convention, but the // convention doesn't work for us. That convention is to walk up the tree from the executing assembly and look for a // relative path called "test/data". This doesn't work because our common "build" folder is one level above our // "test/data" folder, so it doesn't get found. We want to keep the common "build" folder, but allow multiple "modules" // with separate "test/data" folders. E.g. "resharper-unity" and "resharper-yaml" // TODO: This makes things work when building as part of the Unity project, but breaks standalone // Maybe it should be using product/subplatform markers? #pragma warning disable 618 [assembly: TestDataPathBase("resharper-yaml/test/data")] #pragma warning restore 618 namespace JetBrains.ReSharper.Plugins.Yaml.Tests { [ZoneDefinition] public interface IYamlTestZone : ITestsEnvZone, IRequire<PsiFeatureTestZone> { } [SetUpFixture] public class TestEnvironment : ExtensionTestEnvironmentAssembly<IYamlTestZone> { } }
Fix test data path when building in Unity plugin
Fix test data path when building in Unity plugin
C#
apache-2.0
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
7ec68beaa4825a2a9bcb88c8902d8a46bcba7065
SurveyMonkey/Containers/ResponseAnswer.cs
SurveyMonkey/Containers/ResponseAnswer.cs
using Newtonsoft.Json; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class ResponseAnswer { public long? ChoiceId { get; set; } public long? RowId { get; set; } public long? ColId { get; set; } public long? OtherId { get; set; } public string Text { get; set; } public bool? IsCorrect { get; set; } public int? Score { get; set; } public string SimpleText { get; set; } [JsonIgnore] internal object TagData { get; set; } public ChoiceMetadata ChoiceMetadata { get; set; } } }
using Newtonsoft.Json; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class ResponseAnswer { public long? ChoiceId { get; set; } public long? RowId { get; set; } public long? ColId { get; set; } public long? OtherId { get; set; } public string Text { get; set; } public bool? IsCorrect { get; set; } public int? Score { get; set; } public string DownloadUrl { get; set; } public string ContentType { get; set; } public string SimpleText { get; set; } [JsonIgnore] internal object TagData { get; set; } public ChoiceMetadata ChoiceMetadata { get; set; } } }
Add download_url and content_type for file upload questions
Add download_url and content_type for file upload questions
C#
mit
bcemmett/SurveyMonkeyApi-v3
7f8a1a7863c7ae5722637b397fae86e169f7aaa8
WP8App/Services/WordWrapService.cs
WP8App/Services/WordWrapService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WPAppStudio.Services.Interfaces; namespace WPAppStudio.Services { public class WordWrapService { private readonly ITextMeasurementService _tms; public WordWrapService(ITextMeasurementService textMeasurementService) { _tms = textMeasurementService; } public string GetWords(string text, int wordCount) { StringBuilder result = new StringBuilder(); for (int word = 0; word < wordCount; word++) { int space = text.IndexOf(' ', 1); //return text.Substring(0, space); if (space == -1) { result.Append(text); return result.ToString(); } result.Append(text.Substring(0, space)); text = text.Substring(space); } return result.ToString(); } public string GetLine(string text, int lineLength) { for (int wordCount = 10; wordCount > 0; wordCount--) { string line = GetWords(text, wordCount); int width = _tms.GetTextWidth(line); if (width <= lineLength) { return line; } } return GetWords(text, 1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WPAppStudio.Services.Interfaces; namespace WPAppStudio.Services { public class WordWrapService { private readonly ITextMeasurementService _tms; public WordWrapService(ITextMeasurementService textMeasurementService) { _tms = textMeasurementService; } public string GetWords(string text, int wordCount) { StringBuilder result = new StringBuilder(); for (int word = 0; word < wordCount; word++) { int space = text.IndexOf(' ', 1); //return text.Substring(0, space); if (space == -1) { result.Append(text); return result.ToString(); } result.Append(text.Substring(0, space)); text = text.Substring(space); } return result.ToString(); } public string GetLine(string text, int lineLength) { string line = GetWords(text, 3); int width = _tms.GetTextWidth(line); if (width <= lineLength) { return line; } return GetWords(text, 1); } } }
Revert "And we have the medium line working!"
Revert "And we have the medium line working!" This reverts commit 2c642200074b3a3d882a95530f053656346ac05d.
C#
mit
pcamp123/GadgtSpot-Windows-Phone-Application
9a90ebaffe41df590ca3fac9e0b5acdea35c5175
Collections/Paging/PagingHelpers.cs
Collections/Paging/PagingHelpers.cs
using System; using System.Linq; namespace Smartrak.Collections.Paging { public static class PagingHelpers { /// <summary> /// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries /// </summary> /// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam> /// <param name="entities">A queryable of entities</param> /// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param> /// <param name="pageSize">the size of the page you want, cannot be zero or negative</param> /// <returns>A queryable of the page of entities with counts appended.</returns> public static IQueryable<EntityWithCount<T>> GetPageWithTotal<T>(this IQueryable<T> entities, int page, int pageSize) where T : class { if (entities == null) { throw new ArgumentNullException("entities"); } if (page < 1) { throw new ArgumentException("Must be positive", "page"); } if (pageSize < 1) { throw new ArgumentException("Must be positive", "pageSize"); } return entities .Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() }) .Skip(page - 1 * pageSize) .Take(pageSize); } } }
using System; using System.Linq; namespace Smartrak.Collections.Paging { public static class PagingHelpers { /// <summary> /// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries /// </summary> /// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam> /// <param name="entities">A queryable of entities</param> /// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param> /// <param name="pageSize">the size of the page you want, cannot be zero or negative</param> /// <returns>A queryable of the page of entities with counts appended.</returns> public static IQueryable<EntityWithCount<T>> GetPageWithTotalzzz<T>(this IQueryable<T> entities, int page, int pageSize) where T : class { if (entities == null) { throw new ArgumentNullException("entities"); } if (page < 1) { throw new ArgumentException("Must be positive", "page"); } if (pageSize < 1) { throw new ArgumentException("Must be positive", "pageSize"); } return entities .Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() }) .Skip(page - 1 * pageSize) .Take(pageSize); } } }
Revert "Removing 'zzz' from method name"
Revert "Removing 'zzz' from method name" This reverts commit e32baff273074950f07a718edfac63933a00a420.
C#
mit
Smartrak/Smartrak.Library
cc92d3d6a91dfd5acbdd681b57737df083f6f12b
ProcessRelauncher/ProcessMonitor.cs
ProcessRelauncher/ProcessMonitor.cs
using System; using System.Diagnostics; using System.Threading; namespace ProcessRelauncher { public class ProcessMonitor : IDisposable { private Timer _timer; private readonly int _monitoringPollingIntervalMs; private readonly ProcessStartInfo _processStartInfo; private readonly string _processName; public ProcessMonitor(string processName, ProcessStartInfo launcher, int monitoringPollingIntervalMs) { _processStartInfo = launcher; _processName = processName.ToLower(); _monitoringPollingIntervalMs = monitoringPollingIntervalMs; } public void Monitor(object o) { Process[] processlist = Process.GetProcesses(); foreach(var p in processlist) { if (p.ProcessName.ToLower().Equals(_processName)) return; } Process.Start(_processStartInfo); GC.Collect(); } public void Start() { if (_timer != null) return; _timer = new Timer(this.Monitor, null, 0, _monitoringPollingIntervalMs); } public void Dispose() { _timer.Dispose(); } } }
using System; using System.Diagnostics; using System.Threading; namespace ProcessRelauncher { public class ProcessMonitor : IDisposable { private Timer _timer; private readonly int _monitoringPollingIntervalMs; private readonly ProcessStartInfo _processStartInfo; private readonly string _processName; public ProcessMonitor(string processName, ProcessStartInfo launcher, int monitoringPollingIntervalMs) { _processStartInfo = launcher; _processName = processName.ToLower(); _monitoringPollingIntervalMs = monitoringPollingIntervalMs; } public void Monitor(object o) { Process[] processlist = Process.GetProcesses(); foreach (var p in processlist) { if (p.ProcessName.ToLower().Equals(_processName)) return; } Process.Start(_processStartInfo); processlist = null; GC.Collect(); } public void Start() { if (_timer != null) return; _timer = new Timer(this.Monitor, null, 0, _monitoringPollingIntervalMs); } public void Dispose() { if (_timer == null) return; _timer.Dispose(); } } }
Enable the GC to clean up the process list immediately. Fixed potential null reference when disposing before starting.
Enable the GC to clean up the process list immediately. Fixed potential null reference when disposing before starting.
C#
bsd-3-clause
frederik256/ProcessRelauncher
807f0c5ce53fc5b0d7e4749b6cd513b04faef93c
hangman.cs
hangman.cs
using System; namespace Hangman { public class Hangman { public static void Main(string[] args) { Table table = new Table(2, 3); string output = table.Draw(); Console.WriteLine(output); } } }
using System; namespace Hangman { public class Hangman { public static void Main(string[] args) { // Table table = new Table(2, 3); // string output = table.Draw(); // Console.WriteLine(output); } } }
Comment out the code in Hangman that uses Table
Comment out the code in Hangman that uses Table To focus on the development of game logic
C#
unlicense
12joan/hangman
976c435749838971252d53ad550ff07587a6b7b8
BaiduHiCrawler/BaiduHiCrawler/Constants.cs
BaiduHiCrawler/BaiduHiCrawler/Constants.cs
namespace BaiduHiCrawler { using System; static class Constants { public const string CommentRetrivalUrlPattern = "http://hi.baidu.com/qcmt/data/cmtlist?qing_request_source=new_request&thread_id_enc={0}&start={1}&count={2}&orderby_type=0&favor=2&type=smblog"; public const string LocalArchiveFolder = @".\Archive\"; public const string LogsFolder = @".\Logs\"; public static readonly Uri LoginUri = new Uri("http://hi.baidu.com/go/login"); public static readonly Uri HomeUri = new Uri("http://hi.baidu.com/home"); public static readonly DateTime CommentBaseDateTime = new DateTime(1970, 1, 1, 0, 0, 0); public static readonly LogLevel LogLevel = LogLevel.Verbose; } }
namespace BaiduHiCrawler { using System; static class Constants { public const string CommentRetrivalUrlPattern = "http://hi.baidu.com/qcmt/data/cmtlist?qing_request_source=new_request&thread_id_enc={0}&start={1}&count={2}&orderby_type=0&favor=2&type=smblog"; public const string LocalArchiveFolder = @".\Archive\"; public const string LogsFolder = @".\Logs\"; public static readonly Uri LoginUri = new Uri("http://hi.baidu.com/go/login"); public static readonly Uri HomeUri = new Uri("http://hi.baidu.com/home"); public static readonly DateTime CommentBaseDateTime = new DateTime(1970, 1, 1, 0, 0, 0); public static readonly LogLevel LogLevel = LogLevel.Warning; } }
Set LogLevel in master branch to Warning
Set LogLevel in master branch to Warning
C#
mit
sqybi/baidu-hi-crawler
ca98325c82e2288a9215932c46c1fcb61ad35ca8
RegionsConfiguration.cs
RegionsConfiguration.cs
using System.Collections.Generic; using Rocket.API; using RocketRegions.Model; namespace RocketRegions { public class RegionsConfiguration : IRocketPluginConfiguration { public int UpdateFrameCount; public List<Region> Regions; public string UrlOpenMessage; public void LoadDefaults() { Regions = new List<Region>(); UpdateFrameCount = 1; UrlOpenMessage = "Visit webpage"; } } }
using System.Collections.Generic; using Rocket.API; using RocketRegions.Model; namespace RocketRegions { public class RegionsConfiguration : IRocketPluginConfiguration { public int UpdateFrameCount; public List<Region> Regions; public string UrlOpenMessage; public void LoadDefaults() { Regions = new List<Region>(); UpdateFrameCount = 10; UrlOpenMessage = "Visit webpage"; } } }
Set default <UpdateFrameCount> to 10
Set default <UpdateFrameCount> to 10
C#
agpl-3.0
Trojaner25/Rocket-Safezone,Trojaner25/Rocket-Regions
579bdb0ee5287f404ab12a1035f2a47cb73d3ee0
DesktopWidgets/Actions/PopupAction.cs
DesktopWidgets/Actions/PopupAction.cs
using System.ComponentModel; using System.Windows; namespace DesktopWidgets.Actions { internal class PopupAction : ActionBase { [DisplayName("Text")] public string Text { get; set; } = ""; [DisplayName("Title")] public string Title { get; set; } = ""; [DisplayName("Image")] public MessageBoxImage Image { get; set; } protected override void ExecuteAction() { base.ExecuteAction(); MessageBox.Show(Text, Title, MessageBoxButton.OK, Image); } } }
using System.ComponentModel; using System.IO; using System.Windows; using DesktopWidgets.Classes; namespace DesktopWidgets.Actions { internal class PopupAction : ActionBase { public FilePath FilePath { get; set; } = new FilePath(); [DisplayName("Text")] public string Text { get; set; } = ""; [DisplayName("Input Mode")] public InputMode InputMode { get; set; } = InputMode.Text; [DisplayName("Title")] public string Title { get; set; } = ""; [DisplayName("Image")] public MessageBoxImage Image { get; set; } protected override void ExecuteAction() { base.ExecuteAction(); var input = string.Empty; switch (InputMode) { case InputMode.Clipboard: input = Clipboard.GetText(); break; case InputMode.File: input = File.ReadAllText(FilePath.Path); break; case InputMode.Text: input = Text; break; } MessageBox.Show(input, Title, MessageBoxButton.OK, Image); } } }
Add "Input Mode", "File" options to "Popup" action
Add "Input Mode", "File" options to "Popup" action
C#
apache-2.0
danielchalmers/DesktopWidgets
2d92a99e35e0a6fd783b220181a0c104c7416184
src/addoncreator/AddonJson.cs
src/addoncreator/AddonJson.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json; namespace GarrysMod.AddonCreator { public class AddonJson { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("tags")] public List<string> Tags { get; set; } [JsonProperty("ignore")] public List<string> Ignores { get; set; } public void CheckForErrors() { if (string.IsNullOrEmpty(Title)) { throw new MissingFieldException("Title is empty or not specified."); } if (!string.IsNullOrEmpty(Description) && Description.Contains('\0')) { throw new InvalidDataException("Description contains NULL character."); } if (string.IsNullOrEmpty(Type)) { throw new MissingFieldException("Type is empty or not specified."); } } public void RemoveIgnoredFiles(ref Dictionary<string, AddonFileInfo> files) { foreach (var key in files.Keys.ToArray()) // ToArray makes a shadow copy of Keys to avoid "mid-loop-removal" conflicts { if (Ignores.Any(w => w.WildcardRegex().IsMatch(key))) files.Remove(key); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json; namespace GarrysMod.AddonCreator { public class AddonJson { [JsonProperty("title")] public string Title { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("tags")] public List<string> Tags { get; set; } [JsonProperty("ignore")] public List<string> Ignores { get; set; } [JsonProperty("version")] public int Version { get; set; } internal void CheckForErrors() { if (string.IsNullOrEmpty(Title)) { throw new MissingFieldException("Title is empty or not specified."); } if (!string.IsNullOrEmpty(Description) && Description.Contains('\0')) { throw new InvalidDataException("Description contains NULL character."); } if (string.IsNullOrEmpty(Type)) { throw new MissingFieldException("Type is empty or not specified."); } } public void RemoveIgnoredFiles(ref Dictionary<string, AddonFileInfo> files) { foreach (var key in files.Keys.ToArray()) // ToArray makes a shadow copy of Keys to avoid "mid-loop-removal" conflicts { if (Ignores.Any(w => w.WildcardRegex().IsMatch(key))) files.Remove(key); } } } }
Add version field and make CheckForErrors less accessible from outside.
Add version field and make CheckForErrors less accessible from outside.
C#
mit
icedream/gmadsharp
6f7a7b9c18f11ef9a7013133b897bbeac44920cd
InteractApp/EventListPage.xaml.cs
InteractApp/EventListPage.xaml.cs
using System; using System.Diagnostics; using Xamarin.Forms; using InteractApp; namespace InteractApp { public class EventListPageBase : ViewPage<EventListPageViewModel> { } public partial class EventListPage : EventListPageBase { public EventListPage () { InitializeComponent (); this.Title = "Events"; Padding = new Thickness (0, 0, 0, 0); ToolbarItems.Add (new ToolbarItem { Text = "My Info", Order = ToolbarItemOrder.Primary, Command = new Command (this.ShowMyInfoPage), }); ToolbarItems.Add (new ToolbarItem { Text = "My Events", Order = ToolbarItemOrder.Primary, }); //To hide iOS list seperator EventList.SeparatorVisibility = SeparatorVisibility.None; ViewModel.LoadEventsCommand.Execute (null); EventList.ItemTapped += async (sender, e) => { Event evt = (Event)e.Item; Debug.WriteLine ("Tapped: " + (evt.Name)); var page = new EventInfoPage (evt); ((ListView)sender).SelectedItem = null; await Navigation.PushAsync (page); }; } private void ShowMyInfoPage () { Navigation.PushAsync (new MyInfoPage ()); } } }
using System; using System.Diagnostics; using Xamarin.Forms; using InteractApp; namespace InteractApp { public class EventListPageBase : ViewPage<EventListPageViewModel> { } public partial class EventListPage : EventListPageBase { public EventListPage () { InitializeComponent (); this.Title = "Events"; Padding = new Thickness (0, 0, 0, 0); // ToolbarItems.Add (new ToolbarItem { // Text = "My Info", // Order = ToolbarItemOrder.Primary, // Command = new Command (this.ShowMyInfoPage), // }); // ToolbarItems.Add (new ToolbarItem { // Text = "My Events", // Order = ToolbarItemOrder.Primary, // }); //To hide iOS list seperator EventList.SeparatorVisibility = SeparatorVisibility.None; ViewModel.LoadEventsCommand.Execute (null); EventList.ItemTapped += async (sender, e) => { Event evt = (Event)e.Item; Debug.WriteLine ("Tapped: " + (evt.Name)); var page = new EventInfoPage (evt); ((ListView)sender).SelectedItem = null; await Navigation.PushAsync (page); }; } private void ShowMyInfoPage () { Navigation.PushAsync (new MyInfoPage ()); } } }
Remove unused Toolbar options until we actually make use of them
Remove unused Toolbar options until we actually make use of them
C#
mit
IrvingtonProgramming/InteractApp,IrvingtonProgramming/InteractApp,IrvingtonProgramming/InteractApp
d704507823b5c4a107fcab0fff70a1db28fbca41
PolarisServer/Models/PSOObject.cs
PolarisServer/Models/PSOObject.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PolarisServer.Packets; namespace PolarisServer.Models { public class PSOObject { public struct PSOObjectThing { public UInt32 data; } public EntityHeader Header { get; set; } public MysteryPositions Position { get; set; } public string Name { get; set; } public UInt32 ThingFlag { get; set; } public PSOObjectThing[] things { get; set; } public byte[] GenerateSpawnBlob() { PacketWriter writer = new PacketWriter(); writer.WriteStruct(Header); writer.WriteStruct(Position); writer.Seek(2, SeekOrigin.Current); // Padding I guess... writer.WriteFixedLengthASCII(Name, 0x34); writer.Write(ThingFlag); writer.Write(things.Length); foreach (PSOObjectThing thing in things) { writer.WriteStruct(thing); } return writer.ToArray(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PolarisServer.Packets; namespace PolarisServer.Models { public class PSOObject { public struct PSOObjectThing { public UInt32 data; } public EntityHeader Header { get; set; } public MysteryPositions Position { get; set; } public string Name { get; set; } public UInt32 ThingFlag { get; set; } public PSOObjectThing[] things { get; set; } public byte[] GenerateSpawnBlob() { PacketWriter writer = new PacketWriter(); writer.WriteStruct(Header); writer.Write(Position); writer.Seek(2, SeekOrigin.Current); // Padding I guess... writer.WriteFixedLengthASCII(Name, 0x34); writer.Write(ThingFlag); writer.Write(things.Length); foreach (PSOObjectThing thing in things) { writer.WriteStruct(thing); } return writer.ToArray(); } } }
Write Position using the Position Writer Function
Write Position using the Position Writer Function
C#
agpl-3.0
Dreadlow/PolarisServer,MrSwiss/PolarisServer,PolarisTeam/PolarisServer,cyberkitsune/PolarisServer,lockzag/PolarisServer
34dc61040278b937d8c6805dc94168ec49199ebb
RuneScapeCacheToolsTests/VorbisTests.cs
RuneScapeCacheToolsTests/VorbisTests.cs
using System; using System.IO; using System.Linq; using Villermen.RuneScapeCacheTools.Audio.Vorbis; using Xunit; using Xunit.Abstractions; namespace RuneScapeCacheToolsTests { public class VorbisTests : IDisposable { private ITestOutputHelper Output { get; } private VorbisReader Reader1 { get; } private VorbisReader Reader2 { get; } private VorbisWriter Writer { get; } public VorbisTests(ITestOutputHelper output) { Output = output; Reader1 = new VorbisReader(File.OpenRead("testdata/sample1.ogg")); Reader2 = new VorbisReader(File.OpenRead("testdata/sample2.ogg")); Writer = new VorbisWriter(File.OpenWrite("out.ogg")); } [Fact] public void TestReadComments() { Reader1.ReadPacket(); var commentPacket = Reader1.ReadPacket(); Output.WriteLine($"Type of packet: {commentPacket.GetType().FullName}"); Assert.IsType<VorbisCommentHeader>(commentPacket); var commentHeader = (VorbisCommentHeader)commentPacket; Output.WriteLine("Comments in header:"); foreach (var userComment in commentHeader.UserComments) { Output.WriteLine($" - {userComment.Item1}: {userComment.Item2}"); } Assert.True(commentHeader.UserComments.Contains(new Tuple<string, string>("genre", "Soundtrack"))); } public void Dispose() { Reader1?.Dispose(); Reader2?.Dispose(); Writer?.Dispose(); } } }
using System; using System.IO; using System.Linq; using Villermen.RuneScapeCacheTools.Audio.Vorbis; using Xunit; using Xunit.Abstractions; namespace RuneScapeCacheToolsTests { public class VorbisTests : IDisposable { private ITestOutputHelper Output { get; } private VorbisReader Reader1 { get; } private VorbisReader Reader2 { get; } private VorbisWriter Writer { get; } public VorbisTests(ITestOutputHelper output) { Output = output; Reader1 = new VorbisReader(File.OpenRead("testdata/sample1.ogg")); Reader2 = new VorbisReader(File.OpenRead("testdata/sample2.ogg")); Writer = new VorbisWriter(File.OpenWrite("out.ogg")); } [Fact] public void TestReadComments() { Reader1.ReadPacket(); var commentPacket = Reader1.ReadPacket(); Output.WriteLine($"Type of packet: {commentPacket.GetType().FullName}"); Assert.IsType<VorbisCommentHeader>(commentPacket); var commentHeader = (VorbisCommentHeader)commentPacket; Output.WriteLine("Comments in header:"); foreach (var userComment in commentHeader.UserComments) { Output.WriteLine($" - {userComment.Item1}: {userComment.Item2}"); } Assert.True(commentHeader.UserComments.Contains(new Tuple<string, string>("DATE", "2012"))); } public void Dispose() { Reader1?.Dispose(); Reader2?.Dispose(); Writer?.Dispose(); } } }
Change comment test to reflect changed samples
Change comment test to reflect changed samples
C#
mit
villermen/runescape-cache-tools,villermen/runescape-cache-tools
fca6ac5e48a9e85d69f64c87c4b673e2b67c29b3
DAQ/Agilent53131A.cs
DAQ/Agilent53131A.cs
using System; using System.Collections.Generic; using System.Text; using DAQ.Environment; namespace DAQ.HAL { public class Agilent53131A : FrequencyCounter { public Agilent53131A(String visaAddress) : base(visaAddress) {} public override double Frequency { get { if (!Environs.Debug) { Write(":FUNC 'FREQ 1'"); Write(":FREQ:ARM:STAR:SOUR IMM"); Write(":FREQ:ARM:STOP:SOUR TIM"); Write(":FREQ:ARM:STOP:TIM 1.0"); Write("READ:FREQ?"); string fr = Read(); return Double.Parse(fr); } else { return 170.730 + (new Random()).NextDouble(); } } } public override double Amplitude { get { throw new Exception("The method or operation is not implemented."); } } } }
using System; using System.Collections.Generic; using System.Text; using DAQ.Environment; namespace DAQ.HAL { public class Agilent53131A : FrequencyCounter { public Agilent53131A(String visaAddress) : base(visaAddress) {} public override double Frequency { get { if (!Environs.Debug) { Connect(); Write(":FUNC 'FREQ 1'"); Write(":FREQ:ARM:STAR:SOUR IMM"); Write(":FREQ:ARM:STOP:SOUR TIM"); Write(":FREQ:ARM:STOP:TIM 1.0"); Write("READ:FREQ?"); string fr = Read(); Disconnect(); return Double.Parse(fr); } else { return 170.730 + (new Random()).NextDouble(); } } } public override double Amplitude { get { throw new Exception("The method or operation is not implemented."); } } } }
Fix a little bug with the new counter. The rf frequency measurement is now tested and works.
Fix a little bug with the new counter. The rf frequency measurement is now tested and works.
C#
mit
jstammers/EDMSuite,jstammers/EDMSuite,Stok/EDMSuite,ColdMatter/EDMSuite,Stok/EDMSuite,ColdMatter/EDMSuite,jstammers/EDMSuite,jstammers/EDMSuite,ColdMatter/EDMSuite,jstammers/EDMSuite,ColdMatter/EDMSuite
9bfd6986b57cab02c5b3feeac8f1050d837a20e4
Vaskelista/Views/Household/Create.cshtml
Vaskelista/Views/Household/Create.cshtml
@model Vaskelista.Models.Household @{ ViewBag.Title = "Create"; } <h2>Velkommen til vaskelista</h2> <p>Her kan du velge hva vaskelisten din skal hete:</p> <div class="form-horizontal"> <div class="form-group"> <div class="col-md-12"><label>@Request.Url.ToString()</label></div> <div class="col-md-12"> <ul class="form-option-list"> @foreach (string randomUrl in ViewBag.RandomUrls) { <li> @using (Html.BeginForm("Create", "Household", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Token, new { Value = randomUrl }) <input type="submit" value="@randomUrl" class="btn btn-default" /> } </li> } </ul> </div> </div> </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@model Vaskelista.Models.Household @{ ViewBag.Title = "Create"; } <h2>Velkommen til vaskelista</h2> <p>Her kan du velge hva vaskelisten din skal hete:</p> <div class="form-horizontal"> <div class="form-group"> <div class="col-md-2"><label>@Request.Url.ToString()</label></div> <div class="col-md-4"> <ul class="form-option-list"> @foreach (string randomUrl in ViewBag.RandomUrls) { <li> @using (Html.BeginForm("Create", "Household", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.HiddenFor(model => model.Token, new { Value = randomUrl }) <input type="submit" value="@randomUrl" class="btn btn-default" /> } </li> } </ul> </div> </div> </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Decrease bootstrap column sizes to improve mobile experience
Decrease bootstrap column sizes to improve mobile experience
C#
mit
johanhelsing/vaskelista,johanhelsing/vaskelista
2808182c0b917218e68132dd0b72da6ee031d372
TAUtil/Gaf/Structures/GafFrameData.cs
TAUtil/Gaf/Structures/GafFrameData.cs
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(BinaryReader b, ref GafFrameData e) { e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte TransparencyIndex; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(BinaryReader b, ref GafFrameData e) { e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.TransparencyIndex = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
Rename previously unknown GAF field
Rename previously unknown GAF field
C#
mit
MHeasell/TAUtil,MHeasell/TAUtil
9fc9009dbe1a6bba52686e41413aae20c4804652
osu.Game/Screens/Edit/Timing/SampleSection.cs
osu.Game/Screens/Edit/Timing/SampleSection.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.Bindables; using osu.Framework.Graphics; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Screens.Edit.Timing { internal class SampleSection : Section<SampleControlPoint> { private LabelledTextBox bank; private SliderWithTextBoxInput<int> volume; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new Drawable[] { bank = new LabelledTextBox { Label = "Bank Name", }, volume = new SliderWithTextBoxInput<int>("Volume") { Current = new SampleControlPoint().SampleVolumeBindable, } }); } protected override void OnControlPointChanged(ValueChangedEvent<SampleControlPoint> point) { if (point.NewValue != null) { bank.Current = point.NewValue.SampleBankBindable; volume.Current = point.NewValue.SampleVolumeBindable; } } protected override SampleControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.SamplePointAt(SelectedGroup.Value.Time); return new SampleControlPoint { SampleBank = reference.SampleBank, SampleVolume = reference.SampleVolume, }; } } }
// 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.Bindables; using osu.Framework.Graphics; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.UserInterfaceV2; namespace osu.Game.Screens.Edit.Timing { internal class SampleSection : Section<SampleControlPoint> { private LabelledTextBox bank; private SliderWithTextBoxInput<int> volume; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new Drawable[] { bank = new LabelledTextBox { Label = "Bank Name", }, volume = new SliderWithTextBoxInput<int>("Volume") { Current = new SampleControlPoint().SampleVolumeBindable, } }); } protected override void OnControlPointChanged(ValueChangedEvent<SampleControlPoint> point) { if (point.NewValue != null) { bank.Current = point.NewValue.SampleBankBindable; bank.Current.BindValueChanged(_ => ChangeHandler?.SaveState()); volume.Current = point.NewValue.SampleVolumeBindable; volume.Current.BindValueChanged(_ => ChangeHandler?.SaveState()); } } protected override SampleControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.SamplePointAt(SelectedGroup.Value.Time); return new SampleControlPoint { SampleBank = reference.SampleBank, SampleVolume = reference.SampleVolume, }; } } }
Add change handling for sample section
Add change handling for sample section
C#
mit
UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,UselessToucan/osu,peppy/osu
53a491eff93565a852f0d4b4d6c636d19eceb890
src/SFA.DAS.EmployerAccounts/Extensions/EndpointConfigurationExtensions.cs
src/SFA.DAS.EmployerAccounts/Extensions/EndpointConfigurationExtensions.cs
using System; using NServiceBus; using SFA.DAS.AutoConfiguration; using SFA.DAS.EmployerFinance.Messages.Commands; using SFA.DAS.Notifications.Messages.Commands; using SFA.DAS.NServiceBus.Configuration.AzureServiceBus; using StructureMap; namespace SFA.DAS.EmployerAccounts.Extensions { public static class EndpointConfigurationExtensions { public static EndpointConfiguration UseAzureServiceBusTransport(this EndpointConfiguration config, Func<string> connectionStringBuilder, IContainer container) { var isDevelopment = container.GetInstance<IEnvironmentService>().IsCurrent(DasEnv.LOCAL); if (isDevelopment) { var transport = config.UseTransport<LearningTransport>(); transport.Transactions(TransportTransactionMode.ReceiveOnly); ConfigureRouting(transport.Routing()); } else { config.UseAzureServiceBusTransport(connectionStringBuilder(), ConfigureRouting); } return config; } private static void ConfigureRouting(RoutingSettings routing) { routing.RouteToEndpoint( typeof(ImportLevyDeclarationsCommand).Assembly, typeof(ImportLevyDeclarationsCommand).Namespace, "SFA.DAS.EmployerFinance.MessageHandlers" ); routing.RouteToEndpoint( typeof(SendEmailCommand).Assembly, typeof(SendEmailCommand).Namespace, "SFA.DAS.Notifications.MessageHandlers" ); } } }
using System; using NServiceBus; using SFA.DAS.AutoConfiguration; using SFA.DAS.EmployerFinance.Messages.Commands; using SFA.DAS.Notifications.Messages.Commands; using SFA.DAS.NServiceBus.Configuration.AzureServiceBus; using StructureMap; namespace SFA.DAS.EmployerAccounts.Extensions { public static class EndpointConfigurationExtensions { public static EndpointConfiguration UseAzureServiceBusTransport(this EndpointConfiguration config, Func<string> connectionStringBuilder, IContainer container) { var isDevelopment = container.GetInstance<IEnvironmentService>().IsCurrent(DasEnv.LOCAL); if (isDevelopment) { var transport = config.UseTransport<LearningTransport>(); transport.Transactions(TransportTransactionMode.ReceiveOnly); ConfigureRouting(transport.Routing()); } else { config.UseAzureServiceBusTransport(connectionStringBuilder(), ConfigureRouting); var conventions = config.Conventions(); conventions.DefiningCommandsAs(type => { return type.Namespace == typeof(SendEmailCommand).Namespace || type.Namespace == typeof(ImportLevyDeclarationsCommand).Namespace; }); } return config; } private static void ConfigureRouting(RoutingSettings routing) { routing.RouteToEndpoint( typeof(ImportLevyDeclarationsCommand).Assembly, typeof(ImportLevyDeclarationsCommand).Namespace, "SFA.DAS.EmployerFinance.MessageHandlers" ); routing.RouteToEndpoint( typeof(SendEmailCommand).Assembly, typeof(SendEmailCommand).Namespace, "SFA.DAS.Notifications.MessageHandlers" ); } } }
Tweak conventions for nservicebus messages to work in unobtrusive and normal mode
Tweak conventions for nservicebus messages to work in unobtrusive and normal mode
C#
mit
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
1d9198b81116df056e7f23e8baa730a32a47c116
src/Editor/Editor.Client/ServerManager.cs
src/Editor/Editor.Client/ServerManager.cs
using System; using System.Threading; using Flood.Editor.Server; namespace Flood.Editor { public class ServerManager { public EditorServer Server { get; private set; } private ManualResetEventSlim serverCreatedEvent; private void RunBuiltinServer() { serverCreatedEvent.Set(); Server.Serve(); } public void CreateBuiltinServer() { Console.WriteLine("Initializing the built-in editor server..."); serverCreatedEvent = new ManualResetEventSlim(); Server = new EditorServer(); System.Threading.Tasks.Task.Run((Action)RunBuiltinServer); serverCreatedEvent.Wait(); } } }
using System; using System.Threading; using Flood.Editor.Server; namespace Flood.Editor { public class ServerManager { public EditorServer Server { get; private set; } private ManualResetEventSlim serverCreatedEvent; private void RunBuiltinServer() { serverCreatedEvent.Set(); Server.Serve(); } public void CreateBuiltinServer() { Log.Info("Initializing the built-in editor server..."); serverCreatedEvent = new ManualResetEventSlim(); Server = new EditorServer(); System.Threading.Tasks.Task.Run((Action)RunBuiltinServer); serverCreatedEvent.Wait(); } } }
Use the logger for writing to the console.
Use the logger for writing to the console.
C#
bsd-2-clause
FloodProject/flood,FloodProject/flood,FloodProject/flood
702a8b91e99b35a03ea14b9032a348f00a19921d
src/WPFConverters/BitmapImageConverter.cs
src/WPFConverters/BitmapImageConverter.cs
using System; using System.Globalization; using System.Windows; using System.Windows.Media.Imaging; namespace WPFConverters { public class BitmapImageConverter : BaseConverter { protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string) return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute)); if (value is Uri) return new BitmapImage((Uri)value); return DependencyProperty.UnsetValue; } } }
using System; using System.Globalization; using System.Windows; using System.Windows.Media.Imaging; namespace WPFConverters { public class BitmapImageConverter : BaseConverter { protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string) return LoadImage(new Uri((string)value, UriKind.RelativeOrAbsolute)); if (value is Uri) return LoadImage((Uri)value); return DependencyProperty.UnsetValue; } private BitmapImage LoadImage(Uri uri) { var image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.UriSource = uri; image.EndInit(); return image; } } }
Make bitmap loading cache the image
Make bitmap loading cache the image
C#
mit
distantcam/WPFConverters
2b58b1e89220144f669f306fce375f73a596698d
src/Tests/GoogleAsyncGeocoderTest.cs
src/Tests/GoogleAsyncGeocoderTest.cs
using System.Linq; using Geocoding.Google; using Xunit; using Xunit.Extensions; namespace Geocoding.Tests { public class GoogleAsyncGeocoderTest : AsyncGeocoderTest { GoogleGeocoder geoCoder; protected override IAsyncGeocoder CreateAsyncGeocoder() { geoCoder = new GoogleGeocoder(); return geoCoder; } [Theory] [InlineData("United States", GoogleAddressType.Country)] [InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)] [InlineData("New York, New York", GoogleAddressType.Locality)] [InlineData("90210, US", GoogleAddressType.PostalCode)] [InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)] public void CanParseAddressTypes(string address, GoogleAddressType type) { geoCoder.GeocodeAsync(address).ContinueWith(task => { GoogleAddress[] addresses = task.Result.ToArray(); Assert.Equal(type, addresses[0].Type); }); } } }
using System.Configuration; using System.Linq; using Geocoding.Google; using Xunit; using Xunit.Extensions; namespace Geocoding.Tests { public class GoogleAsyncGeocoderTest : AsyncGeocoderTest { GoogleGeocoder geoCoder; protected override IAsyncGeocoder CreateAsyncGeocoder() { geoCoder = new GoogleGeocoder { ApiKey = ConfigurationManager.AppSettings["googleApiKey"] }; return geoCoder; } [Theory] [InlineData("United States", GoogleAddressType.Country)] [InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)] [InlineData("New York, New York", GoogleAddressType.Locality)] [InlineData("90210, US", GoogleAddressType.PostalCode)] [InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)] public void CanParseAddressTypes(string address, GoogleAddressType type) { geoCoder.GeocodeAsync(address).ContinueWith(task => { GoogleAddress[] addresses = task.Result.ToArray(); Assert.Equal(type, addresses[0].Type); }); } } }
Use google API key in async test.
Use google API key in async test.
C#
mit
Troncho/Geocoding.net,harsimranb/Geocoding.net,chadly/Geocoding.net
db7602b5ea3cb9915fc48acfa3b62ed1eb5ff94b
src/StackExchange.Redis.Extensions.Core/Configuration/RedisHostCollection.cs
src/StackExchange.Redis.Extensions.Core/Configuration/RedisHostCollection.cs
using System.Configuration; namespace StackExchange.Redis.Extensions.Core.Configuration { /// <summary> /// Configuration Element Collection for <see cref="RedisHost"/> /// </summary> public class RedisHostCollection : ConfigurationElementCollection { /// <summary> /// Gets or sets the <see cref="RedisHost"/> at the specified index. /// </summary> /// <value> /// The <see cref="RedisHost"/>. /// </value> /// <param name="index">The index.</param> /// <returns></returns> public RedisHost this[int index] { get { return BaseGet(index) as RedisHost; } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } /// <summary> /// Creates the new element. /// </summary> /// <returns></returns> protected override ConfigurationElement CreateNewElement() { return new RedisHost(); } /// <summary> /// Gets the element key. /// </summary> /// <param name="element">The element.</param> /// <returns></returns> protected override object GetElementKey(ConfigurationElement element) { return ((RedisHost)element).Host; } } }
using System.Configuration; namespace StackExchange.Redis.Extensions.Core.Configuration { /// <summary> /// Configuration Element Collection for <see cref="RedisHost"/> /// </summary> public class RedisHostCollection : ConfigurationElementCollection { /// <summary> /// Gets or sets the <see cref="RedisHost"/> at the specified index. /// </summary> /// <value> /// The <see cref="RedisHost"/>. /// </value> /// <param name="index">The index.</param> /// <returns></returns> public RedisHost this[int index] { get { return BaseGet(index) as RedisHost; } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } /// <summary> /// Creates the new element. /// </summary> /// <returns></returns> protected override ConfigurationElement CreateNewElement() { return new RedisHost(); } /// <summary> /// Gets the element key. /// </summary> /// <param name="element">The element.</param> /// <returns></returns> protected override object GetElementKey(ConfigurationElement element) { return string.Format("{0}:{1}", ((RedisHost)element).Host, ((RedisHost)element).CachePort); } } }
Allow for multiple instances of redis running on the same server but different ports.
Allow for multiple instances of redis running on the same server but different ports.
C#
mit
LeCantaloop/StackExchange.Redis.Extensions,imperugo/StackExchange.Redis.Extensions,imperugo/StackExchange.Redis.Extensions
0b78a326d6a739d7045e3890b74f8d52c5ab9279
LINQToTTree/LINQToTTreeLib.Tests/Expressions/SubExpressionReplacementTest.cs
LINQToTTree/LINQToTTreeLib.Tests/Expressions/SubExpressionReplacementTest.cs
using System; using System.Diagnostics; using System.Linq.Expressions; using LINQToTTreeLib.Expressions; using Microsoft.Pex.Framework; using Microsoft.Pex.Framework.Validation; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LINQToTTreeLib.Tests.ResultOperators { [TestClass] [PexClass(typeof(SubExpressionReplacement))] public partial class SubExpressionReplacementTest { [TestInitialize] public void TestInit() { TestUtils.ResetLINQLibrary(); } [TestCleanup] public void TestDone() { MEFUtilities.MyClassDone(); } [PexMethod, PexAllowedException(typeof(ArgumentNullException))] public Expression TestReplacement(Expression source, Expression pattern, Expression replacement) { return source.ReplaceSubExpression(pattern, replacement); } [TestMethod] public void TestSimpleReplacement() { var arr = Expression.Parameter(typeof(int[]), "myarr"); var param = Expression.Parameter(typeof(int), "dude"); var expr = Expression.ArrayIndex(arr, param); var rep = Expression.Parameter(typeof(int), "fork"); var result = expr.ReplaceSubExpression(param, rep); Debg.WriteLine("Expression: " + result.ToString()); Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable"); } } }
using LINQToTTreeLib.Expressions; using Microsoft.Pex.Framework; using Microsoft.Pex.Framework.Validation; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Diagnostics; using System.Linq.Expressions; namespace LINQToTTreeLib.Tests.ResultOperators { [TestClass] [PexClass(typeof(SubExpressionReplacement))] public partial class SubExpressionReplacementTest { [TestInitialize] public void TestInit() { TestUtils.ResetLINQLibrary(); } [TestCleanup] public void TestDone() { MEFUtilities.MyClassDone(); } [PexMethod, PexAllowedException(typeof(ArgumentNullException))] public Expression TestReplacement(Expression source, Expression pattern, Expression replacement) { return source.ReplaceSubExpression(pattern, replacement); } [TestMethod] public void TestSimpleReplacement() { var arr = Expression.Parameter(typeof(int[]), "myarr"); var param = Expression.Parameter(typeof(int), "dude"); var expr = Expression.ArrayIndex(arr, param); var rep = Expression.Parameter(typeof(int), "fork"); var result = expr.ReplaceSubExpression(param, rep); Debug.WriteLine("Expression: " + result.ToString()); Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable"); } } }
Fix up badly spelled test
Fix up badly spelled test
C#
lgpl-2.1
gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT
a90f9074540d20f7e937211f621a9d59022d5774
CakeMail.RestClient/Properties/AssemblyInfo.cs
CakeMail.RestClient/Properties/AssemblyInfo.cs
using System.Reflection; // 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("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-beta04")]
using System.Reflection; // 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("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-beta05")]
Increase nuget package version to 1.0.0-beta05
Increase nuget package version to 1.0.0-beta05
C#
mit
Jericho/CakeMail.RestClient
faf6737218f051bfa35f470e32ef0dc0c407473d
MediaCentreServer/Controllers/RunController.cs
MediaCentreServer/Controllers/RunController.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace MediaCentreServer.Controllers { // Controller for running an application. public class RunController : ApiController { // POST /api/run?path=... public void Post(string path) { var startInfo = new ProcessStartInfo(path); startInfo.UseShellExecute = false; Process.Start(startInfo); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace MediaCentreServer.Controllers { // Controller for running an application. public class RunController : ApiController { // POST /api/run?path=... public HttpResponseMessage Post(string path) { var startInfo = new ProcessStartInfo(path); try { Process.Start(startInfo); return Request.CreateResponse(HttpStatusCode.NoContent); } catch (Exception) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Failed to launch process"); } } } }
Use shell execute for run action.
Use shell execute for run action. Enables launching URLs as well as apps. Probably a major security issue, but fuck it, right? Also improved error handling.
C#
mit
simontaylor81/HomeAutomation,simontaylor81/HomeAutomation,simontaylor81/HomeAutomation,simontaylor81/HomeAutomation,simontaylor81/HomeAutomation
b087c95581e960f80fa26af370aceb15dadf251e
osu.Game.Rulesets.Catch/UI/CatcherTrail.cs
osu.Game.Rulesets.Catch/UI/CatcherTrail.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osuTK; namespace osu.Game.Rulesets.Catch.UI { /// <summary> /// A trail of the catcher. /// It also represents a hyper dash afterimage. /// </summary> // TODO: Trails shouldn't be animated when the skin has an animated catcher. // The animation should be frozen at the animation frame at the time of the trail generation. public class CatcherTrail : PoolableDrawable { public CatcherAnimationState AnimationState { set => body.AnimationState.Value = value; } private readonly SkinnableCatcher body; public CatcherTrail() { Size = new Vector2(CatcherArea.CATCHER_SIZE); Origin = Anchor.TopCentre; Blending = BlendingParameters.Additive; InternalChild = body = new SkinnableCatcher(); } protected override void FreeAfterUse() { ClearTransforms(); base.FreeAfterUse(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Pooling; using osu.Framework.Timing; using osuTK; namespace osu.Game.Rulesets.Catch.UI { /// <summary> /// A trail of the catcher. /// It also represents a hyper dash afterimage. /// </summary> public class CatcherTrail : PoolableDrawable { public CatcherAnimationState AnimationState { set => body.AnimationState.Value = value; } private readonly SkinnableCatcher body; public CatcherTrail() { Size = new Vector2(CatcherArea.CATCHER_SIZE); Origin = Anchor.TopCentre; Blending = BlendingParameters.Additive; InternalChild = body = new SkinnableCatcher { // Using a frozen clock because trails should not be animated when the skin has an animated catcher. // TODO: The animation should be frozen at the animation frame at the time of the trail generation. Clock = new FramedClock(new ManualClock()), }; } protected override void FreeAfterUse() { ClearTransforms(); base.FreeAfterUse(); } } }
Use a frozen clock for catcher trails
Use a frozen clock for catcher trails
C#
mit
ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu
f9bfaf0ea091a1011310a80232a3ede90e3d9dda
EndlessClient/UIControls/StatusBarLabel.cs
EndlessClient/UIControls/StatusBarLabel.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.HUD; using EndlessClient.Rendering; using EOLib; using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.UIControls { public class StatusBarLabel : XNALabel { private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; private readonly IStatusLabelTextProvider _statusLabelTextProvider; public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider, IStatusLabelTextProvider statusLabelTextProvider) : base(Constants.FontSize07) { _statusLabelTextProvider = statusLabelTextProvider; DrawArea = new Rectangle(97, clientWindowSizeProvider.Height - 24, 1, 1); } protected override void OnUpdateControl(GameTime gameTime) { if (Text != _statusLabelTextProvider.StatusText) { Text = _statusLabelTextProvider.StatusText; Visible = true; } if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) Visible = false; base.OnUpdateControl(gameTime); } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.HUD; using EndlessClient.Rendering; using EOLib; using Microsoft.Xna.Framework; using XNAControls; namespace EndlessClient.UIControls { public class StatusBarLabel : XNALabel { private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000; private readonly IStatusLabelTextProvider _statusLabelTextProvider; public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider, IStatusLabelTextProvider statusLabelTextProvider) : base(Constants.FontSize07) { _statusLabelTextProvider = statusLabelTextProvider; DrawArea = new Rectangle(97, clientWindowSizeProvider.Height - 24, 1, 1); } protected override bool ShouldUpdate() { if (Text != _statusLabelTextProvider.StatusText) { Text = _statusLabelTextProvider.StatusText; Visible = true; } if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS) Visible = false; return base.ShouldUpdate(); } } }
Fix status label updating (update method not called if control is not visible)
Fix status label updating (update method not called if control is not visible)
C#
mit
ethanmoffat/EndlessClient
258898a078ba03279c2326639666b7acf63b0825
DaNES.Emulation/Ppu.cs
DaNES.Emulation/Ppu.cs
using System.Drawing; namespace DanTup.DaNES.Emulation { class Ppu { public Memory Ram { get; } public Bitmap Screen { get; } public Ppu(Memory ram, Bitmap screen) { Ram = ram; Screen = screen; for (var x = 0; x < 256; x++) { for (var y = 0; y < 240; y++) { Screen.SetPixel(x, y, Color.FromArgb(x, y, 128)); } } } public void Step() { } } }
using System.Drawing; namespace DanTup.DaNES.Emulation { class Ppu { public Memory Ram { get; } public Bitmap Screen { get; } // PPU Control bool NmiEnable; bool PpuMasterSlave; bool SpriteHeight; bool BackgroundTileSelect; bool SpriteTileSelect; bool IncrementMode; bool NameTableSelect1; bool NameTableSelect0; // PPU Mask bool TintBlue; bool TintGreen; bool TintRed; bool ShowSprites; bool ShowBackground; bool ShowLeftSprites; bool ShowLeftBackground; bool Greyscale; // PPU Status bool VBlank; bool Sprite0Hit; bool SpriteOverflow; byte OamAddress { get; } byte OamData { get; } byte PpuScroll { get; } byte PpuAddr { get; } byte PpuData { get; } byte OamDma { get; } public Ppu(Memory ram, Bitmap screen) { Ram = ram; Screen = screen; for (var x = 0; x < 256; x++) { for (var y = 0; y < 240; y++) { Screen.SetPixel(x, y, Color.FromArgb(x, y, 128)); } } } public void Step() { } } }
Add fields for PPU registers.
Add fields for PPU registers.
C#
mit
DanTup/DaNES
4795170c6044bc7092b4c78b687f5a5bdc880088
osu.Game/IO/Serialization/IJsonSerializable.cs
osu.Game/IO/Serialization/IJsonSerializable.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 Newtonsoft.Json; namespace osu.Game.IO.Serialization { public interface IJsonSerializable { } public static class JsonSerializableExtensions { public static string Serialize(this IJsonSerializable obj) => JsonConvert.SerializeObject(obj, CreateGlobalSettings()); public static T Deserialize<T>(this string objString) => JsonConvert.DeserializeObject<T>(objString, CreateGlobalSettings()); public static void DeserializeInto<T>(this string objString, T target) => JsonConvert.PopulateObject(objString, target, CreateGlobalSettings()); /// <summary> /// Creates the default <see cref="JsonSerializerSettings"/> that should be used for all <see cref="IJsonSerializable"/>s. /// </summary> /// <returns></returns> public static JsonSerializerSettings CreateGlobalSettings() => new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented, ObjectCreationHandling = ObjectCreationHandling.Replace, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, ContractResolver = new KeyContractResolver() }; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using Newtonsoft.Json; using osu.Framework.IO.Serialization; namespace osu.Game.IO.Serialization { public interface IJsonSerializable { } public static class JsonSerializableExtensions { public static string Serialize(this IJsonSerializable obj) => JsonConvert.SerializeObject(obj, CreateGlobalSettings()); public static T Deserialize<T>(this string objString) => JsonConvert.DeserializeObject<T>(objString, CreateGlobalSettings()); public static void DeserializeInto<T>(this string objString, T target) => JsonConvert.PopulateObject(objString, target, CreateGlobalSettings()); /// <summary> /// Creates the default <see cref="JsonSerializerSettings"/> that should be used for all <see cref="IJsonSerializable"/>s. /// </summary> /// <returns></returns> public static JsonSerializerSettings CreateGlobalSettings() => new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented, ObjectCreationHandling = ObjectCreationHandling.Replace, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Converters = new List<JsonConverter> { new Vector2Converter() }, ContractResolver = new KeyContractResolver() }; } }
Add back the default json converter locally to ensure it's actually used
Add back the default json converter locally to ensure it's actually used
C#
mit
peppy/osu,smoogipooo/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu
041eda7e74a012bf5fa21e9859840ba110738d4b
Source/Server/NetBots.WebServer.Host/Models/Secrets.cs
Source/Server/NetBots.WebServer.Host/Models/Secrets.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NetBotsHostProject.Models { public static class Secrets { private static readonly Dictionary<string,string> _secrets = new Dictionary<string, string>() { {"gitHubClientIdDev", "placeholder"}, {"gitHubClientSecretDev", "placeholder"} }; public static string GetSecret(string key) { if (_secrets.ContainsKey(key)) { return _secrets[key]; } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NetBotsHostProject.Models { public static class Secrets { private static readonly Dictionary<string,string> _secrets = new Dictionary<string, string>() { {"gitHubClientIdDev", "placeHolder"}, {"gitHubClientSecretDev", "placeHolder"} }; public static string GetSecret(string key) { if (_secrets.ContainsKey(key)) { return _secrets[key]; } return null; } } }
Set Secret.cs so it will not be modified by default. This means we can put sensitive information in it, and it won't go into source control
Set Secret.cs so it will not be modified by default. This means we can put sensitive information in it, and it won't go into source control
C#
mit
AiBattleground/BotWars,AiBattleground/BotWars
b4a6a6fbe06f77f8a91e7500598da05fe181c8e1
source/Assets/Scripts/Loader.cs
source/Assets/Scripts/Loader.cs
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("1.1.0.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
using UnityEngine; using System.Reflection; [assembly: AssemblyVersion("1.1.1.*")] public class Loader : MonoBehaviour { /// <summary> /// DebugUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _debugUI; /// <summary> /// ModalDialog prefab to instantiate. /// </summary> [SerializeField] private GameObject _modalDialog; /// <summary> /// MainMenu prefab to instantiate. /// </summary> [SerializeField] private GameObject _mainMenu; /// <summary> /// InGameUI prefab to instantiate. /// </summary> [SerializeField] private GameObject _inGameUI; /// <summary> /// SoundManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _soundManager; /// <summary> /// GameManager prefab to instantiate. /// </summary> [SerializeField] private GameObject _gameManager; protected void Awake() { // Check if the instances have already been assigned to static variables or they are still null. if (DebugUI.Instance == null) { Instantiate(_debugUI); } if (ModalDialog.Instance == null) { Instantiate(_modalDialog); } if (MainMenu.Instance == null) { Instantiate(_mainMenu); } if (InGameUI.Instance == null) { Instantiate(_inGameUI); } if (SoundManager.Instance == null) { Instantiate(_soundManager); } if (GameManager.Instance == null) { Instantiate(_gameManager); } } }
Change version up to 1.1.1
Change version up to 1.1.1
C#
unknown
matiasbeckerle/breakout,matiasbeckerle/arkanoid,matiasbeckerle/perspektiva
55d102fd2ed65b32205de6423f39f2f81ee1e0cc
src/Grobid/PdfBlockExtractor.cs
src/Grobid/PdfBlockExtractor.cs
using System; using System.Collections.Generic; using System.Linq; using Grobid.PdfToXml; namespace Grobid.NET { public class PdfBlockExtractor<T> { private readonly BlockStateFactory factory; public PdfBlockExtractor() { this.factory = new BlockStateFactory(); } public IEnumerable<T> Extract(IEnumerable<Block> blocks, Func<BlockState, T> transform) { foreach (var block in blocks) { foreach (var textBlock in block.TextBlocks) { var tokenBlocks = textBlock.TokenBlocks.SelectMany(x => x.Tokenize()); foreach (var tokenBlock in tokenBlocks) { var blockState = this.factory.Create(block, textBlock, tokenBlock); yield return transform(blockState); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using Grobid.PdfToXml; namespace Grobid.NET { public class PdfBlockExtractor<T> { private readonly BlockStateFactory factory; public PdfBlockExtractor() { this.factory = new BlockStateFactory(); } public IEnumerable<T> Extract(IEnumerable<Block> blocks, Func<BlockState, T> transform) { return from block in blocks from textBlock in block.TextBlocks let tokenBlocks = textBlock.TokenBlocks.SelectMany(x => x.Tokenize()) from tokenBlock in tokenBlocks select this.factory.Create(block, textBlock, tokenBlock) into blockState select transform(blockState); } } }
Simplify foreach'es to a LINQ expression
Simplify foreach'es to a LINQ expression
C#
apache-2.0
boumenot/Grobid.NET
b3e7ca47cad2971433616ccdea6883c8b5b825e6
CertiPay.Common/Notifications/ISMSService.cs
CertiPay.Common/Notifications/ISMSService.cs
using CertiPay.Common.Logging; using System; using System.Threading.Tasks; using Twilio; namespace CertiPay.Common.Notifications { /// <summary> /// Send an SMS message to the given recipient. /// </summary> /// <remarks> /// Implementation may be sent into background processing. /// </remarks> public interface ISMSService : INotificationSender<SMSNotification> { // Task SendAsync(T notification); } public class SmsService : ISMSService { private static readonly ILog Log = LogManager.GetLogger<ISMSService>(); private readonly String _twilioAccountSId; private readonly String _twilioAuthToken; private readonly String _twilioSourceNumber; public SmsService(String twilioAccountSid, String twilioAuthToken, String twilioSourceNumber) { this._twilioAccountSId = twilioAccountSid; this._twilioAuthToken = twilioAuthToken; this._twilioSourceNumber = twilioSourceNumber; } public Task SendAsync(SMSNotification notification) { using (Log.Timer("SMSNotification.SendAsync")) { Log.Info("Sending SMSNotification {@Notification}", notification); // TODO Add error handling var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken); foreach (var recipient in notification.Recipients) { client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content); } return Task.FromResult(0); } } } }
using CertiPay.Common.Logging; using System; using System.Threading.Tasks; using Twilio; namespace CertiPay.Common.Notifications { /// <summary> /// Send an SMS message to the given recipient. /// </summary> /// <remarks> /// Implementation may be sent into background processing. /// </remarks> public interface ISMSService : INotificationSender<SMSNotification> { // Task SendAsync(T notification); } public class SmsService : ISMSService { private static readonly ILog Log = LogManager.GetLogger<ISMSService>(); private readonly String _twilioAccountSId; private readonly String _twilioAuthToken; private readonly String _twilioSourceNumber; public SmsService(TwilioConfig config) { this._twilioAccountSId = config.AccountSid; this._twilioAuthToken = config.AuthToken; this._twilioSourceNumber = config.SourceNumber; } public Task SendAsync(SMSNotification notification) { using (Log.Timer("SMSNotification.SendAsync")) { Log.Info("Sending SMSNotification {@Notification}", notification); // TODO Add error handling var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken); foreach (var recipient in notification.Recipients) { client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content); } return Task.FromResult(0); } } public class TwilioConfig { public String AccountSid { get; set; } public String AuthToken { get; set; } public String SourceNumber { get; set; } } } }
Add timer for email sending
Add timer for email sending
C#
mit
mattgwagner/CertiPay.Common
1033c42d0156db660f53b3ca113741ca3cc23b37
DigiTransit10/Helpers/DeviceTypeHelper.cs
DigiTransit10/Helpers/DeviceTypeHelper.cs
using Windows.System.Profile; using Windows.UI.ViewManagement; namespace DigiTransit10.Helpers { public static class DeviceTypeHelper { public static DeviceFormFactorType GetDeviceFormFactorType() { switch (AnalyticsInfo.VersionInfo.DeviceFamily) { case "Windows.Mobile": return DeviceFormFactorType.Phone; case "Windows.Desktop": return UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse ? DeviceFormFactorType.Desktop : DeviceFormFactorType.Tablet; case "Windows.Universal": return DeviceFormFactorType.IoT; case "Windows.Team": return DeviceFormFactorType.SurfaceHub; default: return DeviceFormFactorType.Other; } } } public enum DeviceFormFactorType { Phone, Desktop, Tablet, IoT, SurfaceHub, Other } }
using Windows.System.Profile; using Windows.UI.ViewManagement; namespace DigiTransit10.Helpers { public static class DeviceTypeHelper { public static DeviceFormFactorType GetDeviceFormFactorType() { switch (AnalyticsInfo.VersionInfo.DeviceFamily) { case "Windows.Mobile": return DeviceFormFactorType.Phone; case "Windows.Desktop": return DeviceFormFactorType.Desktop; case "Windows.Universal": return DeviceFormFactorType.IoT; case "Windows.Team": return DeviceFormFactorType.SurfaceHub; default: return DeviceFormFactorType.Other; } } } public enum DeviceFormFactorType { Phone, Desktop, Tablet, IoT, SurfaceHub, Other } }
Make Tablet and Desktop device types report as Desktop
Make Tablet and Desktop device types report as Desktop
C#
mit
pingzing/digi-transit-10
1b87767472bea0910e6dd34f5749a98e6f48c90e
test/MusicStore.Test/GenreMenuComponentTest.cs
test/MusicStore.Test/GenreMenuComponentTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc.ViewComponents; using Microsoft.Data.Entity; using Microsoft.Extensions.DependencyInjection; using MusicStore.Models; using Xunit; namespace MusicStore.Components { public class GenreMenuComponentTest { private readonly IServiceProvider _serviceProvider; public GenreMenuComponentTest() { var services = new ServiceCollection(); services.AddEntityFramework() .AddInMemoryDatabase() .AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase()); _serviceProvider = services.BuildServiceProvider(); } [Fact] public async Task GenreMenuComponent_Returns_NineGenres() { // Arrange var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>(); var genreMenuComponent = new GenreMenuComponent(dbContext); PopulateData(dbContext); // Act var result = await genreMenuComponent.InvokeAsync(); // Assert Assert.NotNull(result); var viewResult = Assert.IsType<ViewViewComponentResult>(result); Assert.Null(viewResult.ViewName); var genreResult = Assert.IsType<List<Genre>>(viewResult.ViewData.Model); Assert.Equal(9, genreResult.Count); } private static void PopulateData(MusicStoreContext context) { var genres = Enumerable.Range(1, 10).Select(n => new Genre()); context.AddRange(genres); context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc.ViewComponents; using Microsoft.Data.Entity; using Microsoft.Extensions.DependencyInjection; using MusicStore.Models; using Xunit; namespace MusicStore.Components { public class GenreMenuComponentTest { private readonly IServiceProvider _serviceProvider; public GenreMenuComponentTest() { var services = new ServiceCollection(); services.AddEntityFramework() .AddInMemoryDatabase() .AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase()); _serviceProvider = services.BuildServiceProvider(); } [Fact] public async Task GenreMenuComponent_Returns_NineGenres() { // Arrange var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>(); var genreMenuComponent = new GenreMenuComponent(dbContext); PopulateData(dbContext); // Act var result = await genreMenuComponent.InvokeAsync(); // Assert Assert.NotNull(result); var viewResult = Assert.IsType<ViewViewComponentResult>(result); Assert.Null(viewResult.ViewName); var genreResult = Assert.IsType<List<Genre>>(viewResult.ViewData.Model); Assert.Equal(9, genreResult.Count); } private static void PopulateData(MusicStoreContext context) { var genres = Enumerable.Range(1, 10).Select(n => new Genre { GenreId = n }); context.AddRange(genres); context.SaveChanges(); } } }
Fix bug in test where key value was not being set.
Fix bug in test where key value was not being set.
C#
apache-2.0
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
7f6e6f5a08d2d9d8287c5594b1f9e9956b6f1d24
Vro.FindExportImport/Stores/SearchService.cs
Vro.FindExportImport/Stores/SearchService.cs
using System.Linq; using EPiServer.Core; using EPiServer.Find; using EPiServer.Find.Framework; using EPiServer.ServiceLocation; using Vro.FindExportImport.Models; namespace Vro.FindExportImport.Stores { public interface ISearchService { ContentReference FindMatchingContent(BestBetEntity bestBetEntity); } [ServiceConfiguration(typeof(ISearchService))] public class SearchService : ISearchService { public ContentReference FindMatchingContent(BestBetEntity bestBetEntity) { var searchQuery = SearchClient.Instance .Search<IContent>() .Filter(x => x.Name.Match(bestBetEntity.TargetName)); if (bestBetEntity.TargetType.Equals(Helpers.PageBestBetSelector)) { searchQuery = searchQuery.Filter(x => !x.ContentLink.ProviderName.Exists()); } else if (bestBetEntity.TargetType.Equals(Helpers.CommerceBestBetSelector)) { searchQuery = searchQuery.Filter(x => x.ContentLink.ProviderName.Match("CatalogContent")); } var searchResults = searchQuery.Select(c => c.ContentLink).Take(1).GetResult(); return searchResults.Hits.FirstOrDefault()?.Document; } } }
using System; using System.Linq; using EPiServer; using EPiServer.Core; using EPiServer.Find; using EPiServer.Find.Framework; using EPiServer.ServiceLocation; using Vro.FindExportImport.Models; namespace Vro.FindExportImport.Stores { public interface ISearchService { ContentReference FindMatchingContent(BestBetEntity bestBetEntity); } [ServiceConfiguration(typeof(ISearchService))] public class SearchService : ISearchService { public ContentReference FindMatchingContent(BestBetEntity bestBetEntity) { var searchQuery = SearchClient.Instance .Search<IContent>() .Filter(x => x.Name.Match(bestBetEntity.TargetName)); if (bestBetEntity.TargetType.Equals(Helpers.PageBestBetSelector)) { searchQuery = searchQuery.Filter(x => x.MatchTypeHierarchy(typeof(PageData))); } else if (bestBetEntity.TargetType.Equals(Helpers.CommerceBestBetSelector)) { // resolving type from string to avoid referencing Commerce assemblies var commerceCatalogEntryType = Type.GetType("EPiServer.Commerce.Catalog.ContentTypes.EntryContentBase, EPiServer.Business.Commerce"); searchQuery = searchQuery.Filter(x => x.MatchTypeHierarchy(commerceCatalogEntryType)); } var searchResults = searchQuery.Select(c => c.ContentLink).Take(1).GetResult(); return searchResults.Hits.FirstOrDefault()?.Document; } } }
Use type filtering when searching matching content for BestBets
Use type filtering when searching matching content for BestBets
C#
mit
SergVro/FindExportImport,SergVro/FindExportImport,SergVro/FindExportImport
84c6f9a068265cb8354f9c82bef8de14f7a8cd84
src/TrackTv.Updater/ApiResultRepository.cs
src/TrackTv.Updater/ApiResultRepository.cs
namespace TrackTv.Updater { using System; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using TrackTv.Data; public class ApiResultRepository { public ApiResultRepository(IDbService dbService) { this.DbService = dbService; } private IDbService DbService { get; } public Task SaveApiResult(object jsonObj, ApiChangeType type, int thetvdbid) { int apiResponseID = this.DbService.ApiResponses .Where(poco => poco.ApiResponseShowThetvdbid == thetvdbid || poco.ApiResponseEpisodeThetvdbid == thetvdbid) .Select(poco => poco.ApiResponseID) .FirstOrDefault(); var result = new ApiResponsePoco { ApiResponseID = apiResponseID, ApiResponseBody = JsonConvert.SerializeObject(jsonObj), ApiResponseLastUpdated = DateTime.UtcNow, }; switch (type) { case ApiChangeType.Show : result.ApiResponseShowThetvdbid = thetvdbid; break; case ApiChangeType.Episode : result.ApiResponseEpisodeThetvdbid = thetvdbid; break; default : throw new ArgumentOutOfRangeException(nameof(type), type, null); } return this.DbService.Save(result); } } }
namespace TrackTv.Updater { using System; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using TrackTv.Data; public class ApiResultRepository { public ApiResultRepository(IDbService dbService) { this.DbService = dbService; } private IDbService DbService { get; } public Task SaveApiResult(object jsonObj, ApiChangeType type, int thetvdbid) { int apiResponseID = this.DbService.ApiResponses .Where(poco => (type == ApiChangeType.Show && poco.ApiResponseShowThetvdbid == thetvdbid) || (type == ApiChangeType.Episode && poco.ApiResponseEpisodeThetvdbid == thetvdbid)) .Select(poco => poco.ApiResponseID) .FirstOrDefault(); var result = new ApiResponsePoco { ApiResponseID = apiResponseID, ApiResponseBody = JsonConvert.SerializeObject(jsonObj), ApiResponseLastUpdated = DateTime.UtcNow, }; switch (type) { case ApiChangeType.Show : result.ApiResponseShowThetvdbid = thetvdbid; break; case ApiChangeType.Episode : result.ApiResponseEpisodeThetvdbid = thetvdbid; break; default : throw new ArgumentOutOfRangeException(nameof(type), type, null); } return this.DbService.Save(result); } } }
Fix for the api_results FK collision.
Fix for the api_results FK collision.
C#
mit
HristoKolev/TrackTV,HristoKolev/TrackTV,HristoKolev/TrackTV,HristoKolev/TrackTV,HristoKolev/TrackTV
40a23b992159327b1d044bdd05b4feb13ff55a3e
osu.Framework.VisualTests/VisualTestGame.cs
osu.Framework.VisualTests/VisualTestGame.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Framework.Screens.Testing; namespace osu.Framework.VisualTests { internal class VisualTestGame : Game { [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { new TestBrowser(), new CursorContainer(), }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Cursor; using osu.Framework.Platform; using osu.Framework.Screens.Testing; namespace osu.Framework.VisualTests { internal class VisualTestGame : Game { [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { new TestBrowser(), new CursorContainer(), }; } protected override void LoadComplete() { base.LoadComplete(); Host.Window.CursorState = CursorState.Hidden; } } }
Set cursor invisible in visual test game
Set cursor invisible in visual test game
C#
mit
paparony03/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,default0/osu-framework,paparony03/osu-framework,ppy/osu-framework,RedNesto/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,Tom94/osu-framework,naoey/osu-framework,RedNesto/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,default0/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework
3ff5a31def87f04ea8ceaac7a4fd351c742260a4
src/Glimpse.Web.Common/ScriptInjector.cs
src/Glimpse.Web.Common/ScriptInjector.cs
using System.Text; using Microsoft.AspNet.Razor.Runtime.TagHelpers; using Microsoft.AspNet.Mvc.Rendering; namespace Glimpse.Web.Common { [TargetElement("body")] public class ScriptInjector : TagHelper { public override int Order => int.MaxValue; public override void Process(TagHelperContext context, TagHelperOutput output) { var js = new StringBuilder(); js.AppendLine("var link = document.createElement('a');"); js.AppendLine("link.setAttribute('href', '/glimpseui/index.html');"); js.AppendLine("link.setAttribute('target', '_blank');"); js.AppendLine("link.text = 'Open Glimpse';"); js.AppendLine("document.body.appendChild(link);"); var tag = new TagBuilder("script") { InnerHtml = new HtmlString(js.ToString()), }; output.PostContent.Append(tag.ToHtmlContent(TagRenderMode.Normal)); } } }
using System.Text; using Microsoft.AspNet.Razor.Runtime.TagHelpers; using Microsoft.AspNet.Mvc.Rendering; namespace Glimpse.Web.Common { [TargetElement("body")] public class ScriptInjector : TagHelper { public override int Order => int.MaxValue; public override void Process(TagHelperContext context, TagHelperOutput output) { var js = new StringBuilder(); js.AppendLine("var link = document.createElement('a');"); js.AppendLine("link.setAttribute('href', '/glimpseui/index.html');"); js.AppendLine("link.setAttribute('target', '_blank');"); js.AppendLine("link.text = 'Open Glimpse';"); js.AppendLine("document.body.appendChild(link);"); var tag = new TagBuilder("script") { InnerHtml = new HtmlString(js.ToString()), }; output.PostContent.Append(tag); } } }
Update tag helper usage from upstream breaking change
Update tag helper usage from upstream breaking change
C#
mit
mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype
c7b4b7da7d5f51346ca4f7c840fb82b9967d4db8
CertiPay.Payroll.Common/Address.cs
CertiPay.Payroll.Common/Address.cs
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CertiPay.Payroll.Common { [ComplexType] public class Address { // Warning: This is marked as a complex type, and used in several projects, so any changes will trickle down into EF changes... [StringLength(75)] public String Address1 { get; set; } [StringLength(75)] public String Address2 { get; set; } [StringLength(75)] public String Address3 { get; set; } [StringLength(50)] public String City { get; set; } public StateOrProvince State { get; set; } [DataType(DataType.PostalCode)] [StringLength(15)] [Display(Name = "Postal Code")] public String PostalCode { get; set; } // TODO: international fields public Address() { this.State = StateOrProvince.FL; } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CertiPay.Payroll.Common { /// <summary> /// Represents a basic address format for the United States /// </summary> [ComplexType] public class Address { // Warning: This is marked as a complex type, and used in several projects, so any changes will trickle down into EF changes... /// <summary> /// The first line of the address /// </summary> [StringLength(75)] public String Address1 { get; set; } /// <summary> /// The second line of the address /// </summary> [StringLength(75)] public String Address2 { get; set; } /// <summary> /// The third line of the address /// </summary> [StringLength(75)] public String Address3 { get; set; } /// <summary> /// The city the address is located in /// </summary> [StringLength(50)] public String City { get; set; } /// <summary> /// The state the address is located in /// </summary> public StateOrProvince State { get; set; } /// <summary> /// The postal "zip" code for the address, could include the additional four digits /// </summary> [DataType(DataType.PostalCode)] [StringLength(15)] [Display(Name = "Postal Code")] public String PostalCode { get; set; } public Address() { this.State = StateOrProvince.FL; } } }
Add API comments for address
Add API comments for address
C#
mit
mattgwagner/CertiPay.Payroll.Common
9358a0e4793b9e2c528017355ae7bb0c82e1275a
alert-roster.web/Views/Home/New.cshtml
alert-roster.web/Views/Home/New.cshtml
@model alert_roster.web.Models.Message @{ ViewBag.Title = "Post New Message"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm("New", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal"> <hr /> @Html.ValidationSummary(true) <div class="alert alert-info"> Please limit messages to < 160 characters. </div> <div class="form-group"> @Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextAreaFor(model => model.Content, new { rows = "3", cols = "80" }) @Html.ValidationMessageFor(model => model.Content) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Post" class="btn btn-default" /> </div> </div> </div> <div> @Html.ActionLink("Back to List", "Index") </div> }
@model alert_roster.web.Models.Message @{ ViewBag.Title = "Post New Message"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm("New", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-horizontal"> <hr /> @Html.ValidationSummary(true) <div class="alert alert-info"> Please limit messages to < 160 characters. Note that, due to notifications being sent, editing or deleting a post is currently unavailable. </div> <div class="form-group"> @Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextAreaFor(model => model.Content, new { rows = "3", cols = "80" }) @Html.ValidationMessageFor(model => model.Content) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Post" class="btn btn-default" /> </div> </div> </div> <div> @Html.ActionLink("Back to List", "Index") </div> }
Add warning about no edit/delete
Add warning about no edit/delete
C#
mit
mattgwagner/alert-roster
602bd3d89a8a732ad0abcc39bbfce494db95b6b7
BotBits/Packages/Login/Client/FutureProofLoginClient.cs
BotBits/Packages/Login/Client/FutureProofLoginClient.cs
using System.Threading.Tasks; using EE.FutureProof; using JetBrains.Annotations; using PlayerIOClient; namespace BotBits { public class FutureProofLoginClient : LoginClient { private const int CurrentVersion = 218; public FutureProofLoginClient([NotNull] ConnectionManager connectionManager, [NotNull] Client client) : base(connectionManager, client) { } protected override Task Attach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int? version) { var versionLoader = version.HasValue ? TaskHelper.FromResult(version.Value) : LoginUtils.GetVersionAsync(this.Client); return versionLoader.Then(v => { connectionManager.AttachConnection(connection.FutureProof(CurrentVersion, v.Result), args); }); } } }
using System.Threading.Tasks; using EE.FutureProof; using JetBrains.Annotations; using PlayerIOClient; namespace BotBits { public class FutureProofLoginClient : LoginClient { private const int CurrentVersion = 218; public FutureProofLoginClient([NotNull] ConnectionManager connectionManager, [NotNull] Client client) : base(connectionManager, client) { } protected override Task Attach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int? version) { var versionLoader = version.HasValue ? TaskHelper.FromResult(version.Value) : LoginUtils.GetVersionAsync(this.Client); return versionLoader.Then(v => { if (v.Result == CurrentVersion) { base.Attach(connectionManager, connection, args, v.Result); } else { this.FutureProofAttach(connectionManager, connection, args, v.Result); } }); } // This line is separated into a function to prevent uncessarily loading FutureProof into memory. private void FutureProofAttach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int version) { connectionManager.AttachConnection(connection.FutureProof(CurrentVersion, version), args); } } }
Optimize FutureProof to not load when the version is up to date
Optimize FutureProof to not load when the version is up to date
C#
mit
Yonom/BotBits
70d7231238f4b1a69f38136d479f6b794aa27417
CasualMeter.Common/Formatters/DamageTrackerFormatter.cs
CasualMeter.Common/Formatters/DamageTrackerFormatter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CasualMeter.Common.Helpers; using Tera.DamageMeter; namespace CasualMeter.Common.Formatters { public class DamageTrackerFormatter : Formatter { public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers) { var placeHolders = new List<KeyValuePair<string, object>>(); placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name)); placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration))); Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value); FormatProvider = formatHelpers.CultureInfo; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CasualMeter.Common.Helpers; using Tera.DamageMeter; namespace CasualMeter.Common.Formatters { public class DamageTrackerFormatter : Formatter { public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers) { var placeHolders = new List<KeyValuePair<string, object>>(); placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name??string.Empty)); placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration))); Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value); FormatProvider = formatHelpers.CultureInfo; } } }
Fix not pasting stats with no boss name available.
Fix not pasting stats with no boss name available.
C#
mit
Gl0/CasualMeter
44e059061365ad21fb624792bdaa8e33f9722bc0
src/Okanshi.Dashboard/GetMetrics.cs
src/Okanshi.Dashboard/GetMetrics.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public interface IGetMetrics { IEnumerable<Metric> Execute(string instanceName); } public class GetMetrics : IGetMetrics { private readonly IStorage _storage; public GetMetrics(IStorage storage) { _storage = storage; } public IEnumerable<Metric> Execute(string instanceName) { var webClient = new WebClient(); var response = webClient.DownloadString(_storage.GetAll().Single(x => x.Name.Equals(instanceName, StringComparison.OrdinalIgnoreCase)).Url); var jObject = JObject.Parse(response); JToken versionToken; jObject.TryGetValue("version", out versionToken); var version = "0"; if (versionToken != null && versionToken.HasValues) { version = versionToken.Value<string>(); } if (version.Equals("0", StringComparison.OrdinalIgnoreCase)) { var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response); return deserializeObject .Select(x => new Metric { Name = x.Key, Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(), WindowSize = x.Value.windowSize.ToObject<float>() }); } return Enumerable.Empty<Metric>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public interface IGetMetrics { IEnumerable<Metric> Execute(string instanceName); } public class GetMetrics : IGetMetrics { private readonly IStorage _storage; public GetMetrics(IStorage storage) { _storage = storage; } public IEnumerable<Metric> Execute(string instanceName) { var webClient = new WebClient(); var response = webClient.DownloadString(_storage.GetAll().Single(x => x.Name.Equals(instanceName, StringComparison.OrdinalIgnoreCase)).Url); var jObject = JObject.Parse(response); JToken versionToken; jObject.TryGetValue("version", out versionToken); var version = "0"; if (versionToken != null && versionToken.HasValues) { version = versionToken.Value<string>(); } if (version.Equals("0", StringComparison.OrdinalIgnoreCase)) { var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response); return deserializeObject .Select(x => new Metric { Name = x.Key, Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(), WindowSize = x.Value.windowSize.ToObject<float>() }); } throw new InvalidOperationException("Not supported version"); } } }
Throw exception on unsupported exception
Throw exception on unsupported exception
C#
mit
mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard
4213dde00547a60ad82fbe587e5ff7b2d45cad7d
Basic.Azure.Storage/Communications/QueueService/MessageOperations/ClearMessageRequest.cs
Basic.Azure.Storage/Communications/QueueService/MessageOperations/ClearMessageRequest.cs
using Basic.Azure.Storage.Communications.Core; using Basic.Azure.Storage.Communications.Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Basic.Azure.Storage.Communications.QueueService.MessageOperations { /// <summary> /// Deletes the specified queue item from the queue /// http://msdn.microsoft.com/en-us/library/azure/dd179347.aspx /// </summary> public class ClearMessageRequest : RequestBase<EmptyResponsePayload> { private string _queueName; public ClearMessageRequest(StorageAccountSettings settings, string queueName) : base(settings) { //TODO: add Guard statements against invalid values, short circuit so we don't have the latency roundtrip to the server _queueName = queueName; } protected override string HttpMethod { get { return "DELETE"; } } protected override StorageServiceType ServiceType { get { return StorageServiceType.QueueService; } } protected override RequestUriBuilder GetUriBase() { var builder = new RequestUriBuilder(Settings.QueueEndpoint); builder.AddSegment(_queueName); builder.AddSegment("messages"); return builder; } } }
using Basic.Azure.Storage.Communications.Core; using Basic.Azure.Storage.Communications.Core.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Basic.Azure.Storage.Communications.QueueService.MessageOperations { /// <summary> /// Clears the specified queue /// http://msdn.microsoft.com/en-us/library/azure/dd179454.aspx /// </summary> public class ClearMessageRequest : RequestBase<EmptyResponsePayload> { private string _queueName; public ClearMessageRequest(StorageAccountSettings settings, string queueName) : base(settings) { //TODO: add Guard statements against invalid values, short circuit so we don't have the latency roundtrip to the server _queueName = queueName; } protected override string HttpMethod { get { return "DELETE"; } } protected override StorageServiceType ServiceType { get { return StorageServiceType.QueueService; } } protected override RequestUriBuilder GetUriBase() { var builder = new RequestUriBuilder(Settings.QueueEndpoint); builder.AddSegment(_queueName); builder.AddSegment("messages"); return builder; } } }
Update comment for ClearMessages request
Update comment for ClearMessages request
C#
bsd-3-clause
BrianMcBrayer/BasicAzureStorageSDK,tarwn/BasicAzureStorageSDK