commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
f3c80c0f2edf8bc2966f8ddd4d3f756c73f7222a
Add diagnostic try-catch blocks to MorphInto()
arthurrump/Zermelo.App.UWP
Zermelo.App.UWP/Helpers/ObservableCollectionExtensions.cs
Zermelo.App.UWP/Helpers/ObservableCollectionExtensions.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zermelo.App.UWP.Helpers { static class ObservableCollectionExtensions { public static void MorphInto<TSource>(this ObservableCollection<TSource> first, IReadOnlyList<TSource> second) { var add = second.Except(first); var remove = first.Except(second); // TODO: Remove the diagnostic try-catch blocks, when #12 is fixed try { foreach (var i in remove) first.Remove(i); } catch (InvalidOperationException ex) { throw new Exception("Exception in the Remove loop.", ex); } try { foreach (var i in add) first.Add(i); } catch (InvalidOperationException ex) { throw new Exception("Exception in the Add loop.", ex); } try { // If there are any changes to first, make sure it's in // the same order as second. if (add.Count() > 0 || remove.Count() > 0) for (int i = 0; i < second.Count(); i++) first.Move(first.IndexOf(second.ElementAt(i)), i); } catch (InvalidOperationException ex) { throw new Exception("Exception in the reordering loop.", ex); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zermelo.App.UWP.Helpers { static class ObservableCollectionExtensions { public static void MorphInto<TSource>(this ObservableCollection<TSource> first, IReadOnlyList<TSource> second) { var add = second.Except(first); var remove = first.Except(second); foreach (var i in remove) first.Remove(i); foreach (var i in add) first.Add(i); // If there are any changes to first, make sure it's in // the same order as second. if (add.Count() > 0 || remove.Count() > 0) for (int i = 0; i < second.Count(); i++) first.Move(first.IndexOf(second.ElementAt(i)), i); } } }
mit
C#
be6250fc7628e3a712bf747c0deb441e4f01ea9a
update Q219
txchen/csharp-leet,txchen/csharp-leet
solutions/Q219.cs
solutions/Q219.cs
public class Solution { public bool ContainsNearbyDuplicate(int[] nums, int k) { HashSet<int> hs = new HashSet<int>(); for (int i = 0; i < nums.Length; i++) { if (!hs.Add(nums[i])) { return true; } if (i >= k) { hs.Remove(nums[i - k]); } } return false; } }
public class Solution { public bool ContainsNearbyDuplicate(int[] nums, int k) { for (int i = 0; i < nums.Length; i++) { for (int j = i + 1; j < nums.Length && (j - i) <= k; j++) { if (nums[j] == nums[i]) { return true; } } } return false; } }
mit
C#
e467f001d762ccc8c44cc0283c92010963a72696
remove ServerCmd enum
ivayloivanof/C-Sharp-Chat-Programm
Client/ChatClient/ChatClient/Command.cs
Client/ChatClient/ChatClient/Command.cs
namespace ChatClient { using System; using System.Collections.Generic; using System.Linq; public class ServerCommand { public ServerCommandList CommandList; public List<string> Args; public ServerCommand(string _CmdString) { fetchCmd(_CmdString); } public ServerCommand() { } public ServerCommand(int _cmd) { ClientCommandList CommandList = (ClientCommandList)Enum.Parse(typeof(ClientCommandList), _cmd.ToString()); } public void fetchCmd(string _CmdString) { string[] buff = _CmdString.Split(';'); ServerCommandList CommandList = (ServerCommandList)Enum.Parse(typeof(ServerCommandList), buff[0]); Args = buff.Where(w => w != buff[0]).ToList<string>(); } public override string ToString() { string myCmdString = ((int)this.CommandList).ToString(); return this.Args.Aggregate(myCmdString, (current, item) => current + ";" + item); } } }
namespace ChatClient { using System; using System.Collections.Generic; using System.Linq; public enum ServerCmd { //Responses of CommandList Login(4;Benutzername;BenutzerPW[;ServerPW]) isLogged,//(0) WrongPwd,//(1) NewUserRegistered,//(2) ServerIsFull,//(3) ServerIsPrivate,//(4) UserIsBanned,//(5) //Response of Cmd getLoggedUserList(6) LoggedUserList, // (6;User;User;User...) //Response of Cmd getLatestMsgLog(5) sendLatestMsgLog,//(7; Nachricht(User,Time,Msg);....;..;...) MsgLogRestricted, //(8) //Response of Cmd sendMsg(1;msg) MsgAccepted, // (9) //Response of Cmd Disconnect(2) DisconnectReceived, //(10) //Response of Cmd getServerInfo(16) SendServerInfo,//(11,serverName,serverMaxUserCount,currentUserCount,needPwd(bool)) spreadMsg, //(12,User,Time,Msg) ServerIsClosing, //(13[,ServerMsg]) WrongArgs,//(14) AlreadyLogged, //(15) NotLoggedIn,//(16) ChangeOfLoggedUserList,//(17,nameOfLoggedUser[,anotherNameOfLoggedUser],...) ChangeOfServerInfo,//(18,serverName,serverMaxUserCount,currentUserCount,needPwd(bool)) } public class ServerCommand { public ServerCmd cmd; public List<string> Args; public ServerCommand(string _CmdString) { fetchCmd(_CmdString); } public ServerCommand() { } public ServerCommand(int _cmd) { ClientCommandList CommandList = (ClientCommandList)Enum.Parse(typeof(ClientCommandList), _cmd.ToString()); } public void fetchCmd(string _CmdString) { string[] buff = _CmdString.Split(';'); ServerCmd cmd = (ServerCmd)Enum.Parse(typeof(ServerCmd), buff[0]); Args = buff.Where(w => w != buff[0]).ToList<string>(); } public override string ToString() { string myCmdString = ((int)cmd).ToString(); return this.Args.Aggregate(myCmdString, (current, item) => current + ";" + item); } } }
unlicense
C#
515f5c497704de857f07fffb86c6e35e32d690af
Refactor FindByColumnHeaderStrategy
YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata
src/Atata/ScopeSearch/Strategies/FindByColumnHeaderStrategy.cs
src/Atata/ScopeSearch/Strategies/FindByColumnHeaderStrategy.cs
using System.Linq; using OpenQA.Selenium; namespace Atata { public class FindByColumnHeaderStrategy : IComponentScopeLocateStrategy { private readonly string headerXPath; public FindByColumnHeaderStrategy() : this("(ancestor::table)[1]//th") { } public FindByColumnHeaderStrategy(string headerXPath) { this.headerXPath = headerXPath; } public ComponentScopeLocateResult Find(IWebElement scope, ComponentScopeLocateOptions options, SearchOptions searchOptions) { var headers = scope.GetAll(By.XPath(headerXPath).With(searchOptions).OfAnyVisibility()); var headerNamePredicate = options.Match.GetPredicate(); int? columnIndex = headers. Select((x, i) => new { x.Text, Index = i }). Where(x => options.Terms.Any(term => headerNamePredicate(x.Text, term))). Select(x => (int?)x.Index). FirstOrDefault(); if (columnIndex == null) { if (searchOptions.IsSafely) return new MissingComponentScopeLocateResult(); else throw ExceptionFactory.CreateForNoSuchElement(options.GetTermsAsString(), searchContext: scope); } return new FindByColumnIndexStrategy(columnIndex.Value).Find(scope, options, searchOptions); } } }
using System.Linq; using OpenQA.Selenium; namespace Atata { public class FindByColumnHeaderStrategy : IComponentScopeLocateStrategy { private readonly string headerXPath; public FindByColumnHeaderStrategy() : this("(ancestor::table)[1]//th") { } public FindByColumnHeaderStrategy(string headerXPath) { this.headerXPath = headerXPath; } public ComponentScopeLocateResult Find(IWebElement scope, ComponentScopeLocateOptions options, SearchOptions searchOptions) { var headers = scope.GetAll(By.XPath(headerXPath).With(searchOptions).OfAnyVisibility()); var headerNamePredicate = options.Match.GetPredicate(); int? columnIndex = headers. Select((x, i) => new { Text = x.Text, Index = i }). Where(x => options.Terms.Any(term => headerNamePredicate(x.Text, term))). Select(x => (int?)x.Index). FirstOrDefault(); if (columnIndex == null) { if (searchOptions.IsSafely) return new MissingComponentScopeLocateResult(); else throw ExceptionFactory.CreateForNoSuchElement(options.GetTermsAsString(), searchContext: scope); } return new FindByColumnIndexStrategy(columnIndex.Value).Find(scope, options, searchOptions); } } }
apache-2.0
C#
0c31248824964fb96198e27ef375b8cf8712b29b
Remove designer ImageBrush references
andburn/hdt-plugin-endgame
EndGame/Utilities/DesignerRepository.cs
EndGame/Utilities/DesignerRepository.cs
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Resources; using HDT.Plugins.EndGame.Models; using HDT.Plugins.EndGame.Services; namespace HDT.Plugins.EndGame.Utilities { public class DesignerRepository : ITrackerRepository { public List<ArchetypeDeck> GetAllArchetypeDecks() { return new List<ArchetypeDeck>() { new ArchetypeDeck("Control", Klass.Warrior, true), new ArchetypeDeck("Patron", Klass.Warrior, true), new ArchetypeDeck("Warrior", Klass.Warrior, true), new ArchetypeDeck("Zoolock", Klass.Warlock, true) }; } public string GetGameMode() { return "ranked"; } public string GetGameNote() { return "I'm a note"; } public Deck GetOpponentDeck() { StreamResourceInfo sri = Application.GetResourceStream( new Uri("pack://application:,,,/EndGame;component/Resources/card_sample.bmp")); BitmapImage bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = sri.Stream; bmp.EndInit(); var deck = new Deck(Klass.Druid, true); // FIXME need to use DrawingBrush //deck.Cards = new List<Card>() { // new Card("OG_280", "C'thun", 1, new ImageBrush(bmp)), // new Card("OG_280", "C'thun", 1, new ImageBrush(bmp)), // new Card("OG_280", "C'thun", 1, new ImageBrush(bmp)) //}; return deck; } public void AddDeck(Deck deck) { } public void AddDeck(string name, string playerClass, string cards, bool archive, params string[] tags) { } public void DeleteAllDecksWithTag(string tag) { } public void UpdateGameNote(string text) { } public bool IsInMenu() { return false; } } }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Resources; using HDT.Plugins.EndGame.Models; using HDT.Plugins.EndGame.Services; namespace HDT.Plugins.EndGame.Utilities { public class DesignerRepository : ITrackerRepository { public List<ArchetypeDeck> GetAllArchetypeDecks() { return new List<ArchetypeDeck>() { new ArchetypeDeck("Control", Klass.Warrior, true), new ArchetypeDeck("Patron", Klass.Warrior, true), new ArchetypeDeck("Warrior", Klass.Warrior, true), new ArchetypeDeck("Zoolock", Klass.Warlock, true) }; } public string GetGameMode() { return "ranked"; } public string GetGameNote() { return "I'm a note"; } public Deck GetOpponentDeck() { StreamResourceInfo sri = Application.GetResourceStream( new Uri("pack://application:,,,/EndGame;component/Resources/card_sample.bmp")); BitmapImage bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = sri.Stream; bmp.EndInit(); var deck = new Deck(Klass.Druid, true); deck.Cards = new List<Card>() { new Card("OG_280", "C'thun", 1, new ImageBrush(bmp)), new Card("OG_280", "C'thun", 1, new ImageBrush(bmp)), new Card("OG_280", "C'thun", 1, new ImageBrush(bmp)) }; return deck; } public void AddDeck(Deck deck) { } public void AddDeck(string name, string playerClass, string cards, bool archive, params string[] tags) { } public void DeleteAllDecksWithTag(string tag) { } public void UpdateGameNote(string text) { } public bool IsInMenu() { return false; } } }
mit
C#
2a180d7369cc9389491f22bbd1c78b0e961374fa
Remove unused log rows
michael-reichenauer/GitMind
GitMind/GitModel/Private/MRepository.cs
GitMind/GitModel/Private/MRepository.cs
using System; using System.Collections.Generic; using System.Linq; using GitMind.Features.StatusHandling; using GitMind.Git; using GitMind.Utils; namespace GitMind.GitModel.Private { public class MRepository { public static string CurrentVersion = "18"; // Serialized start ------------------- public string Version { get; set; } = CurrentVersion; public int CurrentCommitId { get; set; } public string CurrentBranchId { get; set; } public List<MCommit> Commits { get; set; } = new List<MCommit>(); public Dictionary<string, MBranch> Branches { get; set; } = new Dictionary<string, MBranch>(); public TimeSpan TimeToCreateFresh { get; set; } // Serialized Done --------------------- public Dictionary<string, MCommit> CommitsById { get; set; } = new Dictionary<string, MCommit>(); public Dictionary<string, MSubBranch> SubBranches { get; set; } = new Dictionary<string, MSubBranch>(); public string WorkingFolder { get; set; } public bool IsCached { get; set; } public Status Status { get; set; } = Status.Default; public MCommit Uncommitted { get; set; } public IReadOnlyList<string> RepositoryIds { get; set; } = new List<string>(); public MCommit CurrentCommit => Commits[CurrentCommitId]; public MBranch CurrentBranch => Branches[CurrentBranchId]; public MCommit Commit(int id) { return Commits[id]; } public MCommit Commit(string commitId) { MCommit commit; if (!CommitsById.TryGetValue(commitId, out commit)) { commit = AddNewCommit(commitId); } return commit; } public MCommit AddNewCommit(string commitId) { MCommit commit = new MCommit() { Repository = this, IndexId = Commits.Count, CommitId = commitId }; Commits.Add(commit); if (commitId != null) { CommitsById[commitId] = commit; } if (commitId == MCommit.UncommittedId) { Uncommitted = commit; } return commit; } public void CompleteDeserialization(string workingFolder) { WorkingFolder = workingFolder; SubBranches.ForEach(b => b.Value.Repository = this); Branches.ForEach(b => b.Value.Repository = this); Commits.ForEach(c => { c.Repository = this; if (c.CommitId != null) { CommitsById[c.CommitId] = c; } if (c.CommitId == MCommit.UncommittedId) { Uncommitted = c; } }); } } }
using System; using System.Collections.Generic; using System.Linq; using GitMind.Features.StatusHandling; using GitMind.Git; using GitMind.Utils; namespace GitMind.GitModel.Private { public class MRepository { public static string CurrentVersion = "18"; // Serialized start ------------------- public string Version { get; set; } = CurrentVersion; public int CurrentCommitId { get; set; } public string CurrentBranchId { get; set; } public List<MCommit> Commits { get; set; } = new List<MCommit>(); public Dictionary<string, MBranch> Branches { get; set; } = new Dictionary<string, MBranch>(); public TimeSpan TimeToCreateFresh { get; set; } // Serialized Done --------------------- public Dictionary<string, MCommit> CommitsById { get; set; } = new Dictionary<string, MCommit>(); public Dictionary<string, MSubBranch> SubBranches { get; set; } = new Dictionary<string, MSubBranch>(); public string WorkingFolder { get; set; } public bool IsCached { get; set; } public Status Status { get; set; } = Status.Default; public MCommit Uncommitted { get; set; } public IReadOnlyList<string> RepositoryIds { get; set; } = new List<string>(); public MCommit CurrentCommit => Commits[CurrentCommitId]; public MBranch CurrentBranch => Branches[CurrentBranchId]; public MCommit Commit(int id) { return Commits[id]; } public MCommit Commit(string commitId) { MCommit commit; if (!CommitsById.TryGetValue(commitId, out commit)) { commit = AddNewCommit(commitId); } return commit; } public MCommit AddNewCommit(string commitId) { MCommit commit = new MCommit() { Repository = this, IndexId = Commits.Count, CommitId = commitId }; Commits.Add(commit); if (commitId != null) { CommitsById[commitId] = commit; } if (commitId == MCommit.UncommittedId) { Uncommitted = commit; } return commit; } public void CompleteDeserialization(string workingFolder) { WorkingFolder = workingFolder; SubBranches.ForEach(b => b.Value.Repository = this); Branches.ForEach(b => b.Value.Repository = this); Log.Warn($"Commits: {Commits.Count}"); Commits.ForEach(c => { c.Repository = this; if (c.CommitId != null) { CommitsById[c.CommitId] = c; } if (c.CommitId == MCommit.UncommittedId) { Log.Warn($"Commit: {c}"); Uncommitted = c; } }); } } }
mit
C#
16ded911d57649c2c8fbdc76e0cd621a06fcecaf
Update Fizz.cs
metaphorce/leaguesharp
MetaSmite/Champions/Fizz.cs
MetaSmite/Champions/Fizz.cs
using System; using LeagueSharp; using LeagueSharp.Common; using SharpDX; namespace MetaSmite.Champions { public static class Fizz { internal static Spell champSpell; private static Menu Config = MetaSmite.Config; private static double totalDamage; private static double spellDamage; public static void Load() { //Load spells champSpell = new Spell(SpellSlot.Q, 550f); //Spell usage. Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true); //Events Game.OnUpdate += OnGameUpdate; } private static void OnGameUpdate(EventArgs args) { if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active) { if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range) { spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot); totalDamage = spellDamage + SmiteManager.damage; if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && SmiteManager.smite.IsReady() && champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } } } } } }
using System; using LeagueSharp; using LeagueSharp.Common; using SharpDX; namespace MetaSmite.Champions { public static class Fizz { internal static Spell champSpell; private static Menu Config = MetaSmite.Config; private static double totalDamage; private static double spellDamage; public static void Load() { //Load spells champSpell = new Spell(SpellSlot.Q, 550f); //Spell usage. Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true); //Events Game.OnGameUpdate += OnGameUpdate; } private static void OnGameUpdate(EventArgs args) { if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active) { if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range) { spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot); totalDamage = spellDamage + SmiteManager.damage; if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && SmiteManager.smite.IsReady() && champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() && champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health) { MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob); } } } } } }
mit
C#
af6acbd0598339d994cf16ba31f93a85f4bb1bbf
Bump Cake.Recipe from 2.2.0 to 2.2.1
Redth/Cake.Json,Redth/Cake.Json
recipe.cake
recipe.cake
#load nuget:?package=Cake.Recipe&version=2.2.1 Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "Cake.Json", repositoryOwner: "cake-contrib", repositoryName: "Cake.Json", appVeyorAccountName: "cakecontrib", shouldRunDotNetCorePack: true, shouldRunDupFinder: false, shouldRunInspectCode: false, preferredBuildProviderType: BuildProviderType.GitHubActions); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/Cake.Json.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[FakeItEasy]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
#load nuget:?package=Cake.Recipe&version=2.2.0 Environment.SetVariableNames(); BuildParameters.SetParameters(context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "Cake.Json", repositoryOwner: "cake-contrib", repositoryName: "Cake.Json", appVeyorAccountName: "cakecontrib", shouldRunDotNetCorePack: true, shouldRunDupFinder: false, shouldRunInspectCode: false, preferredBuildProviderType: BuildProviderType.GitHubActions); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings(context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/Cake.Json.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[FakeItEasy]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
apache-2.0
C#
b7450e7c690474d188063a03492e7c7e81b6dcaa
Split session and request ID properties to avoid recording superfluous information (e.g. with sessions disabled)
colin-young/serilog,vorou/serilog,redwards510/serilog,adamchester/serilog,JuanjoFuchs/serilog,colin-young/serilog,khellang/serilog,clarkis117/serilog,harishjan/serilog,skomis-mm/serilog,ravensorb/serilog,richiej84/serilog,serilog/serilog,clarkis117/serilog,zmaruo/serilog,harishjan/serilog,Jaben/serilog,serilog/serilog,joelweiss/serilog,nblumhardt/serilog,merbla/serilog,CaioProiete/serilog,ravensorb/serilog,skomis-mm/serilog,DavidSSL/serilog,nblumhardt/serilog,joelweiss/serilog,richardlawley/serilog,vossad01/serilog,merbla/serilog,adamchester/serilog,SaltyDH/serilog,Applicita/serilog,ajayanandgit/serilog,paulcbetts/serilog,paulcbetts/serilog,jotautomation/serilog
src/Serilog.Web/Web/Enrichers/HttpRequestPropertiesEnricher.cs
src/Serilog.Web/Web/Enrichers/HttpRequestPropertiesEnricher.cs
// Copyright 2013 Nicholas Blumhardt // // 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.Threading; using System.Web; using Serilog.Core; using Serilog.Events; namespace Serilog.Web.Enrichers { /// <summary> /// Enrich log events with HttpRequestId and HttpSessionId properties. /// </summary> public class HttpRequestPropertiesEnricher : ILogEventEnricher { const string HttpRequestIdPropertyName = "HttpRequestId"; const string HttpSessionIdPropertyName = "HttpSessionId"; static int LastRequestId; static readonly string RequestIdItemName = typeof(HttpRequestPropertiesEnricher).Name + "+RequestId"; /// <summary> /// Enrich the log event with properties from the currently-executing HTTP request, if any. /// </summary> /// <param name="logEvent">The log event to enrich.</param> /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param> public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { if (logEvent == null) throw new ArgumentNullException("logEvent"); if (propertyFactory == null) throw new ArgumentNullException("propertyFactory"); if (HttpContext.Current == null) return; int requestId; var requestIdItem = HttpContext.Current.Items[RequestIdItemName]; if (requestIdItem == null) HttpContext.Current.Items[RequestIdItemName] = requestId = Interlocked.Increment(ref LastRequestId); else requestId = (int)requestIdItem; var requestIdProperty = propertyFactory.CreateProperty(HttpRequestIdPropertyName, requestId); logEvent.AddPropertyIfAbsent(requestIdProperty); if (HttpContext.Current.Session != null) { var sessionId = HttpContext.Current.Session.SessionID; var sesionIdProperty = propertyFactory.CreateProperty(HttpSessionIdPropertyName, sessionId); logEvent.AddPropertyIfAbsent(sesionIdProperty); } } } }
// Copyright 2013 Nicholas Blumhardt // // 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.Threading; using System.Web; using Serilog.Core; using Serilog.Events; namespace Serilog.Web.Enrichers { /// <summary> /// Enrich log events with a 'HttpRequest' property that supports correlation of events within the /// request and session. /// </summary> public class HttpRequestPropertiesEnricher : ILogEventEnricher { const string HttpRequestPropertyName = "HttpRequest"; static int LastRequestId; static readonly string RequestIdItemName = typeof(HttpRequestPropertiesEnricher).Name + "+RequestId"; /// <summary> /// Enrich the log event with properties from the currently-executing HTTP request, if any. /// </summary> /// <param name="logEvent">The log event to enrich.</param> /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param> public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { if (logEvent == null) throw new ArgumentNullException("logEvent"); if (propertyFactory == null) throw new ArgumentNullException("propertyFactory"); if (HttpContext.Current == null) return; int requestId; var requestIdItem = HttpContext.Current.Items[RequestIdItemName]; if (requestIdItem == null) HttpContext.Current.Items[RequestIdItemName] = requestId = Interlocked.Increment(ref LastRequestId); else requestId = (int)requestIdItem; string sessionId = null; if (HttpContext.Current.Session != null) sessionId = HttpContext.Current.Session.SessionID; logEvent.AddPropertyIfAbsent( propertyFactory.CreateProperty(HttpRequestPropertyName, new { SessionId = sessionId, Id = requestId }, destructureObjects: true)); } } }
apache-2.0
C#
e1a8c8a137b8c0634401bdab0a059ed8e7a17050
Add giftcard method to list of methods
foxip/mollie-api-csharp
Mollie.Api/Models/Method.cs
Mollie.Api/Models/Method.cs
namespace Mollie.Api.Models { /// <summary> /// Payment method /// </summary> public enum Method { ideal, creditcard, mistercash, sofort, banktransfer, directdebit, belfius, kbc, bitcoin, paypal, paysafecard, giftcard, } }
namespace Mollie.Api.Models { /// <summary> /// Payment method /// </summary> public enum Method { ideal, creditcard, mistercash, sofort, banktransfer, directdebit, belfius, kbc, bitcoin, paypal, paysafecard, } }
bsd-2-clause
C#
9e93956187b58840776aabee60669b758462a385
Raise an exception when the size of the array is too large.
dlemstra/Magick.NET,dlemstra/Magick.NET
Magick.NET/Core/Helpers/StreamHelper.cs
Magick.NET/Core/Helpers/StreamHelper.cs
//================================================================================================= // Copyright 2013-2016 Dirk Lemstra <https://magick.codeplex.com/> // // Licensed under the ImageMagick License (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.imagemagick.org/script/license.php // // 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.IO; namespace ImageMagick { internal static class StreamHelper { private static void CheckLength(long length) { if (length > 2147483591) throw new ArgumentException("Streams with a length larger than 2147483591 are not supported, read from file instead.", "stream"); } internal static byte[] ToByteArray(Stream stream) { Throw.IfNull("stream", stream); MemoryStream memStream = stream as MemoryStream; if (memStream != null) { try { return memStream.GetBuffer(); } catch (UnauthorizedAccessException) { return memStream.ToArray(); } } if (stream.CanSeek) { if (stream.Length == 0) return new byte[0]; CheckLength(stream.Length); int length = (int)stream.Length; byte[] result = new byte[length]; stream.Read(result, 0, length); return result; } int bufferSize = 8192; using (MemoryStream tmpStream = new MemoryStream()) { byte[] buffer = new byte[bufferSize]; int length; while ((length = stream.Read(buffer, 0, bufferSize)) != 0) { CheckLength(tmpStream.Length + length); tmpStream.Write(buffer, 0, length); } return tmpStream.ToArray(); } } } }
//================================================================================================= // Copyright 2013-2016 Dirk Lemstra <https://magick.codeplex.com/> // // Licensed under the ImageMagick License (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.imagemagick.org/script/license.php // // 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.IO; namespace ImageMagick { internal static class StreamHelper { internal static byte[] ToByteArray(Stream stream) { Throw.IfNull("stream", stream); MemoryStream memStream = stream as MemoryStream; if (memStream != null) { try { return memStream.GetBuffer(); } catch (UnauthorizedAccessException) { return memStream.ToArray(); } } if (stream.CanSeek) { int length = (int)stream.Length; if (length == 0) return new byte[0]; byte[] result = new byte[length]; stream.Read(result, 0, length); return result; } else { int bufferSize = 8192; using (MemoryStream tmpStream = new MemoryStream()) { byte[] buffer = new byte[bufferSize]; int length; while ((length = stream.Read(buffer, 0, bufferSize)) != 0) { tmpStream.Write(buffer, 0, length); } return tmpStream.ToArray(); } } } } }
apache-2.0
C#
55bd7d25126f0441a1367188e80e7f17d606f200
Add failing coverage for saving difficulty params from editor
peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu-new
osu.Game.Tests/Visual/Editing/TestSceneEditorSaving.cs
osu.Game.Tests/Visual/Editing/TestSceneEditorSaving.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Input; using osu.Framework.Testing; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit; using osu.Game.Screens.Menu; using osu.Game.Screens.Select; using osuTK.Input; namespace osu.Game.Tests.Visual.Editing { public class TestSceneEditorSaving : OsuGameTestScene { private Editor editor => Game.ChildrenOfType<Editor>().FirstOrDefault(); private EditorBeatmap editorBeatmap => (EditorBeatmap)editor.Dependencies.Get(typeof(EditorBeatmap)); /// <summary> /// Tests the general expected flow of creating a new beatmap, saving it, then loading it back from song select. /// </summary> [Test] public void TestNewBeatmapSaveThenLoad() { AddStep("set default beatmap", () => Game.Beatmap.SetDefault()); PushAndConfirm(() => new EditorLoader()); AddUntilStep("wait for editor load", () => editor != null); AddStep("Set overall difficulty", () => editorBeatmap.Difficulty.OverallDifficulty = 7); AddStep("Add timing point", () => editorBeatmap.ControlPointInfo.Add(0, new TimingControlPoint())); AddStep("Enter compose mode", () => InputManager.Key(Key.F1)); AddUntilStep("Wait for compose mode load", () => editor.ChildrenOfType<HitObjectComposer>().FirstOrDefault()?.IsLoaded == true); AddStep("Change to placement mode", () => InputManager.Key(Key.Number2)); AddStep("Move to playfield", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.Centre)); AddStep("Place single hitcircle", () => InputManager.Click(MouseButton.Left)); AddStep("Save and exit", () => { InputManager.Keys(PlatformAction.Save); InputManager.Key(Key.Escape); }); AddUntilStep("Wait for main menu", () => Game.ScreenStack.CurrentScreen is MainMenu); PushAndConfirm(() => new PlaySongSelect()); AddUntilStep("Wait for beatmap selected", () => !Game.Beatmap.IsDefault); AddStep("Open options", () => InputManager.Key(Key.F3)); AddStep("Enter editor", () => InputManager.Key(Key.Number5)); AddUntilStep("Wait for editor load", () => editor != null); AddAssert("Beatmap contains single hitcircle", () => editorBeatmap.HitObjects.Count == 1); AddAssert("Beatmap has correct overall difficulty", () => editorBeatmap.Difficulty.OverallDifficulty == 7); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Input; using osu.Framework.Testing; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit; using osu.Game.Screens.Menu; using osu.Game.Screens.Select; using osuTK.Input; namespace osu.Game.Tests.Visual.Editing { public class TestSceneEditorSaving : OsuGameTestScene { private Editor editor => Game.ChildrenOfType<Editor>().FirstOrDefault(); private EditorBeatmap editorBeatmap => (EditorBeatmap)editor.Dependencies.Get(typeof(EditorBeatmap)); /// <summary> /// Tests the general expected flow of creating a new beatmap, saving it, then loading it back from song select. /// </summary> [Test] public void TestNewBeatmapSaveThenLoad() { AddStep("set default beatmap", () => Game.Beatmap.SetDefault()); PushAndConfirm(() => new EditorLoader()); AddUntilStep("wait for editor load", () => editor != null); AddStep("Add timing point", () => editorBeatmap.ControlPointInfo.Add(0, new TimingControlPoint())); AddStep("Enter compose mode", () => InputManager.Key(Key.F1)); AddUntilStep("Wait for compose mode load", () => editor.ChildrenOfType<HitObjectComposer>().FirstOrDefault()?.IsLoaded == true); AddStep("Change to placement mode", () => InputManager.Key(Key.Number2)); AddStep("Move to playfield", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.Centre)); AddStep("Place single hitcircle", () => InputManager.Click(MouseButton.Left)); AddStep("Save and exit", () => { InputManager.Keys(PlatformAction.Save); InputManager.Key(Key.Escape); }); AddUntilStep("Wait for main menu", () => Game.ScreenStack.CurrentScreen is MainMenu); PushAndConfirm(() => new PlaySongSelect()); AddUntilStep("Wait for beatmap selected", () => !Game.Beatmap.IsDefault); AddStep("Open options", () => InputManager.Key(Key.F3)); AddStep("Enter editor", () => InputManager.Key(Key.Number5)); AddUntilStep("Wait for editor load", () => editor != null); AddAssert("Beatmap contains single hitcircle", () => editorBeatmap.HitObjects.Count == 1); } } }
mit
C#
935cccbf6f8aab2c3b19e21ed0d702d14bef23c3
Swap bits
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
ElementsOfProgrammingInterviews/PrimitiveTypes/reverse_bits.cs
ElementsOfProgrammingInterviews/PrimitiveTypes/reverse_bits.cs
using System; class Program { static byte reverse(byte x) { int y = 0; while (x != 0) { y = (y << 1) | (x & 1); x >>= 1; } return (byte) y; } public static void Main(string[] args) { byte x = (byte) new Random().Next(10, 255); byte y = reverse(x); Console.WriteLine("{0} - {1} - {2} - {3}", x, Convert.ToString(x, 2), y, Convert.ToString(y, 2)); } }
using System; class Program { public static void Main(string[] args) { } }
mit
C#
8944eb9cdf6e2390210fed84e60c7168d7c01615
make dependencies transient
SRoddis/Mongo.Migration
Mongo.Migration/Startup/DotNetCore/MongoMigrationExtensions.cs
Mongo.Migration/Startup/DotNetCore/MongoMigrationExtensions.cs
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Mongo.Migration.Documents.Locators; using Mongo.Migration.Documents.Serializers; using Mongo.Migration.Migrations; using Mongo.Migration.Migrations.Locators; using Mongo.Migration.Services; using Mongo.Migration.Services.Interceptors; namespace Mongo.Migration.Startup.DotNetCore { public static class MongoMigrationExtensions { public static void AddMigration( this IServiceCollection services) { RegisterDefaults(services); services.AddScoped<IMigrationService, MigrationService>(); } private static void RegisterDefaults(IServiceCollection services) { services.AddSingleton<IMigrationLocator, TypeMigrationLocator>(); services.AddSingleton<ICollectionLocator, CollectionLocator>(); services.AddSingleton<ICurrentVersionLocator, CurrentVersionLocator>(); services.AddSingleton<ICollectionVersionLocator, CollectionVersionLocator>(); services.AddTransient<IVersionService, VersionService>(); services.AddTransient<IMigrationInterceptorFactory, MigrationInterceptorFactory>(); services.AddTransient<DocumentVersionSerializer, DocumentVersionSerializer>(); services.AddTransient<ICollectionMigrationRunner, CollectionMigrationRunner>(); services.AddTransient<IMigrationRunner, MigrationRunner>(); services.AddTransient<MigrationInterceptorProvider, MigrationInterceptorProvider>(); services.AddTransient<IMongoMigration, MongoMigration>(); services.AddTransient<IStartupFilter, MongoMigrationStartupFilter>(); } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Mongo.Migration.Documents.Locators; using Mongo.Migration.Documents.Serializers; using Mongo.Migration.Migrations; using Mongo.Migration.Migrations.Locators; using Mongo.Migration.Services; using Mongo.Migration.Services.Interceptors; namespace Mongo.Migration.Startup.DotNetCore { public static class MongoMigrationExtensions { public static void AddMigration( this IServiceCollection services) { RegisterDefaults(services); services.AddScoped<IMigrationService, MigrationService>(); } private static void RegisterDefaults(IServiceCollection services) { services.AddSingleton<IMigrationLocator, TypeMigrationLocator>(); services.AddSingleton<ICollectionLocator, CollectionLocator>(); services.AddSingleton<ICurrentVersionLocator, CurrentVersionLocator>(); services.AddSingleton<ICollectionVersionLocator, CollectionVersionLocator>(); services.AddScoped<IVersionService, VersionService>(); services.AddScoped<IMigrationInterceptorFactory, MigrationInterceptorFactory>(); services.AddScoped<DocumentVersionSerializer, DocumentVersionSerializer>(); services.AddScoped<ICollectionMigrationRunner, CollectionMigrationRunner>(); services.AddScoped<IMigrationRunner, MigrationRunner>(); services.AddScoped<MigrationInterceptorProvider, MigrationInterceptorProvider>(); services.AddScoped<IMongoMigration, MongoMigration>(); services.AddTransient<IStartupFilter, MongoMigrationStartupFilter>(); } } }
mit
C#
d9f5c320f6ca8f915aada806b438321d32e51979
Update ExeRunXml.cs
Seddryck/NBi,Seddryck/NBi
NBi.Xml/Decoration/Command/ExeRunXml.cs
NBi.Xml/Decoration/Command/ExeRunXml.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.IO; using NBi.Core.Process; namespace NBi.Xml.Decoration.Command { public class ExeRunXml : DecorationCommandXml, IRunCommand { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("path")] public string InternalPath { get; set; } [XmlAttribute("arguments")] public string Arguments { get; set; } [XmlIgnore] public string Argument { get { return Arguments; } } [XmlIgnore] public string FullPath { get { var fullPath = string.Empty; if (Path.IsPathRooted(InternalPath) || String.IsNullOrEmpty(Settings.BasePath)) fullPath = InternalPath + Name; else fullPath = Settings.BasePath + InternalPath + Name; return fullPath; } } [XmlAttribute("timeout-milliseconds")] [DefaultValue(0)] public int TimeOut { get; set; } public ExeRunXml() { TimeOut = 0; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using System.IO; using NBi.Core.Process; namespace NBi.Xml.Decoration.Command { public class ExeRunXml : DecorationCommandXml, IRunCommand { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("path")] public string InternalPath { get; set; } [XmlAttribute("arguments")] public string Arguments { get; set; } [XmlIgnore] public string Argument { get { return Arguments; } } [XmlIgnore] public string FullPath { get { var fullPath = string.Empty; if (Path.IsPathRooted(InternalPath) || String.IsNullOrEmpty(Settings.BasePath)) fullPath = InternalPath + Name; else fullPath = Settings.BasePath + fullPath + Name; return fullPath; } } [XmlAttribute("timeout-milliseconds")] [DefaultValue(0)] public int TimeOut { get; set; } public ExeRunXml() { TimeOut = 0; } } }
apache-2.0
C#
19589f2506778ca2bbb4640ee273c9bd1f0be476
Add global exception handler.
ryanjfitz/SimpSim.NET
SimpSim.NET.WPF/App.xaml.cs
SimpSim.NET.WPF/App.xaml.cs
using System.Windows; using Prism.Ioc; using SimpSim.NET.WPF.ViewModels; using SimpSim.NET.WPF.Views; namespace SimpSim.NET.WPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { public App() { DispatcherUnhandledException += (sender, e) => { MessageBox.Show(e.Exception.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error); e.Handled = true; }; } protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton<SimpleSimulator>(); containerRegistry.Register<IUserInputService, UserInputService>(); containerRegistry.Register<IDialogServiceAdapter, DialogServiceAdapter>(); containerRegistry.RegisterSingleton<IStateSaver, StateSaver>(); containerRegistry.RegisterDialog<AssemblyEditorDialog, AssemblyEditorDialogViewModel>(); } } }
using System.Windows; using Prism.Ioc; using SimpSim.NET.WPF.ViewModels; using SimpSim.NET.WPF.Views; namespace SimpSim.NET.WPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton<SimpleSimulator>(); containerRegistry.Register<IUserInputService, UserInputService>(); containerRegistry.Register<IDialogServiceAdapter, DialogServiceAdapter>(); containerRegistry.RegisterSingleton<IStateSaver, StateSaver>(); containerRegistry.RegisterDialog<AssemblyEditorDialog, AssemblyEditorDialogViewModel>(); } } }
mit
C#
7f5cca8825f86a38a202f4d9e0df5bffcb5835cd
Make ints nullable
davek17/SurveyMonkeyApi-v3,bcemmett/SurveyMonkeyApi-v3
SurveyMonkey/Containers/QuestionDisplayOptionsCustomOptions.cs
SurveyMonkey/Containers/QuestionDisplayOptionsCustomOptions.cs
using Newtonsoft.Json; using System.Collections.Generic; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class QuestionDisplayOptionsCustomOptions { public List<string> OptionSet { get; set; } public int? StartingPosition { get; set; } //slider questions public int? StepSize { get; set; } //slider questions public string Color { get; set; } //star rating questions } }
using Newtonsoft.Json; using System.Collections.Generic; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class QuestionDisplayOptionsCustomOptions { public List<string> OptionSet { get; set; } public int StartingPosition { get; set; } //slider questions public int StepSize { get; set; } //slider questions public string Color { get; set; } //star rating questions } }
mit
C#
531bb2b319cb16b825c8393a07ce57e8117f7ed6
add new ctor for Message
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TeraPacketParser/Message.cs
TeraPacketParser/Message.cs
using System; using FoglioUtils.Extensions; using TeraPacketParser.Data; namespace TeraPacketParser { public class Message { public Message(DateTime time, MessageDirection direction, ArraySegment<byte> data) { Time = time; Direction = direction; Data = data; } public Message(DateTime time, byte[] data) { Data = new ArraySegment<byte>(data); Time = time; } public Message(DateTime time, MessageDirection dir, string hex) : this(time, dir, new ArraySegment<byte>(hex.ToByteArrayHex())) { } public DateTime Time { get; private set; } public MessageDirection Direction { get; private set; } public ArraySegment<byte> Data { get; } // ReSharper disable once PossibleNullReferenceException public ushort OpCode => (ushort)(Data.Array[Data.Offset] | Data.Array[Data.Offset + 1] << 8); // ReSharper disable once AssignNullToNotNullAttribute public ArraySegment<byte> Payload => new ArraySegment<byte>(Data.Array, Data.Offset + 2, Data.Count - 2); } }
using System; using FoglioUtils.Extensions; using TeraPacketParser.Data; namespace TeraPacketParser { public class Message { public Message(DateTime time, MessageDirection direction, ArraySegment<byte> data) { Time = time; Direction = direction; Data = data; } public Message(DateTime time, MessageDirection dir, string hex) : this(time, dir, new ArraySegment<byte>(hex.ToByteArrayHex())) { } public DateTime Time { get; private set; } public MessageDirection Direction { get; private set; } public ArraySegment<byte> Data { get; } // ReSharper disable once PossibleNullReferenceException public ushort OpCode => (ushort) (Data.Array[Data.Offset] | Data.Array[Data.Offset + 1] << 8); // ReSharper disable once AssignNullToNotNullAttribute public ArraySegment<byte> Payload => new ArraySegment<byte>(Data.Array, Data.Offset + 2, Data.Count - 2); } }
mit
C#
05f347bf57d6c4d9fb55a3e9b5b20dfe0d5110b3
update NetHelper.
13f/picker
Picker/Picker.Core/Helpers/NetHelper.cs
Picker/Picker.Core/Helpers/NetHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; namespace Picker.Core.Helpers { public static class NetHelper { public static WebClient GetWebClient_UTF8(){ WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.UTF8; client.UseDefaultCredentials = true; client.Headers.Add( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0" ); return client; } public static WebClient GetWebClient_GB2312() { WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.GetEncoding( "GB2312" ); client.UseDefaultCredentials = true; client.Headers.Add( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0" ); return client; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; namespace Picker.Core.Helpers { public static class NetHelper { public static WebClient GetWebClient_UTF8(){ WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.UTF8; client.UseDefaultCredentials = true; return client; } public static WebClient GetWebClient_GB2312() { WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.GetEncoding( "GB2312" ); client.UseDefaultCredentials = true; return client; } } }
mit
C#
180aee6048e69c7119849a9037a85fbcefaa3137
Fix iOS build
UselessToucan/osu,smoogipoo/osu,naoey/osu,DrabWeb/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,DrabWeb/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,naoey/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,2yangk23/osu,2yangk23/osu,EVAST9919/osu,NeoAdonis/osu,smoogipooo/osu,naoey/osu,DrabWeb/osu,johnneijzen/osu,peppy/osu,UselessToucan/osu,ZLima12/osu,peppy/osu,ppy/osu
osu.iOS/OsuGameIOS.cs
osu.iOS/OsuGameIOS.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Foundation; using osu.Game; namespace osu.iOS { public class OsuGameIOS : OsuGame { public override Version AssemblyVersion => new Version(NSBundle.MainBundle.InfoDictionary["CFBundleVersion"].ToString()); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Foundation; using osu.Game; namespace osu.iOS { public class OsuGameIOS : OsuGame { protected override Version AssemblyVersion => new Version(NSBundle.MainBundle.InfoDictionary["CFBundleVersion"].ToString()); } }
mit
C#
db84f8bbe3e4d0be2f14c88b86d09c906fb7d99e
Make FlowEmptyModel public
daniel-luberda/DLToolkit.Forms.Controls
FlowListView/DLToolkit.Forms.Controls.FlowListView/FlowEmptyModel.cs
FlowListView/DLToolkit.Forms.Controls.FlowListView/FlowEmptyModel.cs
using System; namespace DLToolkit.Forms.Controls { [Helpers.FlowListView.Preserve(AllMembers = true)] public class FlowEmptyModel { } }
using System; namespace DLToolkit.Forms.Controls { [Helpers.FlowListView.Preserve(AllMembers = true)] internal class FlowEmptyModel { } }
apache-2.0
C#
66b1d0f70c0b9844a8d899be8e32fb6fa4148143
Add in a cost property in IGameItem interface
liam-middlebrook/Navier-Boats
Navier-Boats/Navier-Boats/Navier-Boats/Engine/Inventory/IGameItem.cs
Navier-Boats/Navier-Boats/Navier-Boats/Engine/Inventory/IGameItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Navier_Boats.Engine.Entities; namespace Navier_Boats.Engine.Inventory { public interface IGameItem : IInteractable { Texture2D InventoryTexture { get; set; } Texture2D ItemTexture { get; set; } int MaxStack { get; set; } int Cost { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Navier_Boats.Engine.Entities; namespace Navier_Boats.Engine.Inventory { public interface IGameItem : IInteractable { Texture2D InventoryTexture { get; set; } Texture2D ItemTexture { get; set; } int MaxStack { get; set; } } }
apache-2.0
C#
a11399c2dbfcadbc1af07ca03512c3a1c047c4a8
Fix LicenseHeaer in AssemblyInfo.Shared (#1056)
SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource-DotNet/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,SonarSource/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild
AssemblyInfo.Shared.cs
AssemblyInfo.Shared.cs
/* * SonarScanner for MSBuild * Copyright (C) 2016-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("5.2.2")] [assembly: AssemblyFileVersion("5.2.2.0")] [assembly: AssemblyInformationalVersion("Version:5.2.2.0 Branch:not-set Sha1:not-set")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015-2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
/* * SonarScanner for MSBuild * Copyright (C) 2016-2020 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("5.2.2")] [assembly: AssemblyFileVersion("5.2.2.0")] [assembly: AssemblyInformationalVersion("Version:5.2.2.0 Branch:not-set Sha1:not-set")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015-2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
mit
C#
3da8937d75d32a3ab8560945d60685fe886b8f07
Fix `VsCodeDiffProgram` path selection on Windows
droyad/Assent
src/Assent/Reporters/DiffPrograms/VsCodeDiffProgram.cs
src/Assent/Reporters/DiffPrograms/VsCodeDiffProgram.cs
using System; using System.Collections.Generic; using System.Linq; namespace Assent.Reporters.DiffPrograms { public class VsCodeDiffProgram : DiffProgramBase { static VsCodeDiffProgram() { var paths = new List<string>(); if (DiffReporter.IsWindows) { paths.AddRange(WindowsProgramFilePaths .Select(p => $@"{p}\Microsoft VS Code\Code.exe") .ToArray()); } else { paths.Add("/usr/local/bin/code"); } DefaultSearchPaths = paths; } public static readonly IReadOnlyList<string> DefaultSearchPaths; public VsCodeDiffProgram() : base(DefaultSearchPaths) { } public VsCodeDiffProgram(IReadOnlyList<string> searchPaths) : base(searchPaths) { } protected override string CreateProcessStartArgs(string receivedFile, string approvedFile) { return $"--diff --wait --new-window \"{receivedFile}\" \"{approvedFile}\""; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Assent.Reporters.DiffPrograms { public class VsCodeDiffProgram : DiffProgramBase { static VsCodeDiffProgram() { var paths = new List<string>(); if (DiffReporter.IsWindows) { DefaultSearchPaths = WindowsProgramFilePaths .Select(p => $@"{p}\Microsoft VS Code\Code.exe") .ToArray(); } else { paths.Add("/usr/local/bin/code"); } DefaultSearchPaths = paths; } public static readonly IReadOnlyList<string> DefaultSearchPaths; public VsCodeDiffProgram() : base(DefaultSearchPaths) { } public VsCodeDiffProgram(IReadOnlyList<string> searchPaths) : base(searchPaths) { } protected override string CreateProcessStartArgs(string receivedFile, string approvedFile) { return $"--diff --wait --new-window \"{receivedFile}\" \"{approvedFile}\""; } } }
mit
C#
ec27ffa4ed01ba2bee89f966df25dd1d303b06a0
Fix old attribute
trenoncourt/AutoQueryable
src/AutoQueryable/Attributes/AutoQueryableAttribute.cs
src/AutoQueryable/Attributes/AutoQueryableAttribute.cs
using System; using AutoQueryable.Filters; using AutoQueryable.Models; using Microsoft.AspNetCore.Mvc.Filters; namespace AutoQueryable.Attributes { [AttributeUsage(AttributeTargets.Method)] public class AutoQueryableAttribute : Attribute, IFilterFactory, IOrderedFilter { // A nullable-int cannot be used as an Attribute parameter. private bool? _useFallbackValue; /// <summary> /// Gets or sets the value which determines whether the data should be stored or not. /// When set to <see langword="true"/>, it sets "Cache-control" header to "no-store". /// Ignores the "Location" parameter for values other than "None". /// Ignores the "duration" parameter. /// </summary> public bool UseFallbackValue { get { return _useFallbackValue ?? false; } set { _useFallbackValue = value; } } public Type DbContextType { get; set; } public Type EntityType { get; set; } public string[] UnselectableProperties { get; set; } /// <inheritdoc /> public bool IsReusable { get; set; } /// <inheritdoc /> public int Order { get; set; } public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } _useFallbackValue = _useFallbackValue ?? false; var profile = new AutoQueryableProfile { DbContextType = DbContextType, EntityType = EntityType, UseFallbackValue = _useFallbackValue.Value, UnselectableProperties = UnselectableProperties }; if (DbContextType != null && EntityType != null) { Type typeFilterExecuting = typeof(AutoQueryableFilter<>).MakeGenericType(EntityType); var oExecuting = Activator.CreateInstance(typeFilterExecuting, profile, serviceProvider) as IActionFilter; return oExecuting; } return new AutoQueryableFilter(profile); } } }
using System; using AutoQueryable.Filters; using AutoQueryable.Models; using Microsoft.AspNetCore.Mvc.Filters; namespace AutoQueryable.Attributes { [AttributeUsage(AttributeTargets.Method)] public class AutoQueryableAttribute : Attribute, IFilterFactory, IOrderedFilter { // A nullable-int cannot be used as an Attribute parameter. private bool? _useFallbackValue; /// <summary> /// Gets or sets the value which determines whether the data should be stored or not. /// When set to <see langword="true"/>, it sets "Cache-control" header to "no-store". /// Ignores the "Location" parameter for values other than "None". /// Ignores the "duration" parameter. /// </summary> public bool UseFallbackValue { get { return _useFallbackValue ?? false; } set { _useFallbackValue = value; } } public Type DbContextType { get; set; } public Type EntityType { get; set; } public string[] UnselectableProperties { get; set; } /// <inheritdoc /> public bool IsReusable { get; set; } /// <inheritdoc /> public int Order { get; set; } public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } _useFallbackValue = _useFallbackValue ?? false; var profile = new AutoQueryableProfile { DbContextType = DbContextType, EntityType = EntityType, UseFallbackValue = _useFallbackValue.Value, UnselectableProperties = UnselectableProperties }; if (DbContextType != null && EntityType != null) { Type typeFilterExecuting = typeof(AutoQueryableFilter<>).MakeGenericType(EntityType); var oExecuting = Activator.CreateInstance(typeFilterExecuting, profile, serviceProvider) as IAsyncActionFilter; return oExecuting; } return new AutoQueryableFilter(profile); } } }
mit
C#
654da6ef5943b4376dea906f8e4313266be292ea
add missing FlagsAttribute
jberezanski/PSKnownFolders
BlaSoft.PowerShell.KnownFolders/Win32/KF_REDIRECT_FLAGS.cs
BlaSoft.PowerShell.KnownFolders/Win32/KF_REDIRECT_FLAGS.cs
using System; namespace BlaSoft.PowerShell.KnownFolders.Win32 { [Flags] internal enum KF_REDIRECT_FLAGS { KF_REDIRECT_NONE = 0, KF_REDIRECT_USER_EXCLUSIVE = 0x00000001, KF_REDIRECT_COPY_SOURCE_DACL = 0x00000002, KF_REDIRECT_OWNER_USER = 0x00000004, KF_REDIRECT_SET_OWNER_EXPLICIT = 0x00000008, KF_REDIRECT_CHECK_ONLY = 0x00000010, KF_REDIRECT_WITH_UI = 0x00000020, KF_REDIRECT_UNPIN = 0x00000040, KF_REDIRECT_PIN = 0x00000080, KF_REDIRECT_COPY_CONTENTS = 0x00000200, KF_REDIRECT_DEL_SOURCE_CONTENTS = 0x00000400, KF_REDIRECT_EXCLUDE_ALL_KNOWN_SUBFOLDERS = 0x00000800 } }
namespace BlaSoft.PowerShell.KnownFolders.Win32 { internal enum KF_REDIRECT_FLAGS { KF_REDIRECT_NONE = 0, KF_REDIRECT_USER_EXCLUSIVE = 0x00000001, KF_REDIRECT_COPY_SOURCE_DACL = 0x00000002, KF_REDIRECT_OWNER_USER = 0x00000004, KF_REDIRECT_SET_OWNER_EXPLICIT = 0x00000008, KF_REDIRECT_CHECK_ONLY = 0x00000010, KF_REDIRECT_WITH_UI = 0x00000020, KF_REDIRECT_UNPIN = 0x00000040, KF_REDIRECT_PIN = 0x00000080, KF_REDIRECT_COPY_CONTENTS = 0x00000200, KF_REDIRECT_DEL_SOURCE_CONTENTS = 0x00000400, KF_REDIRECT_EXCLUDE_ALL_KNOWN_SUBFOLDERS = 0x00000800 } }
mit
C#
7c62277c5d564ee4e4603ae0ca112934c7e7ccf0
add range to With functions.
bordoley/FunctionalHttp
FunctionalHttp.CSharpInterop/Core/ContentInfoExtensions.cs
FunctionalHttp.CSharpInterop/Core/ContentInfoExtensions.cs
using FunctionalHttp.Collections; using Microsoft.FSharp.Collections; using Microsoft.FSharp.Core; using System; using System.Collections.Generic; namespace FunctionalHttp.Core.Interop { public static class ContentInfoExtensionsCSharp { public static ContentInfo With( this ContentInfo This, IEnumerable<ContentCoding> encodings = null, IEnumerable<LanguageTag> languages = null, UInt64? length = null, Uri location = null, MediaType mediaType = null, FSharpChoice<ByteContentRange, OtherContentRange> range = null) { return ContentInfoModule.With( encodings.ToFSharpOption(), languages.ToFSharpOption(), length.ToFSharpOption(), location.ToFSharpOption(), mediaType.ToFSharpOption(), range.ToFSharpOption(), This); } public static ContentInfo Without( this ContentInfo This, bool encodings = false, bool languages = false, bool length = false, bool location = false, bool mediaType = false, bool range = false) { return ContentInfoModule.Without(encodings, languages, length, location, mediaType, range, This); } } }
using FunctionalHttp.Collections; using Microsoft.FSharp.Collections; using Microsoft.FSharp.Core; using System; using System.Collections.Generic; namespace FunctionalHttp.Core.Interop { public static class ContentInfoExtensionsCSharp { public static ContentInfo With( this ContentInfo This, IEnumerable<ContentCoding> encodings = null, IEnumerable<LanguageTag> languages = null, UInt64? length = null, Uri location = null, MediaType mediaType = null) { return ContentInfoModule.With( encodings.ToFSharpOption(), languages.ToFSharpOption(), length.ToFSharpOption(), location.ToFSharpOption(), mediaType.ToFSharpOption(), This); } public static ContentInfo Without( this ContentInfo This, bool encodings = false, bool languages = false, bool length = false, bool location = false, bool mediaType = false) { return ContentInfoModule.Without(encodings, languages, length, location, mediaType, This); } } }
apache-2.0
C#
3380ec8a9312d60805a9d70374a8d651ef9c9eaf
Fix merge issue
karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS
src/Host/Client/Impl/Extensions/AboutHostExtensions.cs
src/Host/Client/Impl/Extensions/AboutHostExtensions.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Reflection; using Microsoft.Common.Core; using Microsoft.R.Host.Protocol; namespace Microsoft.R.Host.Client { public static class AboutHostExtensions { private static readonly Version _localVersion; static AboutHostExtensions() { _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version; } public static string IsHostVersionCompatible(this AboutHost aboutHost) { if (_localVersion.MajorRevision != 0 || _localVersion.MinorRevision != 0) { // Filter out debug builds var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor); var clientVersion = new Version(_localVersion.Major, _localVersion.Minor); if (serverVersion > clientVersion) { return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion); } if (serverVersion < clientVersion) { return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion); } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Reflection; using Microsoft.Common.Core; using Microsoft.R.Host.Protocol; namespace Microsoft.R.Host.Client { public static class AboutHostExtensions { private static readonly Version _localVersion; static AboutHostExtensions() { _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version; } public static string IsHostVersionCompatible(this AboutHost aboutHost) { if (_localVersion.MajorRevision != 0 || _localVersion.MinorRevision != 0) { // Filter out debug builds var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor); var clientVersion = new Version(_localVersion.Major, _localVersion.Minor); if (serverVersion > clientVersion) { return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion); } if (serverVersion < clientVersion) { return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion); } } #endif return null; } } }
mit
C#
f829caf197c7565bf8d4995073d1eae17c183579
Fix custom logic still existing in OsuInputManager
ppy/osu,EVAST9919/osu,2yangk23/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,smoogipoo/osu,johnneijzen/osu,UselessToucan/osu,2yangk23/osu,johnneijzen/osu,naoey/osu,peppy/osu-new,DrabWeb/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,peppy/osu,ppy/osu,naoey/osu,peppy/osu,peppy/osu,EVAST9919/osu,Frontear/osuKyzer,DrabWeb/osu,ZLima12/osu,UselessToucan/osu,DrabWeb/osu,Damnae/osu,ZLima12/osu,Drezi126/osu,NeoAdonis/osu,Nabile-Rahmani/osu
osu.Game.Rulesets.Osu/OsuInputManager.cs
osu.Game.Rulesets.Osu/OsuInputManager.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using osu.Framework.Input.Bindings; using osu.Game.Input.Bindings; namespace osu.Game.Rulesets.Osu { public class OsuInputManager : DatabasedKeyBindingInputManager<OsuAction> { public OsuInputManager(RulesetInfo ruleset) : base(ruleset, 0, SimultaneousBindingMode.Unique) { } } public enum OsuAction { [Description("Left Button")] LeftButton, [Description("Right Button")] RightButton } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using System.Linq; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Game.Input.Bindings; using OpenTK.Input; using KeyboardState = osu.Framework.Input.KeyboardState; using MouseState = osu.Framework.Input.MouseState; namespace osu.Game.Rulesets.Osu { public class OsuInputManager : DatabasedKeyBindingInputManager<OsuAction> { public OsuInputManager(RulesetInfo ruleset) : base(ruleset, 0, SimultaneousBindingMode.Unique) { } protected override void TransformState(InputState state) { base.TransformState(state); var mouse = state.Mouse as MouseState; var keyboard = state.Keyboard as KeyboardState; if (mouse != null && keyboard != null) { if (mouse.IsPressed(MouseButton.Left)) keyboard.Keys = keyboard.Keys.Concat(new[] { Key.LastKey + 1 }); if (mouse.IsPressed(MouseButton.Right)) keyboard.Keys = keyboard.Keys.Concat(new[] { Key.LastKey + 2 }); } } } public enum OsuAction { [Description("Left Button")] LeftButton, [Description("Right Button")] RightButton } }
mit
C#
2bb608b1bdac5d95e04a43b36d40129ac7aab5be
Fix typo.
AxeDotNet/AxePractice.CSharpViaTest
src/CSharpViaTest.Collections/30_MapReducePractices/GetMaxNumbersInMultipleCollections.cs
src/CSharpViaTest.Collections/30_MapReducePractices/GetMaxNumbersInMultipleCollections.cs
using System; using System.Collections.Generic; using System.Linq; using CSharpViaTest.Collections.Annotations; using CSharpViaTest.Collections.Helpers; using Xunit; namespace CSharpViaTest.Collections._30_MapReducePractices { [SuperEasy] public class GetMaxNumbersInMultipleCollections { static IEnumerable<IEnumerable<int>> CreateStreamsContainingMaxNumber(int maxNumber) { return Enumerable .Range(0, 10) .Select(reduced => maxNumber - reduced) .Select(max => NumberStreamFactory.CreateWithTopNumber(max, 100000)); } #region Please modifies the code to pass the test static int GetMaxNumber(IEnumerable<IEnumerable<int>> collections) { throw new NotImplementedException(); } #endregion [Fact] public void should_get_max_numbers_in_collections() { IEnumerable<IEnumerable<int>> streams = CreateStreamsContainingMaxNumber(100); int maxNumber = GetMaxNumber(streams); Assert.Equal(100, maxNumber); } } }
using System; using System.Collections.Generic; using System.Linq; using CSharpViaTest.Collections.Annotations; using CSharpViaTest.Collections.Helpers; using Xunit; namespace CSharpViaTest.Collections._30_MapReducePractices { [SuperEasy] public class GetMaxNumbersInMultipleCollections { static IEnumerable<IEnumerable<int>> CreateStreamsContainingMaxNumber(int maxNumber) { return Enumerable .Range(0, 10) .Select(reduced => maxNumber - reduced) .Select(max => NumberStreamFactory.CreateWithTopNumber(max, 100000)); } #region Please modifies the code to pass the test static int GetMaxNumber(IEnumerable<IEnumerable<int>> collections) { throw new NotImplementedException(); } #endregion [Fact] public void should_get_top_10_numbers_in_collections() { IEnumerable<IEnumerable<int>> streams = CreateStreamsContainingMaxNumber(100); int maxNumber = GetMaxNumber(streams); Assert.Equal(100, maxNumber); } } }
mit
C#
e61d28014599bbe276d6edd97a4ec699c1bb19ff
Fix CI issues
EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework
osu.Framework/Graphics/Video/FfmpegExtensions.cs
osu.Framework/Graphics/Video/FfmpegExtensions.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using FFmpeg.AutoGen; namespace osu.Framework.Graphics.Video { internal static class FfmpegExtensions { internal static double GetValue(this AVRational rational) => rational.num / (double)rational.den; } }
using FFmpeg.AutoGen; using System; using System.Collections.Generic; using System.Text; namespace osu.Framework.Graphics.Video { internal static class FfmpegExtensions { internal static double GetValue(this AVRational rational) => rational.num / (double)rational.den; } }
mit
C#
3fee7587bc3c3943836f23f5e2420f2eb985b03a
Make the shuffle more noticable.
wieslawsoltes/Perspex,wieslawsoltes/Perspex,OronDF343/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,akrisiun/Perspex,wieslawsoltes/Perspex,jazzay/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,danwalmsley/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,MrDaedra/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,punker76/Perspex,SuperJMN/Avalonia,susloparovdenis/Perspex,susloparovdenis/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,MrDaedra/Avalonia,susloparovdenis/Avalonia,SuperJMN/Avalonia,grokys/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,kekekeks/Perspex,AvaloniaUI/Avalonia,kekekeks/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,OronDF343/Avalonia,AvaloniaUI/Avalonia
samples/BindingTest/ViewModels/MainWindowViewModel.cs
samples/BindingTest/ViewModels/MainWindowViewModel.cs
using System; using System.Collections.ObjectModel; using ReactiveUI; namespace BindingTest.ViewModels { public class MainWindowViewModel : ReactiveObject { private string _simpleBinding = "Simple Binding"; public MainWindowViewModel() { Items = new ObservableCollection<TestItem> { new TestItem { StringValue = "Foo" }, new TestItem { StringValue = "Bar" }, new TestItem { StringValue = "Baz" }, }; ShuffleItems = ReactiveCommand.Create(); ShuffleItems.Subscribe(_ => { var r = new Random(); Items[1] = Items[r.Next(Items.Count)]; }); } public ObservableCollection<TestItem> Items { get; } public ReactiveCommand<object> ShuffleItems { get; } public string SimpleBinding { get { return _simpleBinding; } set { this.RaiseAndSetIfChanged(ref _simpleBinding, value); } } } }
using System; using System.Collections.ObjectModel; using ReactiveUI; namespace BindingTest.ViewModels { public class MainWindowViewModel : ReactiveObject { private string _simpleBinding = "Simple Binding"; public MainWindowViewModel() { Items = new ObservableCollection<TestItem> { new TestItem { StringValue = "Foo" }, new TestItem { StringValue = "Bar" }, new TestItem { StringValue = "Baz" }, }; ShuffleItems = ReactiveCommand.Create(); ShuffleItems.Subscribe(_ => { var r = new Random(); Items[r.Next(Items.Count)] = Items[r.Next(Items.Count)]; }); } public ObservableCollection<TestItem> Items { get; } public ReactiveCommand<object> ShuffleItems { get; } public string SimpleBinding { get { return _simpleBinding; } set { this.RaiseAndSetIfChanged(ref _simpleBinding, value); } } } }
mit
C#
48efb686f1d4a1c6c678f3996c6d1cea43401d53
Set size for the fields on contact form
davidsonsousa/CMSEngine,davidsonsousa/CMSEngine,davidsonsousa/CMSEngine,davidsonsousa/CMSEngine
CmsEngine.Application/Helpers/Email/ContactForm.cs
CmsEngine.Application/Helpers/Email/ContactForm.cs
using System.ComponentModel.DataAnnotations; using Newtonsoft.Json.Linq; namespace CmsEngine.Application.Helpers.Email { public class ContactForm { [Required] [DataType(DataType.EmailAddress)] public string From { get; set; } [DataType(DataType.EmailAddress)] public string To { get; set; } [Required] [MaxLength(150)] public string Subject { get; set; } [Required] [MaxLength(500)] public string Message { get; set; } public ContactForm() { } public ContactForm(string to, string subject, string message) { To = to; Subject = subject; Message = message; } public override string ToString() { var jsonResult = new JObject( new JProperty("From", From), new JProperty("To", To), new JProperty("Subject", Subject), new JProperty("Message", Message) ); return jsonResult.ToString(); } } }
using System.ComponentModel.DataAnnotations; using Newtonsoft.Json.Linq; namespace CmsEngine.Application.Helpers.Email { public class ContactForm { [Required] [DataType(DataType.EmailAddress)] public string From { get; set; } [DataType(DataType.EmailAddress)] public string To { get; set; } [Required] public string Subject { get; set; } [Required] public string Message { get; set; } public ContactForm() { } public ContactForm(string to, string subject, string message) { To = to; Subject = subject; Message = message; } public override string ToString() { var jsonResult = new JObject( new JProperty("From", From), new JProperty("To", To), new JProperty("Subject", Subject), new JProperty("Message", Message) ); return jsonResult.ToString(); } } }
mit
C#
ed6a239191b814358f9299b509a4c409782c9429
Update StringExtensions.cs
digipost/digipost-api-client-dotnet
Digipost.Api.Client/Extensions/StringExtensions.cs
Digipost.Api.Client/Extensions/StringExtensions.cs
using System.Text.RegularExpressions; namespace Digipost.Api.Client.Extensions { internal static class StringExtensions { /// <summary> /// Removes reserved characters and commonly encoded characters as explained in https://en.wikipedia.org/wiki/Percent-encoding /// </summary> /// <param name="str">string to remove data from</param> /// <returns></returns> public static string RemoveReservedUriCharacters(this string str ) { Regex pattern = new Regex("[!#$&'()*+,/:;=?[\\]@%-.<>^_`{|}~]"); return pattern.Replace(str, ""); } } }
using System.Text.RegularExpressions; namespace Digipost.Api.Client.Extensions { public static class StringExtensions { /// <summary> /// Removes reserved characters and commonly encoded characters as explained in https://en.wikipedia.org/wiki/Percent-encoding /// </summary> /// <param name="str">string to remove data from</param> /// <returns></returns> public static string RemoveReservedUriCharacters(this string str ) { Regex pattern = new Regex("[!#$&'()*+,/:;=?[\\]@%-.<>^_`{|}~]"); return pattern.Replace(str, ""); } } }
apache-2.0
C#
8c1679ea7672057212492c0f871e9d0c8c39ec4d
Disable 2nd sandbox test by default
b0bi79/ClosedXML,ClosedXML/ClosedXML,igitur/ClosedXML
ClosedXML_Sandbox/Program.cs
ClosedXML_Sandbox/Program.cs
using System; namespace ClosedXML_Sandbox { internal static class Program { private static void Main(string[] args) { Console.WriteLine("Running {0}", nameof(PerformanceRunner.OpenTestFile)); PerformanceRunner.TimeAction(PerformanceRunner.OpenTestFile); Console.WriteLine(); // Disable this block by default - I don't use it often #if false Console.WriteLine("Running {0}", nameof(PerformanceRunner.RunInsertTable)); PerformanceRunner.TimeAction(PerformanceRunner.RunInsertTable); Console.WriteLine(); #endif Console.WriteLine("Press any key to continue"); Console.ReadKey(); } } }
using System; namespace ClosedXML_Sandbox { internal class Program { private static void Main(string[] args) { Console.WriteLine("Running {0}", nameof(PerformanceRunner.OpenTestFile)); PerformanceRunner.TimeAction(PerformanceRunner.OpenTestFile); Console.WriteLine(); Console.WriteLine("Running {0}", nameof(PerformanceRunner.RunInsertTable)); PerformanceRunner.TimeAction(PerformanceRunner.RunInsertTable); Console.WriteLine(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); } } }
mit
C#
95de71af32850ab653ae643ea2996f22a98b7114
Update GlobalMouseListener.cs
gmamaladze/globalmousekeyhook
MouseKeyHook/Implementation/GlobalMouseListener.cs
MouseKeyHook/Implementation/GlobalMouseListener.cs
// This code is distributed under MIT license. // Copyright (c) 2015 George Mamaladze // See license.txt or https://mit-license.org/ using System.Windows.Forms; using Gma.System.MouseKeyHook.WinApi; namespace Gma.System.MouseKeyHook.Implementation { internal class GlobalMouseListener : MouseListener { private readonly int m_SystemDoubleClickTime; private MouseButtons m_PreviousClicked; private Point m_PreviousClickedPosition; private int m_PreviousClickedTime; public GlobalMouseListener() : base(HookHelper.HookGlobalMouse) { m_SystemDoubleClickTime = MouseNativeMethods.GetDoubleClickTime(); } protected override void ProcessDown(ref MouseEventExtArgs e) { if (IsDoubleClick(e)) e = e.ToDoubleClickEventArgs(); else StartDoubleClickWaiting(e); base.ProcessDown(ref e); } protected override void ProcessUp(ref MouseEventExtArgs e) { base.ProcessUp(ref e); if (e.Clicks == 2) StopDoubleClickWaiting(); } private void StartDoubleClickWaiting(MouseEventExtArgs e) { m_PreviousClicked = e.Button; m_PreviousClickedTime = e.Timestamp; m_PreviousClickedPosition = e.Point; } private void StopDoubleClickWaiting() { m_PreviousClicked = MouseButtons.None; m_PreviousClickedTime = 0; m_PreviousClickedPosition = new Point(0, 0); } private bool IsDoubleClick(MouseEventExtArgs e) { return e.Button == m_PreviousClicked && e.Point == m_PreviousClickedPosition && // Click-move-click exception, see Patch 11222 e.Timestamp - m_PreviousClickedTime <= m_SystemDoubleClickTime; } protected override MouseEventExtArgs GetEventArgs(CallbackData data) { return MouseEventExtArgs.FromRawDataGlobal(data); } } }
// This code is distributed under MIT license. // Copyright (c) 2015 George Mamaladze // See license.txt or https://mit-license.org/ using System.Windows.Forms; using Gma.System.MouseKeyHook.WinApi; namespace Gma.System.MouseKeyHook.Implementation { internal class GlobalMouseListener : MouseListener { private readonly int m_SystemDoubleClickTime; private MouseButtons m_PreviousClicked; private Point m_PreviousClickedPosition; private int m_PreviousClickedTime; public GlobalMouseListener() : base(HookHelper.HookGlobalMouse) { m_SystemDoubleClickTime = MouseNativeMethods.GetDoubleClickTime(); } protected override void ProcessDown(ref MouseEventExtArgs e) { if (IsDoubleClick(e)) e = e.ToDoubleClickEventArgs(); base.ProcessDown(ref e); } protected override void ProcessUp(ref MouseEventExtArgs e) { base.ProcessUp(ref e); if (e.Clicks == 2) StopDoubleClickWaiting(); if (e.Clicks == 1) StartDoubleClickWaiting(e); } private void StartDoubleClickWaiting(MouseEventExtArgs e) { m_PreviousClicked = e.Button; m_PreviousClickedTime = e.Timestamp; m_PreviousClickedPosition = e.Point; } private void StopDoubleClickWaiting() { m_PreviousClicked = MouseButtons.None; m_PreviousClickedTime = 0; m_PreviousClickedPosition = new Point(0, 0); } private bool IsDoubleClick(MouseEventExtArgs e) { return e.Button == m_PreviousClicked && e.Point == m_PreviousClickedPosition && // Click-move-click exception, see Patch 11222 e.Timestamp - m_PreviousClickedTime <= m_SystemDoubleClickTime; } protected override MouseEventExtArgs GetEventArgs(CallbackData data) { return MouseEventExtArgs.FromRawDataGlobal(data); } } }
mit
C#
252d89000d2694059553a42afaf71a479fb7be51
Fix comment copy+paste fail
AntiTcb/Discord.Net,Confruggy/Discord.Net,LassieME/Discord.Net,RogueException/Discord.Net
src/Discord.Net.Commands/Attributes/NameAttribute.cs
src/Discord.Net.Commands/Attributes/NameAttribute.cs
using System; namespace Discord.Commands { // Override public name of command/module [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class NameAttribute : Attribute { public string Text { get; } public NameAttribute(string text) { Text = text; } } }
using System; namespace Discord.Commands { // Full summary of method [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class NameAttribute : Attribute { public string Text { get; } public NameAttribute(string text) { Text = text; } } }
mit
C#
0de86757373dd1ce905abc954ab1dfff0a98907b
Remove unnecessary blank lines
AmadeusW/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,stephentoub/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,tmat/roslyn,davkean/roslyn,gafter/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,physhi/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,davkean/roslyn,dotnet/roslyn,tannergooding/roslyn,genlu/roslyn,gafter/roslyn,brettfo/roslyn,mavasani/roslyn,aelij/roslyn,brettfo/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,AlekseyTs/roslyn,gafter/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,tannergooding/roslyn,mavasani/roslyn,diryboy/roslyn,jmarolf/roslyn,bartdesmet/roslyn,diryboy/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,davkean/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,sharwell/roslyn,heejaechang/roslyn,eriawan/roslyn,diryboy/roslyn,aelij/roslyn,KevinRansom/roslyn,wvdd007/roslyn,panopticoncentral/roslyn,physhi/roslyn,stephentoub/roslyn,KevinRansom/roslyn,jmarolf/roslyn,aelij/roslyn,AmadeusW/roslyn,heejaechang/roslyn,dotnet/roslyn,eriawan/roslyn,AmadeusW/roslyn,panopticoncentral/roslyn,physhi/roslyn,brettfo/roslyn,weltkante/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,stephentoub/roslyn,genlu/roslyn,mgoertz-msft/roslyn,mavasani/roslyn
src/Features/Lsif/Generator/Writing/LsifConverter.cs
src/Features/Lsif/Generator/Writing/LsifConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { internal sealed class LsifConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(ISerializableId).IsAssignableFrom(objectType) || objectType == typeof(Uri); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { switch (value) { case ISerializableId id: writer.WriteValue(id.NumericId); break; case Uri uri: writer.WriteValue(uri.AbsoluteUri); break; default: throw new NotSupportedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { internal sealed class LsifConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(ISerializableId).IsAssignableFrom(objectType) || objectType == typeof(Uri); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { switch (value) { case ISerializableId id: writer.WriteValue(id.NumericId); break; case Uri uri: writer.WriteValue(uri.AbsoluteUri); break; default: throw new NotSupportedException(); } } } }
mit
C#
8a1d4ab62ae0ec448c128b2f03864c6f8ce2faff
Fix deprecation
nikeee/HolzShots
src/HolzShots.Core/Net/Custom/SemVersionConverter.cs
src/HolzShots.Core/Net/Custom/SemVersionConverter.cs
using Newtonsoft.Json; using Semver; namespace HolzShots.Net.Custom { /// <summary> /// Taken from /// https://gist.github.com/madaz/efab4a5554b88dc2862d58046ddba00f /// (https://github.com/maxhauser/semver/issues/21) /// </summary> public class SemVersionConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (value == null) { writer.WriteNull(); } else { if (value is not SemVersion) throw new JsonSerializationException("Expected SemVersion object value"); writer.WriteValue(value.ToString()); } } public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (reader.TokenType == JsonToken.Null) return null; if (reader.TokenType != JsonToken.String) throw new JsonSerializationException($"Unexpected token or value when parsing version. Token: {reader.TokenType}, Value: {reader.Value}"); try { var v = reader.Value as string; return SemVersion.Parse(v, SemVersionStyles.Strict); } catch (Exception ex) { throw new JsonSerializationException($"Error parsing SemVersion string: {reader.Value}", ex); } } public override bool CanConvert(Type objectType) => objectType == typeof(SemVersion); } }
using Newtonsoft.Json; using Semver; namespace HolzShots.Net.Custom { /// <summary> /// Taken from /// https://gist.github.com/madaz/efab4a5554b88dc2862d58046ddba00f /// (https://github.com/maxhauser/semver/issues/21) /// </summary> public class SemVersionConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (value == null) { writer.WriteNull(); } else { if (!(value is SemVersion)) throw new JsonSerializationException("Expected SemVersion object value"); writer.WriteValue(value.ToString()); } } public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (reader.TokenType == JsonToken.Null) return null; if (reader.TokenType != JsonToken.String) throw new JsonSerializationException($"Unexpected token or value when parsing version. Token: {reader.TokenType}, Value: {reader.Value}"); try { var v = reader.Value as string; return SemVersion.Parse(v, SemVersionStyles.Strict); } catch (Exception ex) { throw new JsonSerializationException($"Error parsing SemVersion string: {reader.Value}", ex); } } public override bool CanConvert(Type objectType) => objectType == typeof(SemVersion); } }
agpl-3.0
C#
dd1a1150f8aa58b2edca8cef18b8b3f7d96f2446
Make VersionDescriptor immutable
mrahhal/MR.AspNetCore.ApiVersioning,mrahhal/MR.AspNetCore.ApiVersioning
src/MR.AspNetCore.ApiVersioning/VersionDescriptor.cs
src/MR.AspNetCore.ApiVersioning/VersionDescriptor.cs
using System; using System.Collections.Generic; namespace MR.AspNetCore.ApiVersioning { public struct VersionDescriptor : IComparable<VersionDescriptor> { private static VersionDescriptor _invalid = new VersionDescriptor(-1, -1); private static _Comparer _comparer = new _Comparer(); private int _major; private int _minor; public VersionDescriptor(int major, int minor) { _major = major; _minor = minor; } public int Major => _major; public int Minor => _minor; public static VersionDescriptor Parse(string version) { if (string.IsNullOrWhiteSpace(version)) return _invalid; var v = new VersionDescriptor(); var split = version.Split('.'); if (split.Length != 2) { return _invalid; } if (!int.TryParse(split[0], out v._major)) { return _invalid; } if (!int.TryParse(split[1], out v._minor)) { return _invalid; } return v; } public static IComparer<VersionDescriptor> Comparer => _comparer; public override bool Equals(object obj) => this == (VersionDescriptor)obj; public override int GetHashCode() => base.GetHashCode(); public static bool operator ==(VersionDescriptor v1, VersionDescriptor v2) => v1.Major == v2.Major && v1.Minor == v2.Minor; public static bool operator !=(VersionDescriptor v1, VersionDescriptor v2) => !(v1 == v2); public static bool operator >(VersionDescriptor v1, VersionDescriptor v2) { if (v1.Major > v2.Major) return true; if (v1.Major == v2.Major && v1.Minor > v2.Minor) return true; return false; } public static bool operator <(VersionDescriptor v1, VersionDescriptor v2) { if (v1.Major < v2.Major) return true; if (v1.Major == v2.Major && v1.Minor < v2.Minor) return true; return false; } public static bool IsInvalid(VersionDescriptor v) => v == _invalid; public override string ToString() => $"{Major}.{Minor}"; public int CompareTo(VersionDescriptor other) { if (this == other) return 0; if (this > other) return 1; return -1; } private class _Comparer : IComparer<VersionDescriptor> { public int Compare(VersionDescriptor x, VersionDescriptor y) { if (x == y) return 0; if (x > y) return 1; return -1; } } } }
using System; using System.Collections.Generic; namespace MR.AspNetCore.ApiVersioning { public struct VersionDescriptor : IComparable<VersionDescriptor> { private static VersionDescriptor _invalid = new VersionDescriptor(-1, -1); private static _Comparer _comparer = new _Comparer(); public int Major; public int Minor; public VersionDescriptor(int major, int minor) { Major = major; Minor = minor; } public static VersionDescriptor Parse(string version) { if (string.IsNullOrWhiteSpace(version)) return _invalid; var v = new VersionDescriptor(); var split = version.Split('.'); if (split.Length != 2) { return _invalid; } if (!int.TryParse(split[0], out v.Major)) { return _invalid; } if (!int.TryParse(split[1], out v.Minor)) { return _invalid; } return v; } public static IComparer<VersionDescriptor> Comparer => _comparer; public override bool Equals(object obj) => this == (VersionDescriptor)obj; public override int GetHashCode() => base.GetHashCode(); public static bool operator ==(VersionDescriptor v1, VersionDescriptor v2) => v1.Major == v2.Major && v1.Minor == v2.Minor; public static bool operator !=(VersionDescriptor v1, VersionDescriptor v2) => !(v1 == v2); public static bool operator >(VersionDescriptor v1, VersionDescriptor v2) { if (v1.Major > v2.Major) return true; if (v1.Major == v2.Major && v1.Minor > v2.Minor) return true; return false; } public static bool operator <(VersionDescriptor v1, VersionDescriptor v2) { if (v1.Major < v2.Major) return true; if (v1.Major == v2.Major && v1.Minor < v2.Minor) return true; return false; } public static bool IsInvalid(VersionDescriptor v) => v == _invalid; public override string ToString() => $"{Major}.{Minor}"; public int CompareTo(VersionDescriptor other) { if (this == other) return 0; if (this > other) return 1; return -1; } private class _Comparer : IComparer<VersionDescriptor> { public int Compare(VersionDescriptor x, VersionDescriptor y) { if (x == y) return 0; if (x > y) return 1; return -1; } } } }
mit
C#
96620f209c8e8132e2b6826e0c1d71080cb325b4
Increment version number to 1.3.5.0
rhythmagency/formulate,rhythmagency/formulate,rhythmagency/formulate
src/formulate.meta/Constants.cs
src/formulate.meta/Constants.cs
namespace formulate.meta { /// <summary> /// Constants relating to Formulate itself (i.e., does not /// include constants used by Formulate). /// </summary> public class Constants { /// <summary> /// This is the version of Formulate. It is used on /// assemblies and during the creation of the /// installer package. /// </summary> /// <remarks> /// Do not reformat this code. A grunt task reads this /// version number with a regular expression. /// </remarks> public const string Version = "1.3.5.0"; /// <summary> /// The name of the Formulate package. /// </summary> public const string PackageName = "Formulate"; /// <summary> /// The name of the Formulate package, in camel case. /// </summary> public const string PackageNameCamelCase = "formulate"; } }
namespace formulate.meta { /// <summary> /// Constants relating to Formulate itself (i.e., does not /// include constants used by Formulate). /// </summary> public class Constants { /// <summary> /// This is the version of Formulate. It is used on /// assemblies and during the creation of the /// installer package. /// </summary> /// <remarks> /// Do not reformat this code. A grunt task reads this /// version number with a regular expression. /// </remarks> public const string Version = "1.3.4.0"; /// <summary> /// The name of the Formulate package. /// </summary> public const string PackageName = "Formulate"; /// <summary> /// The name of the Formulate package, in camel case. /// </summary> public const string PackageNameCamelCase = "formulate"; } }
mit
C#
706e041a3ae10d7d1c6101bbbf0d24671e671a89
Update SimpleArraySum.cs
michaeljwebb/Algorithm-Practice
HackerRank/SimpleArraySum.cs
HackerRank/SimpleArraySum.cs
//Given an array of integers find the sum of its elements. using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static int simpleArraySum(int n, int[] ar) { int result = 0; for(n = 0; n < ar.Length; n++){ result += ar[n]; } return result; } static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); string[] ar_temp = Console.ReadLine().Split(' '); int[] ar = Array.ConvertAll(ar_temp,Int32.Parse); int result = simpleArraySum(n, ar); Console.WriteLine(result); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static int simpleArraySum(int n, int[] ar) { int result = 0; for(n = 0; n < ar.Length; n++){ result += ar[n]; } return result; } static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); string[] ar_temp = Console.ReadLine().Split(' '); int[] ar = Array.ConvertAll(ar_temp,Int32.Parse); int result = simpleArraySum(n, ar); Console.WriteLine(result); } }
mit
C#
60274b71d6019941c00883377b6cd9d453e3907c
Fix status bar overlapping text on iOS 7
robinlaide/monotouch-samples,YOTOV-LIMITED/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,nervevau2/monotouch-samples,markradacz/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,sakthivelnagarajan/monotouch-samples,markradacz/monotouch-samples,a9upam/monotouch-samples,haithemaraissia/monotouch-samples,a9upam/monotouch-samples,hongnguyenpro/monotouch-samples,albertoms/monotouch-samples,haithemaraissia/monotouch-samples,davidrynn/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples,davidrynn/monotouch-samples,YOTOV-LIMITED/monotouch-samples,kingyond/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,albertoms/monotouch-samples,iFreedive/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,hongnguyenpro/monotouch-samples,robinlaide/monotouch-samples,albertoms/monotouch-samples,nelzomal/monotouch-samples,labdogg1003/monotouch-samples,xamarin/monotouch-samples,YOTOV-LIMITED/monotouch-samples,davidrynn/monotouch-samples,nelzomal/monotouch-samples,robinlaide/monotouch-samples,robinlaide/monotouch-samples,iFreedive/monotouch-samples,hongnguyenpro/monotouch-samples,peteryule/monotouch-samples,kingyond/monotouch-samples,andypaul/monotouch-samples,W3SS/monotouch-samples,kingyond/monotouch-samples,W3SS/monotouch-samples,peteryule/monotouch-samples,sakthivelnagarajan/monotouch-samples,YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,davidrynn/monotouch-samples,xamarin/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,xamarin/monotouch-samples,nervevau2/monotouch-samples,nelzomal/monotouch-samples,andypaul/monotouch-samples,sakthivelnagarajan/monotouch-samples,peteryule/monotouch-samples,haithemaraissia/monotouch-samples,markradacz/monotouch-samples
ImageProtocol/AppDelegate.cs
ImageProtocol/AppDelegate.cs
// // AppDelegate.cs // // Author: // Rolf Bjarne Kvinge (rolf@xamarin.com) // // Copyright 2012, Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace ImageProtocol { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { UIWindow window; UIWebView web; UIViewController controller; public override bool FinishedLaunching (UIApplication application, NSDictionary options) { // Register our custom url protocol NSUrlProtocol.RegisterClass (new MonoTouch.ObjCRuntime.Class (typeof (ImageProtocol))); controller = new UIViewController (); web = new UIWebView () { BackgroundColor = UIColor.White, ScalesPageToFit = true, AutoresizingMask = UIViewAutoresizing.All }; if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) web.Frame = new RectangleF (0, 20, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height - 20); else web.Frame = UIScreen.MainScreen.Bounds; controller.NavigationItem.Title = "Test case"; controller.View.AutosizesSubviews = true; controller.View.AddSubview (web); web.LoadRequest (NSUrlRequest.FromUrl (NSUrl.FromFilename (NSBundle.MainBundle.PathForResource ("test", "html")))); window = new UIWindow (UIScreen.MainScreen.Bounds); window.BackgroundColor = UIColor.White; window.MakeKeyAndVisible (); window.RootViewController = controller; return true; } } }
// // AppDelegate.cs // // Author: // Rolf Bjarne Kvinge (rolf@xamarin.com) // // Copyright 2012, Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace ImageProtocol { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { UIWindow window; UIWebView web; UIViewController controller; public override bool FinishedLaunching (UIApplication application, NSDictionary options) { // Register our custom url protocol NSUrlProtocol.RegisterClass (new MonoTouch.ObjCRuntime.Class (typeof (ImageProtocol))); controller = new UIViewController (); web = new UIWebView (UIScreen.MainScreen.Bounds) { BackgroundColor = UIColor.White, ScalesPageToFit = true, AutoresizingMask = UIViewAutoresizing.All }; controller.NavigationItem.Title = "Test case"; controller.View.AutosizesSubviews = true; controller.View.AddSubview (web); web.LoadRequest (NSUrlRequest.FromUrl (NSUrl.FromFilename (NSBundle.MainBundle.PathForResource ("test", "html")))); window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); window.RootViewController = controller; return true; } } }
mit
C#
d8161c37014a0d4543d7ce359408f667590f5426
Update code flow sample
EternalXw/IdentityServer3,kouweizhong/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,18098924759/IdentityServer3,chicoribas/IdentityServer3,AscendXYZ/Thinktecture.IdentityServer.v3,jonathankarsh/IdentityServer3,yanjustino/IdentityServer3,tuyndv/IdentityServer3,uoko-J-Go/IdentityServer,bodell/IdentityServer3,jackswei/IdentityServer3,maz100/Thinktecture.IdentityServer.v3,feanz/Thinktecture.IdentityServer.v3,angelapper/IdentityServer3,paulofoliveira/IdentityServer3,iamkoch/IdentityServer3,buddhike/IdentityServer3,AscendXYZ/Thinktecture.IdentityServer.v3,feanz/Thinktecture.IdentityServer.v3,kouweizhong/IdentityServer3,delloncba/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,charoco/IdentityServer3,olohmann/IdentityServer3,paulofoliveira/IdentityServer3,ryanvgates/IdentityServer3,tbitowner/IdentityServer3,olohmann/IdentityServer3,bestwpw/IdentityServer3,buddhike/IdentityServer3,Agrando/IdentityServer3,remunda/IdentityServer3,delRyan/IdentityServer3,roflkins/IdentityServer3,IdentityServer/IdentityServer3,delloncba/IdentityServer3,Agrando/IdentityServer3,faithword/IdentityServer3,jonathankarsh/IdentityServer3,charoco/IdentityServer3,uoko-J-Go/IdentityServer,jackswei/IdentityServer3,maz100/Thinktecture.IdentityServer.v3,SonOfSam/IdentityServer3,18098924759/IdentityServer3,ascoro/Thinktecture.IdentityServer.v3.Fork,jackswei/IdentityServer3,chicoribas/IdentityServer3,buddhike/IdentityServer3,olohmann/IdentityServer3,openbizgit/IdentityServer3,tuyndv/IdentityServer3,iamkoch/IdentityServer3,EternalXw/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,wondertrap/IdentityServer3,tbitowner/IdentityServer3,yanjustino/IdentityServer3,wondertrap/IdentityServer3,18098924759/IdentityServer3,paulofoliveira/IdentityServer3,yanjustino/IdentityServer3,bestwpw/IdentityServer3,angelapper/IdentityServer3,openbizgit/IdentityServer3,codeice/IdentityServer3,uoko-J-Go/IdentityServer,angelapper/IdentityServer3,wondertrap/IdentityServer3,ryanvgates/IdentityServer3,ascoro/Thinktecture.IdentityServer.v3.Fork,bestwpw/IdentityServer3,Agrando/IdentityServer3,delRyan/IdentityServer3,faithword/IdentityServer3,tonyeung/IdentityServer3,mvalipour/IdentityServer3,EternalXw/IdentityServer3,tuyndv/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,mvalipour/IdentityServer3,tbitowner/IdentityServer3,bodell/IdentityServer3,roflkins/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,roflkins/IdentityServer3,chicoribas/IdentityServer3,remunda/IdentityServer3,SonOfSam/IdentityServer3,codeice/IdentityServer3,mvalipour/IdentityServer3,codeice/IdentityServer3,tonyeung/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,delRyan/IdentityServer3,IdentityServer/IdentityServer3,tonyeung/IdentityServer3,kouweizhong/IdentityServer3,delloncba/IdentityServer3,remunda/IdentityServer3,openbizgit/IdentityServer3,charoco/IdentityServer3,SonOfSam/IdentityServer3,iamkoch/IdentityServer3,IdentityServer/IdentityServer3,faithword/IdentityServer3,ryanvgates/IdentityServer3,maz100/Thinktecture.IdentityServer.v3,huoxudong125/Thinktecture.IdentityServer.v3,bodell/IdentityServer3,jonathankarsh/IdentityServer3
samples/Clients/MvcCodeFlowClientManual/Views/Callback/Token.cshtml
samples/Clients/MvcCodeFlowClientManual/Views/Callback/Token.cshtml
@model Thinktecture.IdentityModel.Client.TokenResponse @{ ViewBag.Title = "Token response"; } <h2>Token response</h2> <br /> <p> <strong>Token response:</strong> <br /> <pre>@Model.Json.ToString()</pre> </p> <p> <strong>Identity token:</strong> <pre>@ViewBag.IdentityTokenParsed</pre> </p> <p> <strong>Access token:</strong> <pre>@ViewBag.AccessTokenParsed</pre> </p> <p> <strong>Token type:</strong> <br /> @Model.TokenType </p> <p> <strong>Expires:</strong> <br /> @(DateTime.Now.AddSeconds(Model.ExpiresIn).ToString()) </p> <p> <strong>Refresh token:</strong> <br /> @Model.RefreshToken </p> @using (Html.BeginForm("CallService", "Callback")) { @Html.Hidden("token", @Model.AccessToken) <input type="submit" value="Call service" /> } <br /> @using (Html.BeginForm("RenewToken", "Callback")) { <input type="hidden" name="refreshToken" value="@Model.RefreshToken" /> <input type="submit" value="Renew Token" /> }
@model Thinktecture.IdentityModel.Client.TokenResponse @{ ViewBag.Title = "Token response"; } <h2>Token response</h2> <br /> <p> <strong>Identity token:</strong> <br /> <pre>@Model.IdentityToken</pre> </p> <p> <pre>@ViewBag.IdentityTokenParsed</pre> </p> <p> <strong>Access token:</strong> <br /> <pre>@Model.AccessToken</pre> </p> <p> <pre>@ViewBag.AccessTokenParsed</pre> </p> <p> <strong>Token type:</strong> <br /> @Model.TokenType </p> <p> <strong>Expires:</strong> <br /> @(DateTime.Now.AddSeconds(Model.ExpiresIn).ToString()) </p> <p> <strong>Refresh token:</strong> <br /> @Model.RefreshToken </p> @using (Html.BeginForm("CallService", "Callback")) { @Html.Hidden("token", @Model.AccessToken) <input type="submit" value="Call service" /> } <br /> @using (Html.BeginForm("RenewToken", "Callback")) { <input type="hidden" name="refreshToken" value="@Model.RefreshToken" /> <input type="submit" value="Renew Token" /> }
apache-2.0
C#
f7502c18a3be71fc21dac7662b67bc308f3a6ac0
Update version
DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; using System.Resources; // WARNING this file is shared accross multiple projects [assembly: AssemblyProduct("ASP.NET AJAX Control Toolkit")] [assembly: AssemblyCopyright("Copyright © CodePlex Foundation 2012-2016")] [assembly: AssemblyCompany("CodePlex Foundation")] [assembly: AssemblyVersion("17.0.0.0")] [assembly: AssemblyFileVersion("17.0.0.0")] [assembly: NeutralResourcesLanguage("en-US")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
using System.Reflection; using System.Resources; // WARNING this file is shared accross multiple projects [assembly: AssemblyProduct("ASP.NET AJAX Control Toolkit")] [assembly: AssemblyCopyright("Copyright © CodePlex Foundation 2012-2016")] [assembly: AssemblyCompany("CodePlex Foundation")] [assembly: AssemblyVersion("16.1.2.0")] [assembly: AssemblyFileVersion("16.1.2.0")] [assembly: NeutralResourcesLanguage("en-US")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
bsd-3-clause
C#
fbcccd6894e833af2695508bdb0cbfcb07938abf
Handle unrecognized properties from Mongo (LF-48)
sillsdev/LfMerge,ermshiperete/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge
src/LfMerge.Core/LanguageForge/Model/LfFieldBase.cs
src/LfMerge.Core/LanguageForge/Model/LfFieldBase.cs
// Copyright (c) 2016 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using LfMerge.Core.Logging; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace LfMerge.Core.LanguageForge.Model { public class LfFieldBase: ISupportInitialize { // Used in subclasses to help reduce size of MongoDB JSON serializations protected bool _ShouldSerializeLfMultiText(LfMultiText value) { return value != null && !value.IsEmpty && value.Values.AsEnumerable().All(field => field != null && !field.IsEmpty); } protected bool _ShouldSerializeLfStringArrayField(LfStringArrayField value) { return value != null && !value.IsEmpty && value.Values.TrueForAll(s => !string.IsNullOrEmpty(s)); } protected bool _ShouldSerializeLfStringField(LfStringField value) { return value != null && !value.IsEmpty; } protected bool _ShouldSerializeList(IEnumerable<object> value) { return value != null && value.GetEnumerator().MoveNext() != false; } protected bool _ShouldSerializeBsonDocument(BsonDocument value) { return value != null && value.ElementCount > 0; } // Will receive all additional fields from Mongo that we don't know about [BsonExtraElements] public IDictionary<string, object> ExtraElements { get; set; } void ISupportInitialize.BeginInit() { // nothing to do at beginning } void ISupportInitialize.EndInit() { if (ExtraElements == null || ExtraElements.Count <= 0) return; var bldr = new StringBuilder(); bldr.AppendFormat("Read {0} unknown elements from Mongo for type {1}: ", ExtraElements.Count, GetType().Name); bldr.Append(string.Join(", ", ExtraElements.Keys)); MainClass.Logger.Log(LogSeverity.Warning, bldr.ToString()); } } }
// Copyright (c) 2016 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using MongoDB.Bson; using System.Collections.Generic; using System.Linq; namespace LfMerge.Core.LanguageForge.Model { public class LfFieldBase { // Used in subclasses to help reduce size of MongoDB JSON serializations protected bool _ShouldSerializeLfMultiText(LfMultiText value) { return value != null && !value.IsEmpty && value.Values.AsEnumerable().All(field => field != null && !field.IsEmpty); } protected bool _ShouldSerializeLfStringArrayField(LfStringArrayField value) { return value != null && !value.IsEmpty && value.Values.TrueForAll(s => !string.IsNullOrEmpty(s)); } protected bool _ShouldSerializeLfStringField(LfStringField value) { return value != null && !value.IsEmpty; } protected bool _ShouldSerializeList(IEnumerable<object> value) { return value != null && value.GetEnumerator().MoveNext() != false; } protected bool _ShouldSerializeBsonDocument(BsonDocument value) { return value != null && value.ElementCount > 0; } } }
mit
C#
642510422da980aead806a21e1c05d8c38cf9b2e
add missing model: NpmConnectorPackage
lvermeulen/ProGet.Net
src/ProGet.Net/Native/Models/NpmConnectorPackage.cs
src/ProGet.Net/Native/Models/NpmConnectorPackage.cs
using System; // ReSharper disable InconsistentNaming namespace ProGet.Net.Native.Models { public class NpmConnectorPackage { public int Connector_Id { get; set; } public string Package_Name { get; set; } public string Package_Version { get; set; } public DateTime Modified_Date { get; set; } public byte[] PackageJson_Bytes { get; set; } } }
namespace ProGet.Net.Native.Models { public class NpmConnectorPackage { } }
mit
C#
0cf27bd14bd5f0e8362af277d94d3dc812cb1762
Refactor QueueManager to remove code duplication
lindydonna/ContosoMoments,lindydonna/ContosoMoments,lindydonna/ContosoMoments,lindydonna/ContosoMoments,azure-appservice-samples/ContosoMoments,azure-appservice-samples/ContosoMoments,azure-appservice-samples/ContosoMoments,azure-appservice-samples/ContosoMoments,azure-appservice-samples/ContosoMoments,lindydonna/ContosoMoments
src/Cloud/ContosoMoments.Common/Queue/QueueManager.cs
src/Cloud/ContosoMoments.Common/Queue/QueueManager.cs
using ContosoMoments.Common.Models; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Newtonsoft.Json; using System; using System.Diagnostics; using System.Threading.Tasks; namespace ContosoMoments.Common { public class QueueManager { private static string StorageConnectionString() { return $"DefaultEndpointsProtocol=https;AccountName={AppSettings.StorageAccountName};AccountKey={AppSettings.StorageAccountKey}"; } public async Task PushToResizeQueue(BlobInformation blobInfo) { await PushToQueue(AppSettings.ResizeQueueName, JsonConvert.SerializeObject(blobInfo)); } public async Task PushToDeleteQueue(BlobInformation blobInfo) { await PushToQueue(AppSettings.DeleteQueueName, JsonConvert.SerializeObject(blobInfo)); } private async Task PushToQueue(string queueName, string data) { try { CloudStorageAccount account; if (CloudStorageAccount.TryParse(StorageConnectionString(), out account)) { CloudQueueClient queueClient = account.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference(queueName); queue.CreateIfNotExists(); var queueMessage = new CloudQueueMessage(data); await queue.AddMessageAsync(queueMessage); } } catch (Exception ex) { Trace.TraceError("Exception in QueueManager.PushToQueue => " + ex.Message); } } } }
using ContosoMoments.Common.Models; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using Newtonsoft.Json; using System; using System.Diagnostics; using System.Threading.Tasks; namespace ContosoMoments.Common { public class QueueManager { private static string StorageConnectionString() { return $"DefaultEndpointsProtocol=https;AccountName={AppSettings.StorageAccountName};AccountKey={AppSettings.StorageAccountKey}"; } public async Task PushToResizeQueue(BlobInformation blobInformation) { try { CloudStorageAccount account; if (CloudStorageAccount.TryParse(StorageConnectionString(), out account)) { CloudQueueClient queueClient = account.CreateCloudQueueClient(); CloudQueue resizeRequestQueue = queueClient.GetQueueReference(AppSettings.ResizeQueueName); resizeRequestQueue.CreateIfNotExists(); var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInformation)); await resizeRequestQueue.AddMessageAsync(queueMessage); } } catch (Exception ex) { Trace.TraceError("Exception in QueueManager.PushToQueue => " + ex.Message); } } public async Task PushToDeleteQueue(BlobInformation blobInformation) { try { CloudStorageAccount account; if (CloudStorageAccount.TryParse(StorageConnectionString(), out account)) { CloudQueueClient queueClient = account.CreateCloudQueueClient(); CloudQueue deleteRequestQueue = queueClient.GetQueueReference(AppSettings.DeleteQueueName); deleteRequestQueue.CreateIfNotExists(); var queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(blobInformation)); await deleteRequestQueue.AddMessageAsync(queueMessage); } } catch (Exception ex) { Trace.TraceError("Exception in QueueManager.PushToQueue => " + ex.Message); } } } }
mit
C#
7284fe89e30c3a4a76b4136594352bd0c56d63bf
Add debug logs
SnpM/DarkRiftNetworkHelper
DarkRiftNetworkHelper.cs
DarkRiftNetworkHelper.cs
using UnityEngine; using System.Collections; using DarkRift; using Lockstep.NetworkHelpers.DarkRift; namespace Lockstep.NetworkHelpers { public class DarkRiftNetworkHelper : NetworkHelper { DarkRiftConnection Connection = new DarkRiftConnection (); void Start() { Connection.onData += HandleData; } int port = 4296; void HandleData (byte tag, ushort subject, object data) { byte [] byteData = data as byte []; if (byteData != null) { Debug.Log ("com source: " + byteData.PrintAll ()); base.Receive ((MessageType)tag, byteData); } } public override void Connect (string ip) { Connection.Connect (ip); } public override void Disconnect () { if (this._isServer) { this._isServer = false; } else { Connection.Disconnect (); } } bool first = true; void Update () { Connection.Receive (); } public override void Simulate () { if (this.IsConnected) { if (first) { first = false; } } } public override int ID { get { return (int)Connection.id; } } public override void Host (int roomSize) { this._isServer = true; } public override bool IsConnected { get { return this.IsServer || Connection.isConnected; } } private bool _isServer; public override bool IsServer { get { return _isServer; } } public override int PlayerCount { get { return 0; } } protected override void OnSendMessageToServer (MessageType messageType, byte [] data) { Connection.SendMessageToServer ((byte)messageType, 0, data); } protected override void OnSendMessageToAll (MessageType messageType, byte [] data) { } } }
using UnityEngine; using System.Collections; using DarkRift; using Lockstep.NetworkHelpers.DarkRift; namespace Lockstep.NetworkHelpers { public class DarkRiftNetworkHelper : NetworkHelper { DarkRiftConnection Connection = new DarkRiftConnection (); void Start() { Connection.onData += HandleData; } int port = 4296; void HandleData (byte tag, ushort subject, object data) { byte [] byteData = data as byte []; if (byteData != null) { base.Receive ((MessageType)tag, byteData); } } public override void Connect (string ip) { Connection.Connect (ip); } public override void Disconnect () { if (this._isServer) { this._isServer = false; } else { Connection.Disconnect (); } } bool first = true; void Update () { Connection.Receive (); } public override void Simulate () { if (this.IsConnected) { if (first) { first = false; } } } public override int ID { get { return (int)Connection.id; } } public override void Host (int roomSize) { this._isServer = true; } public override bool IsConnected { get { return this.IsServer || Connection.isConnected; } } private bool _isServer; public override bool IsServer { get { return _isServer; } } public override int PlayerCount { get { return 0; } } protected override void OnSendMessageToServer (MessageType messageType, byte [] data) { Connection.SendMessageToServer ((byte)messageType, 0, data); } protected override void OnSendMessageToAll (MessageType messageType, byte [] data) { } } }
mit
C#
9b4efd73d2f4b5d41cd373869bbdb6d76adfed7b
Add additional options from Dokany v1.3.0.1000
dokan-dev/dokan-dotnet,dokan-dev/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,dokan-dev/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,TrabacchinLuigi/dokan-dotnet
DokanNet/DokanOptions.cs
DokanNet/DokanOptions.cs
using System; using DokanNet.Native; namespace DokanNet { /// <summary> /// Dokan mount options used to describe dokan device behavior. /// </summary> /// \if PRIVATE /// <seealso cref="DOKAN_OPTIONS.Options"/> /// \endif [Flags] public enum DokanOptions : long { /// <summary>Fixed Drive.</summary> FixedDrive = 0, /// <summary>Enable output debug message.</summary> DebugMode = 1, /// <summary>Enable output debug message to stderr.</summary> StderrOutput = 2, /// <summary>Use alternate stream.</summary> AltStream = 4, /// <summary>Enable mount drive as write-protected.</summary> WriteProtection = 8, /// <summary>Use network drive - Dokan network provider need to be installed.</summary> NetworkDrive = 16, /// <summary>Use removable drive.</summary> RemovableDrive = 32, /// <summary>Use mount manager.</summary> MountManager = 64, /// <summary>Mount the drive on current session only.</summary> CurrentSession = 128, /// <summary>Enable Lockfile/Unlockfile operations.</summary> UserModeLock = 256, /// <summary> /// Whether DokanNotifyXXX functions should be enabled, which requires this /// library to maintain a special handle while the file system is mounted. /// Without this flag, the functions always return FALSE if invoked. /// </summary> EnableNotificationAPI = 512, /// <summary>Whether to disable any oplock support on the volume.</summary> /// <remarks>Regular range locks are enabled regardless.</remarks> DisableOplocks = 1024, /// <summary> /// Whether Dokan should satisfy a single-entry, name-only directory search /// without dispatching to <see cref="IDokanOperations.FindFiles(string, out System.Collections.Generic.IList{FileInformation}, IDokanFileInfo)"/>, /// if there is already an open file from which the driver can just copy the /// normalized name. These searches are frequently done inside of CreateFile /// calls on Windows 7. /// </summary> OptimizeSingleNameSearch = 2048, } }
using System; using DokanNet.Native; namespace DokanNet { /// <summary> /// Dokan mount options used to describe dokan device behavior. /// </summary> /// \if PRIVATE /// <seealso cref="DOKAN_OPTIONS.Options"/> /// \endif [Flags] public enum DokanOptions : long { /// <summary>Fixed Drive.</summary> FixedDrive = 0, /// <summary>Enable output debug message.</summary> DebugMode = 1, /// <summary>Enable output debug message to stderr.</summary> StderrOutput = 2, /// <summary>Use alternate stream.</summary> AltStream = 4, /// <summary>Enable mount drive as write-protected.</summary> WriteProtection = 8, /// <summary>Use network drive - Dokan network provider need to be installed.</summary> NetworkDrive = 16, /// <summary>Use removable drive.</summary> RemovableDrive = 32, /// <summary>Use mount manager.</summary> MountManager = 64, /// <summary>Mount the drive on current session only.</summary> CurrentSession = 128, /// <summary>Enable Lockfile/Unlockfile operations.</summary> UserModeLock = 256, /// <summary> /// Whether DokanNotifyXXX functions should be enabled, which requires this /// library to maintain a special handle while the file system is mounted. /// Without this flag, the functions always return FALSE if invoked. /// </summary> EnableNotificationAPI = 512, } }
mit
C#
37efd6c4c6cc30bb7ea2c13f27f89bddd57cd4d7
Add comments to RedisLockEndPoint
samcook/RedLock.net
RedLock/RedisLockEndPoint.cs
RedLock/RedisLockEndPoint.cs
using System.Net; namespace RedLock { public class RedisLockEndPoint { /// <summary> /// The endpoint for the redis connection. /// </summary> public EndPoint EndPoint { get; set; } /// <summary> /// Whether to use SSL for the redis connection. /// </summary> public bool Ssl { get; set; } /// <summary> /// The password for the redis connection. /// </summary> public string Password { get; set; } /// <summary> /// The connection timeout for the redis connection. /// Defaults to 100ms if not specified. /// </summary> public int? ConnectionTimeout { get; set; } /// <summary> /// The database to use with this redis connection. /// Defaults to 0 if not specified. /// </summary> public int? RedisDatabase { get; set; } /// <summary> /// The string format for keys created in redis, must include {0}. /// Defaults to "redlock-{0}" if not specified. /// </summary> public string RedisKeyFormat { get; set; } } }
using System.Net; namespace RedLock { public class RedisLockEndPoint { public EndPoint EndPoint { get; set; } public bool Ssl { get; set; } public string Password { get; set; } public int? ConnectionTimeout { get; set; } public int? RedisDatabase { get; set; } public string RedisKeyFormat { get; set; } } }
mit
C#
ab2a343bb878074fe6f03b267ee6401f6c4a970e
switch endpoint to "https://gate.hockeyapp.net/v2/track"
dkackman/HockeySDK-Windows,bitstadium/HockeySDK-Windows,ChristopheLav/HockeySDK-Windows
Src/Core.Shared/Constants.cs
Src/Core.Shared/Constants.cs
namespace Microsoft.HockeyApp { internal class Constants { internal const string TelemetryServiceEndpoint = "https://gate.hockeyapp.net/v2/track"; internal const string TelemetryNamePrefix = "Microsoft.ApplicationInsights."; internal const string DevModeTelemetryNamePrefix = "Microsoft.ApplicationInsights.Dev."; // This is a special EventSource key for groups and cannot be changed. internal const string EventSourceGroupTraitKey = "ETW_GROUP"; internal const int MaxExceptionCountToSave = 10; } }
namespace Microsoft.HockeyApp { internal class Constants { internal const string TelemetryServiceEndpoint = "https://dc.services.visualstudio.com/v2/track"; internal const string TelemetryNamePrefix = "Microsoft.ApplicationInsights."; internal const string DevModeTelemetryNamePrefix = "Microsoft.ApplicationInsights.Dev."; // This is a special EventSource key for groups and cannot be changed. internal const string EventSourceGroupTraitKey = "ETW_GROUP"; internal const int MaxExceptionCountToSave = 10; } }
mit
C#
0f8e45074f39e2384707c4f5b13948bda14daf3a
Revert "Make all strings in loaded TdfNodes lowercase"
MHeasell/TAUtil,MHeasell/TAUtil
TAUtil/Tdf/TdfNodeAdapter.cs
TAUtil/Tdf/TdfNodeAdapter.cs
namespace TAUtil.Tdf { using System.Collections.Generic; public class TdfNodeAdapter : ITdfNodeAdapter { private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>(); public TdfNodeAdapter() { this.RootNode = new TdfNode(); this.nodeStack.Push(this.RootNode); } public TdfNode RootNode { get; private set; } public void BeginBlock(string name) { TdfNode n = new TdfNode(name); this.nodeStack.Peek().Keys[name] = n; this.nodeStack.Push(n); } public void AddProperty(string name, string value) { this.nodeStack.Peek().Entries[name] = value; } public void EndBlock() { this.nodeStack.Pop(); } } }
namespace TAUtil.Tdf { using System.Collections.Generic; public class TdfNodeAdapter : ITdfNodeAdapter { private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>(); public TdfNodeAdapter() { this.RootNode = new TdfNode(); this.nodeStack.Push(this.RootNode); } public TdfNode RootNode { get; private set; } public void BeginBlock(string name) { name = name.ToLowerInvariant(); TdfNode n = new TdfNode(name); this.nodeStack.Peek().Keys[name] = n; this.nodeStack.Push(n); } public void AddProperty(string name, string value) { name = name.ToLowerInvariant(); value = value.ToLowerInvariant(); this.nodeStack.Peek().Entries[name] = value; } public void EndBlock() { this.nodeStack.Pop(); } } }
mit
C#
f3d15c683e3b0b2c8c849adb72d6227cdc376bef
Update Hello.cs
theDrake/csharp-experiments
Hello.cs
Hello.cs
class HelloWorld { static void Main() { System.Console.WriteLine("Hello world!"); } }
class HelloWorld { static void Main() { System.Console.WriteLine("Hello world!"); } }
mit
C#
3613cb9fa245f4e963a8064256d33c52854a0629
Fix test oh my
StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop
src/BloomExe/WebLibraryIntegration/ProblemBookUploader.cs
src/BloomExe/WebLibraryIntegration/ProblemBookUploader.cs
using System; using System.Net; using Amazon.Runtime; using Amazon.S3; using L10NSharp; using SIL.Progress; namespace Bloom.WebLibraryIntegration { /// <summary> /// this differs from Book Transfer in that it knows nothing of Parse or the Bloom Library. It simply knows /// how to push a zip to an s3 bucket and give hopefully helpful error messages. /// It is used for sending us problem books /// </summary> public class ProblemBookUploader { public static string UploadBook(string bucketName, string bookZipPath, IProgress progress) { try { using(var s3Client = new BloomS3Client(bucketName)) { var url = s3Client.UploadSingleFile(bookZipPath, progress); progress.WriteMessage("Upload Success"); return url; } } catch (WebException e) { progress.WriteError("There was a problem uploading your book: "+e.Message); throw; } catch (AmazonS3Exception e) { if (e.Message.Contains("The difference between the request time and the current time is too large")) { progress.WriteError(LocalizationManager.GetString("PublishTab.Upload.TimeProblem", "There was a problem uploading your book. This is probably because your computer is set to use the wrong timezone or your system time is badly wrong. See http://www.di-mgt.com.au/wclock/help/wclo_setsysclock.html for how to fix this.")); } else { progress.WriteError("There was a problem uploading your book: " + e.Message); } throw; } catch (AmazonServiceException e) { progress.WriteError("There was a problem uploading your book: " + e.Message); throw; } catch (Exception e) { progress.WriteError("There was a problem uploading your book."); progress.WriteError(e.Message.Replace("{", "{{").Replace("}", "}}")); progress.WriteVerbose(e.StackTrace); throw; } } } }
using System; using System.Net; using Amazon.Runtime; using Amazon.S3; using L10NSharp; using SIL.Progress; namespace Bloom.WebLibraryIntegration { /// <summary> /// this differs from Book Transfer in that it knows nothing of Parse or the Bloom Library. It simply knows /// how to push a zip to an s3 bucket and give hopefully helpful error messages. /// It is used for sending us problem books /// </summary> public class ProblemBookUploader { public static string UploadBook(string bucketName, string bookZipPath, IProgress progress) { try { using(var s3Client = new BloomS3Client(bucketName)) { return s3Client.UploadSingleFile(bookZipPath, progress); } } catch (WebException e) { progress.WriteError("There was a problem uploading your book: "+e.Message); throw; } catch (AmazonS3Exception e) { if (e.Message.Contains("The difference between the request time and the current time is too large")) { progress.WriteError(LocalizationManager.GetString("PublishTab.Upload.TimeProblem", "There was a problem uploading your book. This is probably because your computer is set to use the wrong timezone or your system time is badly wrong. See http://www.di-mgt.com.au/wclock/help/wclo_setsysclock.html for how to fix this.")); } else { progress.WriteError("There was a problem uploading your book: " + e.Message); } throw; } catch (AmazonServiceException e) { progress.WriteError("There was a problem uploading your book: " + e.Message); throw; } catch (Exception e) { progress.WriteError("There was a problem uploading your book."); progress.WriteError(e.Message.Replace("{", "{{").Replace("}", "}}")); progress.WriteVerbose(e.StackTrace); throw; } progress.WriteMessage("Upload Success"); } } }
mit
C#
d2c6183d6d8a5b15aa13e2ead374eefb91cba2bf
Add edited object to `ReactiveEditCommand`
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/EditorView/ReactiveEditCommand.cs
SolidworksAddinFramework/EditorView/ReactiveEditCommand.cs
using System; using System.ComponentModel; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Windows.Input; using LanguageExt; using ReactiveUI; using SolidworksAddinFramework.Wpf; namespace SolidworksAddinFramework.EditorView { public class ReactiveEditCommand { /// <summary> /// The editable object the editor will edit /// </summary> public object Editable { get; } public Func<IEditor> CreateEditor { get; } public IObservable<bool> CanExecute { get; } public IScheduler EditorScheduler { get; } public ReactiveEditCommand( Func<IEditor> createEditor, IObservable<bool> canExecute, IScheduler editorScheduler, object editable) { Editable = editable; CreateEditor = createEditor; CanExecute = canExecute.ObserveOnDispatcher(); EditorScheduler = editorScheduler; } public static ReactiveEditCommand Create(Func<IEditor> createEditor, IScheduler schedular, object editable) { return new ReactiveEditCommand( createEditor, Observable.Return(true) ,schedular ,editable); } } public static class ReactiveEditCommandExtensions { public static IReactiveCommand RegisterWith(this ReactiveEditCommand command, ISerialCommandController serialCommandController, IScheduler schedular) { return serialCommandController.Register(command, schedular); } } public interface ISerialCommandController : INotifyPropertyChanged { IReactiveCommand Register(ReactiveEditCommand command, IScheduler wpfScheduler); Option<object> Editing { get; } } }
using System; using System.ComponentModel; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Windows.Input; using ReactiveUI; using SolidworksAddinFramework.Wpf; namespace SolidworksAddinFramework.EditorView { public class ReactiveEditCommand { public Func<IEditor> CreateEditor { get; } public IObservable<bool> CanExecute { get; } public IScheduler EditorScheduler { get; } public ReactiveEditCommand( Func<IEditor> createEditor, IObservable<bool> canExecute, IScheduler editorScheduler) { CreateEditor = createEditor; CanExecute = canExecute.ObserveOnDispatcher(); EditorScheduler = editorScheduler; } public static ReactiveEditCommand Create(Func<IEditor> createEditor, IScheduler schedular) { return new ReactiveEditCommand( createEditor, Observable.Return(true) ,schedular); } } public static class ReactiveEditCommandExtensions { public static IReactiveCommand RegisterWith(this ReactiveEditCommand command, ISerialCommandController serialCommandController, IScheduler schedular) { return serialCommandController.Register(command, schedular); } } public interface ISerialCommandController : INotifyPropertyChanged { IReactiveCommand Register(ReactiveEditCommand command, IScheduler wpfScheduler); bool CanEdit { get; } } }
mit
C#
acb6dbe3a85308473b7c5f3dc78f6294828157c9
Set default to true
devedse/DeveImageOptimizer
DeveImageOptimizer/FileProcessing/DeveImageOptimizerConfiguration.cs
DeveImageOptimizer/FileProcessing/DeveImageOptimizerConfiguration.cs
using DeveImageOptimizer.Helpers; using DeveImageOptimizer.ImageOptimization; using System; namespace DeveImageOptimizer.FileProcessing { public class DeveImageOptimizerConfiguration { private static char s = System.IO.Path.DirectorySeparatorChar; public string FileOptimizerPath { get; set; } = Environment.GetEnvironmentVariable("FILEOPTIMIZERPATH") ?? $"C:{s}Program Files{s}FileOptimizer{s}FileOptimizer64.exe"; public string TempDirectory { get; set; } = FolderHelperMethods.TempDirectory; public bool HideFileOptimizerWindow { get; set; } = true; public string FailedFilesDirectory { get; set; } = FolderHelperMethods.FailedFilesDirectory; public bool SaveFailedFiles { get; set; } = false; public bool ExecuteImageOptimizationParallel { get; set; } = true; public int MaxDegreeOfParallelism { get; set; } = Environment.ProcessorCount; /// <summary> /// The log level passed to FileOptimizerFull /// </summary> public int LogLevel { get; set; } = 2; /// <summary> /// This loops through all the files first to ensure we get a total filecount before starting the optimization /// </summary> public bool DetermineCountFilesBeforehand { get; set; } = false; /// <summary> /// By default this program uses the synchronisationcontext for progress reporting. However in some scenario's you want to make sure that progress reporting /// completes before the image optimization process is finished. That's when you should put this to true. /// </summary> public bool AwaitProgressReporting { get; set; } = false; /// <summary> /// This settings ensures the DeveImageOptimizer doesn't make use of FileOptimizerFull anymore. It calls the tool .exe files directly. /// </summary> public bool CallOptimizationToolsDirectlyInsteadOfThroughFileOptimizer { get; set; } = true; /// <summary> /// This setting determines if logs from internal tools will be forwarded to the console log /// (Only works when UseNewDeveImageOptimizer is enabled) /// </summary> public bool ForwardOptimizerToolLogsToConsole { get; set; } = false; /// <summary> /// Configure how strong the image compression should be. Only the levels 'Maximum' and 'Placebo' will /// </summary> public ImageOptimizationLevel ImageOptimizationLevel { get; set; } = ImageOptimizationLevel.Maximum; } }
using DeveImageOptimizer.Helpers; using DeveImageOptimizer.ImageOptimization; using System; namespace DeveImageOptimizer.FileProcessing { public class DeveImageOptimizerConfiguration { private static char s = System.IO.Path.DirectorySeparatorChar; public string FileOptimizerPath { get; set; } = Environment.GetEnvironmentVariable("FILEOPTIMIZERPATH") ?? $"C:{s}Program Files{s}FileOptimizer{s}FileOptimizer64.exe"; public string TempDirectory { get; set; } = FolderHelperMethods.TempDirectory; public bool HideFileOptimizerWindow { get; set; } = true; public string FailedFilesDirectory { get; set; } = FolderHelperMethods.FailedFilesDirectory; public bool SaveFailedFiles { get; set; } = false; public bool ExecuteImageOptimizationParallel { get; set; } = true; public int MaxDegreeOfParallelism { get; set; } = Environment.ProcessorCount; /// <summary> /// The log level passed to FileOptimizerFull /// </summary> public int LogLevel { get; set; } = 2; /// <summary> /// This loops through all the files first to ensure we get a total filecount before starting the optimization /// </summary> public bool DetermineCountFilesBeforehand { get; set; } = false; /// <summary> /// By default this program uses the synchronisationcontext for progress reporting. However in some scenario's you want to make sure that progress reporting /// completes before the image optimization process is finished. That's when you should put this to true. /// </summary> public bool AwaitProgressReporting { get; set; } = false; /// <summary> /// This settings ensures the DeveImageOptimizer doesn't make use of FileOptimizerFull anymore. It calls the tool .exe files directly. /// </summary> public bool CallOptimizationToolsDirectlyInsteadOfThroughFileOptimizer { get; set; } = false; /// <summary> /// This setting determines if logs from internal tools will be forwarded to the console log /// (Only works when UseNewDeveImageOptimizer is enabled) /// </summary> public bool ForwardOptimizerToolLogsToConsole { get; set; } = false; /// <summary> /// Configure how strong the image compression should be. Only the levels 'Maximum' and 'Placebo' will /// </summary> public ImageOptimizationLevel ImageOptimizationLevel { get; set; } = ImageOptimizationLevel.Maximum; } }
mit
C#
8f3937341b3f0027a8154ee882997b977b9bbfdb
Update 2darray tests
mcneel/compat,mcneel/compat,mcneel/compat,mcneel/compat,mcneel/compat
test/integration/projects/rdktest/2darray_test/MyClass.cs
test/integration/projects/rdktest/2darray_test/MyClass.cs
using System; using Rhino.Geometry; namespace darray_test { public class MyClass { public MyClass() { // old md array test var arr1d = new Point3d[1]; arr1d[0] = Point3d.Origin; var pt1 = arr1d[0]; var arr2d = new Point3d[1, 1]; arr2d[0, 0] = Point3d.Origin; var pt2 = arr2d[0, 0]; var arr3d = new Point3d[,,] {}; } // new md array tests double ArrayStruct() { var arr = new Point3d[] { new Point3d(0, 0, 0), new Point3d(0, 1, 0) }; var dist = arr[0].DistanceTo(arr[1]); return dist; } double Array2dStruct() { var arr2d = new Point3d[,] { { new Point3d(0, 0, 0), new Point3d(0, 1, 0) } }; var dist2d = arr2d[0, 0].DistanceTo(arr2d[0, 1]); return dist2d; } bool ArrayRef() { var arr = new Mesh[] { Mesh.CreateFromBox(new Box(), 10, 10, 10), null }; arr[1] = Mesh.CreateFromSphere(new Sphere(), 10, 10); var m = arr[0]; return m.Scale(2); } bool Array2dRef() { var arr = new Mesh[,] { { Mesh.CreateFromBox(new Box(), 10, 10, 10), null } }; arr[0, 1] = Mesh.CreateFromSphere(new Sphere(), 10, 10); var m = arr[0, 0]; return m.Scale(2); } } }
using System; using Rhino.Geometry; namespace darray_test { public class MyClass { public MyClass() { var arr1d = new Point3d[1]; arr1d[0] = Point3d.Origin; var pt1 = arr1d[0]; var arr2d = new Point3d[1, 1]; arr2d[0, 0] = Point3d.Origin; var pt2 = arr2d[0, 0]; var arr3d = new Point3d[,,] {}; } } }
mit
C#
7af949ee7379fd97ef1c7afd19f81bb5da0f4ddf
Add private constructor to singleton class
mike-ward/tweetz-desktop
tweetz5/tweetz5/Utilities/Translate/TranslationService.cs
tweetz5/tweetz5/Utilities/Translate/TranslationService.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; namespace tweetz5.Utilities.Translate { public class TranslationService { public readonly static TranslationService Instance = new TranslationService(); public ITranslationProvider TranslationProvider { get; set; } public event EventHandler LanguageChanged; private TranslationService() { } public CultureInfo CurrentLanguage { get { return Thread.CurrentThread.CurrentUICulture; } set { if (value.Equals(Thread.CurrentThread.CurrentUICulture) == false) { Thread.CurrentThread.CurrentUICulture = value; OnLanguageChanged(); } } } private void OnLanguageChanged() { if (LanguageChanged != null) { LanguageChanged(this, EventArgs.Empty); } } public IEnumerable<CultureInfo> Languages { get { return (TranslationProvider != null) ? TranslationProvider.Languages : Enumerable.Empty<CultureInfo>(); } } public object Translate(string key) { if (TranslationProvider != null) { var translatedValue = TranslationProvider.Translate(key); if (translatedValue != null) { return translatedValue; } } return string.Format("!{0}!", key); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; namespace tweetz5.Utilities.Translate { public class TranslationService { public readonly static TranslationService Instance = new TranslationService(); public ITranslationProvider TranslationProvider { get; set; } public event EventHandler LanguageChanged; public CultureInfo CurrentLanguage { get { return Thread.CurrentThread.CurrentUICulture; } set { if (value.Equals(Thread.CurrentThread.CurrentUICulture) == false) { Thread.CurrentThread.CurrentUICulture = value; OnLanguageChanged(); } } } private void OnLanguageChanged() { if (LanguageChanged != null) { LanguageChanged(this, EventArgs.Empty); } } public IEnumerable<CultureInfo> Languages { get { return (TranslationProvider != null) ? TranslationProvider.Languages : Enumerable.Empty<CultureInfo>(); } } public object Translate(string key) { if (TranslationProvider != null) { var translatedValue = TranslationProvider.Translate(key); if (translatedValue != null) { return translatedValue; } } return string.Format("!{0}!", key); } } }
mit
C#
fb3bac68a370747344b5b28cba8fae93abe59f70
Add null checks for MethodReplacer
pardeike/Harmony
Harmony/Transpilers.cs
Harmony/Transpilers.cs
using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null) { if (from == null) throw new ArgumentException("Unexpected null argument", nameof(from)); if (to == null) throw new ArgumentException("Unexpected null argument", nameof(to)); foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = callOpcode ?? OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) { instruction.opcode = callOpcode ?? OpCodes.Call; instruction.operand = to; } yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } // more added soon } }
mit
C#
0ed063c00576d3c10d5e25b36a92f66858628362
Prepare release 4.5.3 Work Item #1913
CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork
trunk/Solutions/CslaGenFork/Properties/AssemblyInfo.cs
trunk/Solutions/CslaGenFork/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("Csla Generator Fork")] [assembly: AssemblyDescription("CSLA.NET Business Objects and Data Access Layer code generation tool.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CslaGenFork Project")] [assembly: AssemblyProduct("Csla Generator Fork")] [assembly: AssemblyCopyright("Copyright CslaGen Project 2007, 2009\r\nCopyright Tiago Freitas Leal 2009, 2015")] [assembly: AssemblyTrademark("All Rights Reserved.")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.3.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: AssemblyFileVersionAttribute("4.5.3")] [assembly: GuidAttribute("5c019c4f-d2ab-40dd-9860-70bd603b6017")] [assembly: ComVisibleAttribute(false)]
using System; using System.Reflection; using System.Runtime.InteropServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("Csla Generator Fork")] [assembly: AssemblyDescription("CSLA.NET Business Objects and Data Access Layer code generation tool.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CslaGenFork Project")] [assembly: AssemblyProduct("Csla Generator Fork")] [assembly: AssemblyCopyright("Copyright CslaGen Project 2007, 2009\r\nCopyright Tiago Freitas Leal 2009, 2014")] [assembly: AssemblyTrademark("All Rights Reserved.")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.2.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: AssemblyFileVersionAttribute("4.5.2")] [assembly: GuidAttribute("5c019c4f-d2ab-40dd-9860-70bd603b6017")] [assembly: ComVisibleAttribute(false)]
mit
C#
35927c3b0a3518f51020ed96e4a31850d031f016
Update RegisterCommandsCommand.cs
skibitsky/lizzard
Assets/lizzard/Scripts/Commands/RegisterCommandsCommand.cs
Assets/lizzard/Scripts/Commands/RegisterCommandsCommand.cs
using lizzard.Commands.MobileInput; using UnityPureMVC.Interfaces; using UnityPureMVC.Patterns; namespace lizzard.Scripts.Commands { public class RegisterCommandsCommand : SimpleCommand { public override void Execute(INotification notification) { base.Execute(notification); Facade.RegisterCommand(Notifications.DEBUG_LOG, typeof(DebugLogCommand)); #region MobileInput #if UNITY_IOS || UNITY_ANDROID // You can register any of these commands with your own inherted from them Facade.RegisterCommand(Notifications.TOUCH_BEGAN, typeof(TouchBeganMacroCommand)); Facade.RegisterCommand(Notifications.TOUCH_ENDED, typeof(TouchEndedMacroCommand)); Facade.RegisterCommand(Notifications.TOUCH_CANCELED, typeof(TouchCanceledMacroCommand)); Facade.RegisterCommand(Notifications.TOUCH_MOVED, typeof(TouchMovedMacroCommand)); Facade.RegisterCommand(Notifications.TOUCH_STATIONARY, typeof(TouchStationaryMacroCommand)); #endif #endregion } } }
using lizzard.Commands.MobileInput; using UnityPureMVC.Interfaces; using UnityPureMVC.Patterns; namespace lizzard.Scripts.Commands { public class RegisterCommandsCommand : SimpleCommand { public override void Execute(INotification notification) { base.Execute(notification); Facade.RegisterCommand(Notifications.DEBUG_LOG, typeof(DebugLogCommand)); #region MobileInput #if UNITY_IOS || UNITY_ANDROID // You can reregister any of these commands with your own inherted from them Facade.RegisterCommand(Notifications.TOUCH_BEGAN, typeof(TouchBeganMacroCommand)); Facade.RegisterCommand(Notifications.TOUCH_ENDED, typeof(TouchEndedMacroCommand)); Facade.RegisterCommand(Notifications.TOUCH_CANCELED, typeof(TouchCanceledMacroCommand)); Facade.RegisterCommand(Notifications.TOUCH_MOVED, typeof(TouchMovedMacroCommand)); Facade.RegisterCommand(Notifications.TOUCH_STATIONARY, typeof(TouchStationaryMacroCommand)); #endif #endregion } } }
mit
C#
067f530d702e2ab7e9eb64a3a3f1d05d45bd9ed4
Update ImplementingNonSequencedRanges.cs
asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Articles/ImplementingNonSequencedRanges.cs
Examples/CSharp/Articles/ImplementingNonSequencedRanges.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Articles { public class ImplementingNonSequencedRanges { public static void Main() { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a Name for non sequenced range int index = workbook.Worksheets.Names.Add("NonSequencedRange"); Name name = workbook.Worksheets.Names[index]; //Creating a non sequence range of cells name.RefersTo = "=Sheet1!$A$1:$B$3,Sheet1!$E$5:$D$6"; //Save the workbook workbook.Save(dataDir+ "Output.out.xlsx"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Articles { public class ImplementingNonSequencedRanges { public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiating a Workbook object Workbook workbook = new Workbook(); //Adding a Name for non sequenced range int index = workbook.Worksheets.Names.Add("NonSequencedRange"); Name name = workbook.Worksheets.Names[index]; //Creating a non sequence range of cells name.RefersTo = "=Sheet1!$A$1:$B$3,Sheet1!$E$5:$D$6"; //Save the workbook workbook.Save(dataDir+ "Output.out.xlsx"); } } }
mit
C#
bf8270fd7ada46e2c67a7eb33d72eccd04ca5d57
Update request.cs
balanced/balanced-csharp
scenarios/scenarios/card_credit_order/request.cs
scenarios/scenarios/card_credit_order/request.cs
using Balanced; using System.Collections.Generic; Balanced.Balanced.configure("{{ api_key }}"); Order order = Order.Fetch("{{ order_href }}"); Card card = Card.Fetch("{{ card_href }}"); Dictionary<string, object> creditPayload = new Dictionary<string, object>(); creditPayload.Add("amount", {{payload.amount}}); Credit credit = order.CreditTo(card, creditPayload);
using Balanced; using System.Collections.Generic; Balanced.Balanced.configure("{{ api_key }}"); Order order = Order.Fetch("{{ order_href }}"); Card card = Card.Fetch("{{ card_href }}"); Dictionary<string, object> debitPayload = new Dictionary<string, object>(); debitPayload.Add("amount", {{payload.amount}}); Debit debit = order.CreditTo(card, debitPayload);
mit
C#
967527d7d38cb35cde34ac7916653418a504741e
Remove noise
ceddlyburge/canoe-polo-league-organiser-backend
CanoePoloLeagueOrganiser/RubyInspiredListFunctions.cs
CanoePoloLeagueOrganiser/RubyInspiredListFunctions.cs
using System; using System.Collections.Generic; using System.Linq; namespace CanoePoloLeagueOrganiser { public static class RubyInspiredListFunctions { public static IEnumerable<IEnumerable<T>> EachCons<T>(this IEnumerable<T> enumerable, int length) { for (int i = 0; i < enumerable.Count() - length + 1; i++) yield return ListAt(enumerable, i, length); } public static IEnumerable<Tuple<T, T>> EachCons2<T>(this IReadOnlyList<T> list) { for (int i = 0; i < list.Count() - 2 + 1; i++) yield return PairAt(list, i); } static IEnumerable<T> ListAt<T>(IEnumerable<T> enumerable, int index, int length) => enumerable.Skip(index).Take(length); static Tuple<T, T> PairAt<T>(IReadOnlyList<T> list, int i) => new Tuple<T, T>(list[i], list[i + 1]); } }
using System; using System.Collections.Generic; using System.Linq; namespace CanoePoloLeagueOrganiser { public static class RubyInspiredListFunctions { public static IEnumerable<IEnumerable<T>> EachCons<T>(this IEnumerable<T> enumerable, int length) { for (int i = 0; i < enumerable.Count() - length + 1; i++) yield return ListAt(enumerable, i, length); } public static IEnumerable<Tuple<T, T>> EachCons2<T>(this IReadOnlyList<T> list) { for (int i = 0; i < list.Count() - 2 + 1; i++) yield return PairAt(list, i); } private static IEnumerable<T> ListAt<T>(IEnumerable<T> enumerable, int index, int length) => enumerable.Skip(index).Take(length); private static Tuple<T, T> PairAt<T>(IReadOnlyList<T> list, int i) => new Tuple<T, T>(list[i], list[i + 1]); } }
mit
C#
94f72d6e3df12a724911b3db03c4670e4917f660
Remove superfluous usings
terrajobst/nquery-vnext
NQueryViewer/EditorIntegration/INQuerySyntaxTreeManager.cs
NQueryViewer/EditorIntegration/INQuerySyntaxTreeManager.cs
using System; using System.Collections.Generic; using System.Linq; using NQuery.Language; namespace NQueryViewer.EditorIntegration { public interface INQuerySyntaxTreeManager { SyntaxTree SyntaxTree { get; } event EventHandler<EventArgs> SyntaxTreeChanged; } }
using System; using NQuery.Language; namespace NQueryViewer.EditorIntegration { public interface INQuerySyntaxTreeManager { SyntaxTree SyntaxTree { get; } event EventHandler<EventArgs> SyntaxTreeChanged; } }
mit
C#
f6f5cb6d8f77b655db76039e3bf72a05e899ddbe
make methods virtual
functionGHW/HelperLibrary
HelperLibrary.Core/Configurations/LocalAppSettings.cs
HelperLibrary.Core/Configurations/LocalAppSettings.cs
/* * FileName: LocalAppSettings.cs * Author: functionghw<functionghw@hotmail.com> * CreateTime: 3/4/2016 5:42:28 PM * Description: * */ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelperLibrary.Core.Configurations { /// <summary> /// simply wrapper of ConfigurationManager.AppSettings /// </summary> public class LocalAppSettings : IAppSettings { public string this[string name] => Get(name); public virtual string Get(string name) { return ConfigurationManager.AppSettings.Get(name); } public virtual void Add(string name, string value) { ConfigurationManager.AppSettings.Add(name, value); } public virtual void Set(string name, string newValue) { ConfigurationManager.AppSettings.Set(name, newValue); } public virtual void Remove(string name) { ConfigurationManager.AppSettings.Remove(name); } } }
/* * FileName: LocalAppSettings.cs * Author: functionghw<functionghw@hotmail.com> * CreateTime: 3/4/2016 5:42:28 PM * Description: * */ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelperLibrary.Core.Configurations { /// <summary> /// simply wrapper of ConfigurationManager.AppSettings /// </summary> public class LocalAppSettings : IAppSettings { public string this[string name] => Get(name); public string Get(string name) { return ConfigurationManager.AppSettings.Get(name); } public void Add(string name, string value) { ConfigurationManager.AppSettings.Add(name, value); } public void Set(string name, string newValue) { ConfigurationManager.AppSettings.Set(name, newValue); } public void Remove(string name) { ConfigurationManager.AppSettings.Remove(name); } } }
mit
C#
a2d9b991aaafd2bc87563f7bc3f9556a0695c29d
add cookie header
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Demo/NakedObjects.Rest.App.Demo/App_Start/CorsConfig.cs
Demo/NakedObjects.Rest.App.Demo/App_Start/CorsConfig.cs
using System.Web.Http; using Thinktecture.IdentityModel.Http.Cors.WebApi; public class CorsConfig { public static void RegisterCors(HttpConfiguration httpConfig) { var corsConfig = new WebApiCorsConfiguration(); // this adds the CorsMessageHandler to the HttpConfiguration’s // MessageHandlers collection corsConfig.RegisterGlobal(httpConfig); // this allow all CORS requests to the Products controller // from the http://foo.com origin. corsConfig.ForResources("RestfulObjects"). ForOrigins("http://localhost:49998", "http://localhost:8080", "http://nakedobjectstest.azurewebsites.net"). AllowAll(). AllowResponseHeaders("Warning", "Set-Cookie"). AllowCookies(); } }
using System.Web.Http; using Thinktecture.IdentityModel.Http.Cors.WebApi; public class CorsConfig { public static void RegisterCors(HttpConfiguration httpConfig) { var corsConfig = new WebApiCorsConfiguration(); // this adds the CorsMessageHandler to the HttpConfiguration’s // MessageHandlers collection corsConfig.RegisterGlobal(httpConfig); // this allow all CORS requests to the Products controller // from the http://foo.com origin. corsConfig.ForResources("RestfulObjects").ForOrigins("http://localhost:49998", "http://localhost:8080", "http://nakedobjectstest.azurewebsites.net").AllowAll().AllowResponseHeaders("Warning").AllowCookies(); } }
apache-2.0
C#
0d4f494d24138c1a086b6eb599f67677c08acf2d
Fix namespace of WebControlVersion enum.
cube-soft/Cube.Core,cube-soft/Cube.Core,cube-soft/Cube.Forms,cube-soft/Cube.Forms
Libraries/Sources/Views/Controls/WebControlVersion.cs
Libraries/Sources/Views/Controls/WebControlVersion.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, 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. // /* ------------------------------------------------------------------------- */ namespace Cube.Forms.Controls { /* --------------------------------------------------------------------- */ /// /// WebControlVersion /// /// <summary> /// Specifies the version of the WebControl rendering engine. /// </summary> /// /* --------------------------------------------------------------------- */ public enum WebControlVersion { /// <summary>IE7.</summary> IE7 = 7000, /// <summary>IE8 compatibility mode.</summary> IE8Quirks = 8000, /// <summary>IE8.</summary> IE8 = 8888, /// <summary>IE9 compatibility mode.</summary> IE9Quirks = 9000, /// <summary>IE9.</summary> IE9 = 9999, /// <summary>IE10 compatibility mode.</summary> IE10Quirks = 10000, /// <summary>IE10.</summary> IE10 = 10001, /// <summary>IE11 compatibility mode.</summary> IE11Quirks = 11000, /// <summary>IE11.</summary> IE11 = 11001, /// <summary>Latest available version.</summary> Latest = -1, } }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, 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. // /* ------------------------------------------------------------------------- */ namespace Cube.Forms { /* --------------------------------------------------------------------- */ /// /// WebControlVersion /// /// <summary> /// Specifies the version of the WebControl rendering engine. /// </summary> /// /* --------------------------------------------------------------------- */ public enum WebControlVersion { /// <summary>IE7.</summary> IE7 = 7000, /// <summary>IE8 compatibility mode.</summary> IE8Quirks = 8000, /// <summary>IE8.</summary> IE8 = 8888, /// <summary>IE9 compatibility mode.</summary> IE9Quirks = 9000, /// <summary>IE9.</summary> IE9 = 9999, /// <summary>IE10 compatibility mode.</summary> IE10Quirks = 10000, /// <summary>IE10.</summary> IE10 = 10001, /// <summary>IE11 compatibility mode.</summary> IE11Quirks = 11000, /// <summary>IE11.</summary> IE11 = 11001, /// <summary>Latest available version.</summary> Latest = -1, } }
apache-2.0
C#
32fa4053f93b9c7de18a81502fd9b1daa9cea4c8
Order methods in membership service interface by type
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
Oogstplanner.Services/Contracts/IMembershipService.cs
Oogstplanner.Services/Contracts/IMembershipService.cs
using System.Web.Security; using Oogstplanner.Models; namespace Oogstplanner.Services { public interface IMembershipService { bool ValidateUser(string userNameOrEmail, string password); MembershipUser GetMembershipUserByEmail(string email); bool TryCreateUser(string username, string password, string email, out ModelError modelError); void SetAuthCookie(string userNameOrEmail, bool createPersistentCookie); void AddUserToRole(string userName, string role); void SignOut(); void RemoveUser(string userName); } }
using System.Web.Security; using Oogstplanner.Models; namespace Oogstplanner.Services { public interface IMembershipService { bool ValidateUser(string userNameOrEmail, string password); void SetAuthCookie(string userNameOrEmail, bool createPersistentCookie); MembershipUser GetMembershipUserByEmail(string email); bool TryCreateUser(string username, string password, string email, out ModelError modelError); void AddUserToRole(string userName, string role); void SignOut(); void RemoveUser(string userName); } }
mit
C#
77b24f48bd4c9a0caabe0ded1b1cf15bce47fec6
Remove unused properties
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/NavigationStateViewModel.cs
WalletWasabi.Fluent/ViewModels/NavigationStateViewModel.cs
using ReactiveUI; using System; using WalletWasabi.Fluent.ViewModels.Dialogs; namespace WalletWasabi.Fluent.ViewModels { public enum NavigationTarget { Default = 0, Home = 1, Dialog = 2 } public class NavigationStateViewModel { public Func<IScreen>? HomeScreen { get; set; } public Func<IScreen>? DialogScreen { get; set; } public Func<IDialogHost>? DialogHost { get; set; } } }
using ReactiveUI; using System; using WalletWasabi.Fluent.ViewModels.Dialogs; namespace WalletWasabi.Fluent.ViewModels { public enum NavigationTarget { Default = 0, Home = 1, Dialog = 2 } public class NavigationStateViewModel { public Func<IScreen>? HomeScreen { get; set; } public Func<IScreen>? DialogScreen { get; set; } public Func<IDialogHost>? DialogHost { get; set; } public Func<IRoutableViewModel>? CancelView { get; set; } public Func<IRoutableViewModel>? NextView { get; set; } } }
mit
C#
ef5b28abe448b3160c407a86ef2702911fb9d4af
Remove trace log of message body
thinktecture/relayserver,jasminsehic/relayserver,jasminsehic/relayserver,thinktecture/relayserver,thinktecture/relayserver,jasminsehic/relayserver
Thinktecture.Relay.Server/Filters/NLogActionFilter.cs
Thinktecture.Relay.Server/Filters/NLogActionFilter.cs
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Controllers; using System.Web.Http.Filters; using Newtonsoft.Json; using NLog; namespace Thinktecture.Relay.Server.Filters { public class NLogActionFilter : IActionFilter { private readonly ILogger _logger; private readonly JsonSerializerSettings _jsonSettings; /// <inheritdoc /> public bool AllowMultiple => true; public NLogActionFilter(ILogger logger) { _logger = logger; _jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; } public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { if (actionContext == null) throw new ArgumentNullException(nameof(actionContext)); if (continuation == null) throw new ArgumentNullException(nameof(continuation)); var response = await continuation().ConfigureAwait(false); _logger?.Trace("[Response] {0} - {1} ({2}): {3}", actionContext.Request?.Method, response.StatusCode, (int)response.StatusCode, actionContext.Request?.RequestUri); return response; } private string SerializeArguments(Dictionary<string, object> arguments) { try { return JsonConvert.SerializeObject(arguments, _jsonSettings); } catch (Exception ex) { _logger?.Error(ex, "Error during serializing action argements."); return null; } } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Controllers; using System.Web.Http.Filters; using Newtonsoft.Json; using NLog; namespace Thinktecture.Relay.Server.Filters { public class NLogActionFilter : IActionFilter { private readonly ILogger _logger; private readonly JsonSerializerSettings _jsonSettings; /// <inheritdoc /> public bool AllowMultiple => true; public NLogActionFilter(ILogger logger) { _logger = logger; _jsonSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; } public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { if (actionContext == null) throw new ArgumentNullException(nameof(actionContext)); if (continuation == null) throw new ArgumentNullException(nameof(continuation)); // This serializes the complete request body to the log. For the time being, prevent that: // _logger?.Trace("[Request] {0}: {1}. Arguments: {2}", actionContext.Request?.Method, actionContext.Request?.RequestUri, SerializeArguments(actionContext.ActionArguments)); var response = await continuation().ConfigureAwait(false); _logger?.Trace("[Response] {0} - {1} ({2}): {3}", actionContext.Request?.Method, response.StatusCode, (int)response.StatusCode, actionContext.Request?.RequestUri); return response; } private string SerializeArguments(Dictionary<string, object> arguments) { try { return JsonConvert.SerializeObject(arguments, _jsonSettings); } catch (Exception ex) { _logger?.Error(ex, "Error during serializing action argements."); return null; } } } }
bsd-3-clause
C#
0c2c4aa107977cdfee5177dca3a51ef70f24b32d
change label and formatting
agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov
WebAPI.Dashboard/Areas/admin/Views/Home/ApiKey.cshtml
WebAPI.Dashboard/Areas/admin/Views/Home/ApiKey.cshtml
@using WebAPI.Common.Executors @using WebAPI.Dashboard.Commands.Time @model WebAPI.Common.Indexes.StatsPerApiKey.Stats <h3>@Model.Key</h3> <ul class="list-unstyled"> <li><strong>Type:</strong> @Model.Type <li><strong>Status:</strong> @Model.Status <li><strong>App Status:</strong> @Model.ApplicationStatus <li><strong>Pattern:</strong> @Model.Pattern <li><strong>Last Used:</strong> @CommandExecutor.ExecuteCommand(new CalculateTimeAgoCommand(Model.LastUsed)) <li><strong>Requests To Date:</strong> @Model.UsageCount.ToString("0,##") </ul>
@using WebAPI.Common.Executors @using WebAPI.Dashboard.Commands.Time @model WebAPI.Common.Indexes.StatsPerApiKey.Stats <h3>@Model.Key</h3> <ul class="list-unstyled"> <li><strong>Type:</strong> @Model.Type <li><strong>Status:</strong> @Model.Status <li><strong>App Status:</strong> @Model.ApplicationStatus <li><strong>Pattern:</strong> @Model.Pattern <li><strong>Last Used:</strong> @CommandExecutor.ExecuteCommand(new CalculateTimeAgoCommand(Model.LastUsed)) <li><strong>Count:</strong> @Model.UsageCount </ul>
mit
C#
b4bd92c5f81aa651cd66c36ac30f7c0c6ba6c5ac
Delete unnecessary lines.
t-miyake/OutlookOkan
OutlookAddIn/Ribbon.cs
OutlookAddIn/Ribbon.cs
using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Windows.Forms; using Office = Microsoft.Office.Core; namespace OutlookAddIn { [ComVisible(true)] public class Ribbon : Office.IRibbonExtensibility { private Office.IRibbonUI _ribbon; public Ribbon(){} #region IRibbonExtensibility のメンバー public string GetCustomUI(string ribbonId) { return GetResourceText("OutlookAddIn.Ribbon.xml"); } #endregion #region リボンのコールバック //ここでコールバック メソッドを作成します。コールバック メソッドの追加について詳しくは https://go.microsoft.com/fwlink/?LinkID=271226 をご覧ください public void Ribbon_Load(Office.IRibbonUI ribbonUi) { this._ribbon = ribbonUi; } public void ShowVersion(Office.IRibbonControl control) { MessageBox.Show(@"誤送信防止アドイン"+ Environment.NewLine + @"Version 0.2" + Environment.NewLine + @"(株)のらねこ", @"バージョン情報", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion #region ヘルパー private static string GetResourceText(string resourceName) { Assembly asm = Assembly.GetExecutingAssembly(); string[] resourceNames = asm.GetManifestResourceNames(); for (int i = 0; i < resourceNames.Length; ++i) { if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0) { using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i]))) { if (resourceReader != null) { return resourceReader.ReadToEnd(); } } } } return null; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using Office = Microsoft.Office.Core; namespace OutlookAddIn { [ComVisible(true)] public class Ribbon : Office.IRibbonExtensibility { private Office.IRibbonUI _ribbon; public Ribbon() { } #region IRibbonExtensibility のメンバー public string GetCustomUI(string ribbonId) { return GetResourceText("OutlookAddIn.Ribbon.xml"); } #endregion #region リボンのコールバック //ここでコールバック メソッドを作成します。コールバック メソッドの追加について詳しくは https://go.microsoft.com/fwlink/?LinkID=271226 をご覧ください public void Ribbon_Load(Office.IRibbonUI ribbonUi) { this._ribbon = ribbonUi; } public void ShowVersion(Office.IRibbonControl control) { MessageBox.Show(@"誤送信防止アドイン"+ Environment.NewLine + @"Version 0.2" + Environment.NewLine + @"(株)のらねこ", @"バージョン情報", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion #region ヘルパー private static string GetResourceText(string resourceName) { Assembly asm = Assembly.GetExecutingAssembly(); string[] resourceNames = asm.GetManifestResourceNames(); for (int i = 0; i < resourceNames.Length; ++i) { if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0) { using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i]))) { if (resourceReader != null) { return resourceReader.ReadToEnd(); } } } } return null; } #endregion } }
apache-2.0
C#
1f7f8ab8db51a62bd76c3c440d97111f704a1159
Add more asserts for BuildingTelemetry tests (#1678)
exercism/xcsharp,exercism/xcsharp
exercises/concept/building-telemetry/BuildingTelemetryTests.cs
exercises/concept/building-telemetry/BuildingTelemetryTests.cs
using Xunit; using Exercism.Tests; public class ParametersTests { [Fact] public void DisplayNextSponsor_for_3_sponsors() { var car = RemoteControlCar.Buy(); car.SetSponsors("Exercism", "Walker Industries", "Acme Co."); var sp1 = car.DisplaySponsor(sponsorNum: 0); var sp2 = car.DisplaySponsor(sponsorNum: 1); var sp3 = car.DisplaySponsor(sponsorNum: 2); Assert.Equal((sp1, sp2, sp3), ("Exercism", "Walker Industries", "Acme Co.")); } [Fact(Skip = "Remove this Skip property to run this test")] public void GetTelmetryData_good() { var car = RemoteControlCar.Buy(); car.Drive(); car.Drive(); int serialNum = 1; var result = car.GetTelemetryData(ref serialNum, out int batteryPercentage, out int distanceDrivenInMeters); Assert.True(result); Assert.Equal((1, 80, 4), (serialNum, batteryPercentage, distanceDrivenInMeters)); } [Fact(Skip = "Remove this Skip property to run this test")] public void GetTelmetryData_bad() { var car = RemoteControlCar.Buy(); int batteryPercentage, distanceDrivenInMeters; car.Drive(); car.Drive(); int serialNum = 4; car.GetTelemetryData(ref serialNum, out batteryPercentage, out distanceDrivenInMeters); serialNum = 1; bool result = car.GetTelemetryData(ref serialNum, out batteryPercentage, out distanceDrivenInMeters); Assert.False(result); Assert.Equal((4, -1, -1), (serialNum, batteryPercentage, distanceDrivenInMeters)); } [Fact(Skip = "Remove this Skip property to run this test")] public void GetUsagePerMeter_good() { var car = RemoteControlCar.Buy(); car.Drive(); car.Drive(); var tc = new TelemetryClient(car); Assert.Equal("usage-per-meter=5", tc.GetBatteryUsagePerMeter(serialNum: 1)); } [Fact(Skip = "Remove this Skip property to run this test")] public void GetUsagePerMeter_not_started() { var car = RemoteControlCar.Buy(); var tc = new TelemetryClient(car); Assert.Equal("no data", tc.GetBatteryUsagePerMeter(serialNum: 1)); } }
using Xunit; using Exercism.Tests; public class ParametersTests { [Fact] public void DisplayNextSponsor_for_3_sponsors() { var car = RemoteControlCar.Buy(); car.SetSponsors("Exercism", "Walker Industries", "Acme Co."); var sp1 = car.DisplaySponsor(sponsorNum: 0); var sp2 = car.DisplaySponsor(sponsorNum: 1); var sp3 = car.DisplaySponsor(sponsorNum: 2); Assert.Equal((sp1, sp2, sp3), ("Exercism", "Walker Industries", "Acme Co.")); } [Fact(Skip = "Remove this Skip property to run this test")] public void GetTelmetryData_good() { var car = RemoteControlCar.Buy(); car.Drive(); car.Drive(); int serialNum = 1; car.GetTelemetryData(ref serialNum, out int batteryPercentage, out int distanceDrivenInMeters); Assert.Equal((1, 80, 4), (serialNum, batteryPercentage, distanceDrivenInMeters)); } [Fact(Skip = "Remove this Skip property to run this test")] public void GetTelmetryData_bad() { var car = RemoteControlCar.Buy(); int batteryPercentage, distanceDrivenInMeters; car.Drive(); car.Drive(); int serialNum = 4; car.GetTelemetryData(ref serialNum, out batteryPercentage, out distanceDrivenInMeters); serialNum = 1; car.GetTelemetryData(ref serialNum, out batteryPercentage, out distanceDrivenInMeters); Assert.Equal((4, -1, -1), (serialNum, batteryPercentage, distanceDrivenInMeters)); } [Fact(Skip = "Remove this Skip property to run this test")] public void GetUsagePerMeter_good() { var car = RemoteControlCar.Buy(); car.Drive(); car.Drive(); var tc = new TelemetryClient(car); Assert.Equal("usage-per-meter=5", tc.GetBatteryUsagePerMeter(serialNum: 1)); } [Fact(Skip = "Remove this Skip property to run this test")] public void GetUsagePerMeter_not_started() { var car = RemoteControlCar.Buy(); var tc = new TelemetryClient(car); Assert.Equal("no data", tc.GetBatteryUsagePerMeter(serialNum: 1)); } }
mit
C#
5d46eceb0d5a3201d897cc95c3f04bef8a55877b
Fix a typo.
MrLeebo/unitystation,Necromunger/unitystation,MrLeebo/unitystation,MrLeebo/unitystation,Necromunger/unitystation,Lancemaker/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,Lancemaker/unitystation,MrLeebo/unitystation,fomalsd/unitystation,MrLeebo/unitystation,krille90/unitystation,MrLeebo/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,krille90/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation
Assets/Scripts/Health/HealthBehaviour.cs
Assets/Scripts/Health/HealthBehaviour.cs
using UnityEngine; using UnityEngine.Networking; public abstract class HealthBehaviour : NetworkBehaviour { public int initialHealth = 100; private void OnEnable() { if ( initialHealth <= 0 ) { Debug.LogWarningFormat("Initial health ({0}) set to zero/below zero!", initialHealth); initialHealth = 1; } Health = initialHealth; IsDead = false; } public int Health { get; private set; } public DamageType LastDamageType { get; private set; } public string LastDamagedBy { get; private set; } public bool IsDead { get; private set; } public void ApplyDamage(string damagedBy, int damage, DamageType damageType, BodyPartType bodyPartAim = BodyPartType.CHEST) { if ( damage <= 0 || IsDead ) return; var calculatedDamage = ReceiveAndCalculateDamage(damagedBy, damage, damageType, bodyPartAim); // Debug.LogFormat("{3} received {0} {4} damage from {6} aimed for {5}. Health: {1}->{2}", // calculatedDamage, Health, Health - calculatedDamage, gameObject.name, damageType, bodyPartAim, damagedBy); Health -= calculatedDamage; checkDeadStatus(); } public virtual int ReceiveAndCalculateDamage(string damagedBy, int damage, DamageType damageType, BodyPartType bodyPartAim) { LastDamageType = damageType; LastDamagedBy = damagedBy; return damage; } private void checkDeadStatus() { if ( Health > 0 || IsDead ) return; Health = 0; onDeathActions(); IsDead = true; } public abstract void onDeathActions(); }
using UnityEngine; using UnityEngine.Networking; public abstract class HealthBehaviour : NetworkBehaviour { public int initialHealth = 100; private void OnEnable() { if ( initialHealth <= 0 ) { Debug.LogWarningFormat("Initial health ({0}) set to zero/below zero!", initialHealth); initialHealth = 1; } Health = initialHealth; IsDead = false; } public int Health { get; private set; } public DamageType LastDamageType { get; private set; } public string LastDamagedBy { get; private set; } public bool IsDead { get; private set; } public void ApplyDamage(string damagedBy, int damage, DamageType damageType, BodyPartType bodyPartAim = BodyPartType.CHEST) { if ( damage <= 0 || IsDead ) return; var calculatedDamage = ReceiveAndCalculateDamage(damagedBy, damage, damageType, bodyPartAim); // Debug.LogFormat("{3} received {0} {4} damage from {6} aimed for {5}. Health: {1}->{2}", // calculatedDamage, Health, Health - calculatedDamage, gameObject.name, damageType, bodyPartAim, damagedBy); Health -= calculatedDamage; checkDedStatus(); } public virtual int ReceiveAndCalculateDamage(string damagedBy, int damage, DamageType damageType, BodyPartType bodyPartAim) { LastDamageType = damageType; LastDamagedBy = damagedBy; return damage; } private void checkDedStatus() { if ( Health > 0 || IsDead ) return; Health = 0; onDeathActions(); IsDead = true; } public abstract void onDeathActions(); }
agpl-3.0
C#
428668bb2a6732f183851ca12e2d4082c596cb93
Use a new id to fix the failing AAT
danhaller/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper
src/SevenDigital.Api.Wrapper.Integration.Tests/EndpointTests/Releases/ReleaseTracksTests.cs
src/SevenDigital.Api.Wrapper.Integration.Tests/EndpointTests/Releases/ReleaseTracksTests.cs
using System.Linq; using NUnit.Framework; using SevenDigital.Api.Schema.Pricing; using SevenDigital.Api.Schema.Releases; namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.Releases { [TestFixture] public class ReleaseTracksTests { [Test] public async void Can_hit_endpoint() { var request = Api<ReleaseTracks>.Create .ForReleaseId(1996067); var releaseTracks = await request.Please(); Assert.That(releaseTracks, Is.Not.Null); Assert.That(releaseTracks.Tracks.Count, Is.EqualTo(16)); Assert.That(releaseTracks.Tracks.First().Title, Is.EqualTo("Never Gonna Give You Up")); Assert.That(releaseTracks.Tracks.First().Price.Status, Is.EqualTo(PriceStatus.Available)); } [Test] public async void can_determine_if_a_track_is_free() { var request = Api<ReleaseTracks>.Create .ForReleaseId(394123); var releaseTracks = await request.Please(); Assert.That(releaseTracks, Is.Not.Null); Assert.That(releaseTracks.Tracks.Count, Is.EqualTo(1)); Assert.That(releaseTracks.Tracks.First().Price.Status, Is.EqualTo(PriceStatus.Free)); } [Test] public async void can_determine_if_a_track_is_available_separately() { var request = Api<ReleaseTracks>.Create .ForReleaseId(1193196); var releaseTracks = await request.Please(); Assert.That(releaseTracks, Is.Not.Null); Assert.That(releaseTracks.Tracks.Count, Is.GreaterThanOrEqualTo(1)); Assert.That(releaseTracks.Tracks.First().Price.Status, Is.EqualTo(PriceStatus.UnAvailable)); } } }
using System.Linq; using NUnit.Framework; using SevenDigital.Api.Schema.Pricing; using SevenDigital.Api.Schema.Releases; namespace SevenDigital.Api.Wrapper.Integration.Tests.EndpointTests.Releases { [TestFixture] public class ReleaseTracksTests { [Test] public async void Can_hit_endpoint() { var request = Api<ReleaseTracks>.Create .ForReleaseId(278990); var releaseTracks = await request.Please(); Assert.That(releaseTracks, Is.Not.Null); Assert.That(releaseTracks.Tracks.Count, Is.EqualTo(16)); Assert.That(releaseTracks.Tracks.First().Title, Is.EqualTo("Never Gonna Give You Up")); Assert.That(releaseTracks.Tracks.First().Price.Status, Is.EqualTo(PriceStatus.Available)); } [Test] public async void can_determine_if_a_track_is_free() { var request = Api<ReleaseTracks>.Create .ForReleaseId(394123); var releaseTracks = await request.Please(); Assert.That(releaseTracks, Is.Not.Null); Assert.That(releaseTracks.Tracks.Count, Is.EqualTo(1)); Assert.That(releaseTracks.Tracks.First().Price.Status, Is.EqualTo(PriceStatus.Free)); } [Test] public async void can_determine_if_a_track_is_available_separately() { var request = Api<ReleaseTracks>.Create .ForReleaseId(1193196); var releaseTracks = await request.Please(); Assert.That(releaseTracks, Is.Not.Null); Assert.That(releaseTracks.Tracks.Count, Is.GreaterThanOrEqualTo(1)); Assert.That(releaseTracks.Tracks.First().Price.Status, Is.EqualTo(PriceStatus.UnAvailable)); } } }
mit
C#
f3fc5f554739c9abd6df6614c645fdce779fb84e
Fix paragraph regression
EVAST9919/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework
osu.Framework/Graphics/Containers/Markdown/MarkdownParagraph.cs
osu.Framework/Graphics/Containers/Markdown/MarkdownParagraph.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Markdig.Syntax; using osu.Framework.Allocation; namespace osu.Framework.Graphics.Containers.Markdown { /// <summary> /// Visualises a paragraph. /// </summary> public class MarkdownParagraph : CompositeDrawable, IMarkdownTextFlowComponent { private readonly ParagraphBlock paragraphBlock; [Resolved] private IMarkdownTextFlowComponent parentFlowComponent { get; set; } public MarkdownParagraph(ParagraphBlock paragraphBlock, int level) { this.paragraphBlock = paragraphBlock; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; } [BackgroundDependencyLoader] private void load() { MarkdownTextFlowContainer textFlow; InternalChild = textFlow = CreateTextFlow(); textFlow.AddInlineText(paragraphBlock.Inline); } public virtual MarkdownTextFlowContainer CreateTextFlow() => parentFlowComponent.CreateTextFlow(); } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Markdig.Syntax; using osu.Framework.Allocation; namespace osu.Framework.Graphics.Containers.Markdown { /// <summary> /// Visualises a paragraph. /// </summary> public class MarkdownParagraph : CompositeDrawable, IMarkdownTextFlowComponent { private readonly ParagraphBlock paragraphBlock; [Resolved] private IMarkdownTextFlowComponent parentFlowComponent { get; set; } public MarkdownParagraph(ParagraphBlock paragraphBlock, int level) { this.paragraphBlock = paragraphBlock; } [BackgroundDependencyLoader] private void load() { MarkdownTextFlowContainer textFlow; InternalChild = textFlow = CreateTextFlow(); textFlow.AddInlineText(paragraphBlock.Inline); } public virtual MarkdownTextFlowContainer CreateTextFlow() => parentFlowComponent.CreateTextFlow(); } }
mit
C#
88d908f883ae060a173446022960924918a37bd6
check path with file name.
RichardHowells/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,EPTamminga/Dnn.Platform,robsiera/Dnn.Platform,bdukes/Dnn.Platform,nvisionative/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,mitchelsellers/Dnn.Platform,EPTamminga/Dnn.Platform,dnnsoftware/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,bdukes/Dnn.Platform,robsiera/Dnn.Platform,EPTamminga/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,RichardHowells/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,robsiera/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,nvisionative/Dnn.Platform,RichardHowells/Dnn.Platform
src/Modules/UI/Dnn.EditBar.UI/Items/PageSettingsMenu.cs
src/Modules/UI/Dnn.EditBar.UI/Items/PageSettingsMenu.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dnn.EditBar.Library; using Dnn.EditBar.Library.Items; using Dnn.EditBar.UI.Helpers; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Portals; using DotNetNuke.Security.Permissions; namespace Dnn.EditBar.UI.Items { [Serializable] public class PageSettingsMenu : BaseMenuItem { public override string Name { get; } = "PageSettings"; public override string Text { get; } = "PageSettings"; public override string Parent { get; } = Constants.LeftMenu; public override string Loader { get; } = "PageSettings"; public override int Order { get; } = 15; public override bool Visible() { return PortalSettings.Current?.UserMode == PortalSettings.Mode.Edit && Host.ControlPanel.EndsWith("PersonaBarContainer.ascx", StringComparison.InvariantCultureIgnoreCase); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dnn.EditBar.Library; using Dnn.EditBar.Library.Items; using Dnn.EditBar.UI.Helpers; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Portals; using DotNetNuke.Security.Permissions; namespace Dnn.EditBar.UI.Items { [Serializable] public class PageSettingsMenu : BaseMenuItem { public override string Name { get; } = "PageSettings"; public override string Text { get; } = "PageSettings"; public override string Parent { get; } = Constants.LeftMenu; public override string Loader { get; } = "PageSettings"; public override int Order { get; } = 15; public override bool Visible() { return PortalSettings.Current?.UserMode == PortalSettings.Mode.Edit && Host.ControlPanel == "admin/Dnn.PersonaBar/UserControls/PersonaBarContainer.ascx"; } } }
mit
C#
e92610e13e29263e35d8924be9a1da26e19f6e0c
Update docblocks
felladrin/unity3d-mvc
Scripts/Application.cs
Scripts/Application.cs
using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Application : MonoBehaviour { public ModelContainer Model; public ControllerContainer Controller; public ViewContainer View; private Dictionary<string, UnityEvent> eventDictionary = new Dictionary<string, UnityEvent>(); /// <summary> /// Add listener to a given event. /// Usage: Call it inside OnEnable() method of MonoBehaviours. /// </summary> /// <param name="eventName">Name of the event.</param> /// <param name="listener">Callback function.</param> public void AddEventListener(string eventName, UnityAction listener) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.AddListener(listener); } else { e = new UnityEvent(); e.AddListener(listener); eventDictionary.Add(eventName, e); } } /// <summary> /// Remove listener from a given event. /// Usage: Call it inside OnDisable() method of MonoBehaviours. /// </summary> /// <param name="eventName">Name of the event.</param> /// <param name="listener">Callback function.</param> public void RemoveEventListener(string eventName, UnityAction listener) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.RemoveListener(listener); } } /// <summary> /// Triggers all registered callbacks of a given event. /// </summary> public void TriggerEvent(string eventName) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.Invoke(); } } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Application : MonoBehaviour { public ModelContainer Model; public ControllerContainer Controller; public ViewContainer View; private Dictionary<string, UnityEvent> eventDictionary = new Dictionary<string, UnityEvent>(); /// <summary> /// Add listener to a given event. /// </summary> /// <param name="eventName">Name of the event.</param> /// <param name="listener">Callback function.</param> public void AddEventListener(string eventName, UnityAction listener) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.AddListener(listener); } else { e = new UnityEvent(); e.AddListener(listener); eventDictionary.Add(eventName, e); } } /// <summary> /// Remove listener from a given event. /// </summary> /// <param name="eventName">Name of the event.</param> /// <param name="listener">Callback function.</param> public void RemoveEventListener(string eventName, UnityAction listener) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.RemoveListener(listener); } } /// <summary> /// Triggers all registered callbacks of a given event. /// </summary> public void TriggerEvent(string eventName) { UnityEvent e; if (eventDictionary.TryGetValue(eventName, out e)) { e.Invoke(); } } }
mit
C#
d00ba2a7e3cc456cab19646a176ba179cbfd93bd
Update Startup.cs
bradwestness/SecretSanta,bradwestness/SecretSanta
SecretSanta/Startup.cs
SecretSanta/Startup.cs
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SecretSanta.Utilities; using System; namespace SecretSanta { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; AppSettings.Initialize(configuration); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => { o.LoginPath = AppSettings.LoginPath; o.LogoutPath = AppSettings.LogoutPath; o.ExpireTimeSpan = TimeSpan.FromMinutes(60); o.SlidingExpiration = true; }); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); }); services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { DataRepository.Initialize(env.ContentRootPath); PreviewGenerator.Initialize(env.WebRootPath); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SecretSanta.Utilities; using System; namespace SecretSanta { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; AppSettings.Initialize(configuration); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDistributedMemoryCache(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => { o.LoginPath = AppSettings.LoginPath; o.LogoutPath = AppSettings.LogoutPath; o.ExpireTimeSpan = TimeSpan.FromMinutes(60); o.SlidingExpiration = true; }); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { DataRepository.Initialize(env.ContentRootPath); PreviewGenerator.Initialize(env.WebRootPath); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
apache-2.0
C#
e7c0049298eca63cb987f1e71c46852e4d5b5080
Remove reduntant code
kalinau/ObservableDataQuerying
ObservableData/ObservableData.Structures/ListExtensions.cs
ObservableData/ObservableData.Structures/ListExtensions.cs
using System; using System.Reactive.Linq; using JetBrains.Annotations; using ObservableData.Structures.Lists.Updates; using ObservableData.Structures.Utils; namespace ObservableData.Structures { public static class ListExtensions { [NotNull] public static IObservable<IUpdate<IListOperation<T>>> AsObservable<T>( [NotNull] this IObservableReadOnlyList<T> list) => list.Updates.StartWith(new ListInsertBatchOperation<T>(list, 0)).NotNull(); } }
using System; using System.Reactive.Linq; using JetBrains.Annotations; using ObservableData.Structures.Lists.Updates; using ObservableData.Structures.Utils; namespace ObservableData.Structures { public static class ListExtensions { [NotNull] public static IObservable<IUpdate<IListOperation<T>>> AsObservable<T>( [NotNull] this IObservableReadOnlyList<T> list) => list.Updates.StartWith(new ListInsertBatchOperation<T>(list, 0)).NotNull(); public static void Do() { } } }
mit
C#
bc50248a53ca61d2cd6cfb12eb3a9e3328c16a2e
Update WeavingHelper.cs
Fody/Costura,Fody/Costura
Tests/WeavingHelper.cs
Tests/WeavingHelper.cs
using System.IO; using System.Linq; using System.Xml.Linq; using Fody; #pragma warning disable 618 static class WeavingHelper { public static TestResult CreateIsolatedAssemblyCopy(string assemblyPath, string config, string[] references, string assemblyName) { var weavingTask = new ModuleWeaver { Config = XElement.Parse(config), References = string.Join(";", references.Select(r => Path.Combine(CodeBaseLocation.CurrentDirectory, r))), ReferenceCopyLocalPaths = references.Select(r => Path.Combine(CodeBaseLocation.CurrentDirectory, r)).ToList(), }; return weavingTask.ExecuteTestRun(assemblyPath, assemblyName: assemblyName, ignoreCodes: new []{ "0x80131869" }, runPeVerify:false); } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using Fody; #pragma warning disable 618 static class WeavingHelper { public static TestResult CreateIsolatedAssemblyCopy(string assemblyPath, string config, string[] references, string assemblyName) { var weavingTask = new ModuleWeaver { Config = XElement.Parse(config), References = string.Join(";", references.Select(r => Path.Combine(CodeBaseLocation.CurrentDirectory, r))), ReferenceCopyLocalPaths = references.Select(r => Path.Combine(CodeBaseLocation.CurrentDirectory, r)).ToList(), }; return weavingTask.ExecuteTestRun(assemblyPath, assemblyName: assemblyName, ignoreCodes: new []{ "0x80131869" }, runPeVerify:false); } }
mit
C#
3fa74eaa3deebb9273bd84ea581b567d76b2d960
Add MapRoutesInController extension method.
jgoz/beeline,jgoz/beeline,jgoz/beeline
src/Beeline/RouteCollectionExtensions.cs
src/Beeline/RouteCollectionExtensions.cs
namespace Beeline { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Mvc; using System.Web.Routing; using Beeline.Routing; /// <summary> /// Extension methods for <see cref="RouteCollection"/>. /// </summary> public static class RouteCollectionExtensions { /// <summary> /// Searches the assembly containing <typeparamref name="T"/> for <see cref="RouteAttribute"/> declarations /// and maps the results in a specified route collection. /// </summary> /// <typeparam name="T">A type in the assembly that will be searched.</typeparam> /// <param name="routeCollection">The route collection.</param> /// <returns>A list of <see cref="Route"/> objects added to <paramref name="routeCollection"/>.</returns> public static IList<Route> MapRoutesInAssemblyOf<T>(this RouteCollection routeCollection) { return routeCollection.MapRoutesInAssembly(typeof(T).Assembly); } /// <summary> /// Searches an assembly for <see cref="RouteAttribute"/> declarations and maps the results in a /// specified route collection. /// </summary> /// <param name="routeCollection">The route collection.</param> /// <param name="assembly">The assembly to search.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="assembly"/> is null.</exception> /// <returns>A list of <see cref="Route"/> objects added to <paramref name="routeCollection"/>.</returns> public static IList<Route> MapRoutesInAssembly(this RouteCollection routeCollection, Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); return routeCollection.MapActionMethodsToRoutes(FindActionMethods(assembly)); } /// <summary> /// Finds action methods with <see cref="RouteAttribute"/> declarations in a specified controller type /// and maps the results in a specified route collection. /// </summary> /// <typeparam name="TController">The controller type. Must inherit from <see cref="ControllerBase"/></typeparam> /// <param name="routeCollection">The route collection.</param> /// <returns>A list of <see cref="Route"/> objects added to <paramref name="routeCollection"/>.</returns> public static IList<Route> MapRoutesInController<TController>(this RouteCollection routeCollection) where TController : ControllerBase { return routeCollection.MapActionMethodsToRoutes(typeof(TController).GetMethods().Where(m => m.HasRouteAttributes())); } private static IEnumerable<MethodInfo> FindActionMethods(Assembly assembly) { return assembly.GetTypes() .Where(t => typeof(ControllerBase).IsAssignableFrom(t)) .SelectMany(t => t.GetMethods()) .Where(m => m.HasRouteAttributes()); } private static IList<Route> MapActionMethodsToRoutes(this RouteCollection routeCollection, IEnumerable<MethodInfo> actionMethods) { return actionMethods .Select(RouteBuilder.FromActionMethod) .Select(r => routeCollection.MapRouteBuilder(r)) .ToList(); } private static Route MapRouteBuilder(this RouteCollection routeCollection, RouteBuilder routeBuilder) { Route route = routeCollection.MapRoute(routeBuilder.Name, routeBuilder.Url); route.Defaults = routeBuilder.Defaults; route.Constraints = routeBuilder.Constraints; return route; } } }
namespace Beeline { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Mvc; using System.Web.Routing; using Beeline.Routing; /// <summary> /// Extension methods for <see cref="RouteCollection"/>. /// </summary> public static class RouteCollectionExtensions { /// <summary> /// Searches the assembly containing <typeparamref name="T"/> for <see cref="RouteAttribute"/> declarations /// and maps the results in a specified route collection. /// </summary> /// <typeparam name="T">A type in the assembly that will be searched.</typeparam> /// <param name="routeCollection">The route collection.</param> /// <returns>A list of <see cref="Route"/> objects added to <paramref name="routeCollection"/>.</returns> public static IList<Route> MapRoutesInAssemblyOf<T>(this RouteCollection routeCollection) { return routeCollection.MapRoutesInAssembly(typeof(T).Assembly); } /// <summary> /// Searches an assembly for <see cref="RouteAttribute"/> declarations and maps the results in a /// specified route collection. /// </summary> /// <param name="routeCollection">The route collection.</param> /// <param name="assembly">The assembly to search.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="assembly"/> is null.</exception> /// <returns>A list of <see cref="Route"/> objects added to <paramref name="routeCollection"/>.</returns> public static IList<Route> MapRoutesInAssembly(this RouteCollection routeCollection, Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); return FindActionMethods(assembly) .Select(RouteBuilder.FromActionMethod) .Select(r => routeCollection.MapRoute(r)) .ToList(); } private static IEnumerable<MethodInfo> FindActionMethods(Assembly assembly) { return assembly.GetTypes() .Where(t => typeof(Controller).IsAssignableFrom(t)) .SelectMany(t => t.GetMethods()) .Where(m => m.HasRouteAttributes()); } private static Route MapRoute(this RouteCollection routeCollection, RouteBuilder routeBuilder) { Route route = routeCollection.MapRoute(routeBuilder.Name, routeBuilder.Url); route.Defaults = routeBuilder.Defaults; route.Constraints = routeBuilder.Constraints; return route; } } }
mit
C#
968854fc06ee350787f751a4cf32194756f674b7
Fix GetLanguageId logic
dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua
src/Core/Managers/LocalizationManager.cs
src/Core/Managers/LocalizationManager.cs
using System.Linq; using Microsoft.Extensions.Caching.Memory; namespace Core.Managers { public class LocalizationManager : ManagerBase { public LocalizationManager(string connectionString, IMemoryCache cache = null) : base(connectionString, cache) { } public int? GetLanguageId(string code) { if (string.IsNullOrWhiteSpace(code)) { return null; } code = code.Trim().ToLower(); var language = _database.Language.FirstOrDefault(o => o.Code == code); return language?.Id; } } }
using System.Linq; using Microsoft.Extensions.Caching.Memory; namespace Core.Managers { public class LocalizationManager : ManagerBase { public LocalizationManager(string connectionString, IMemoryCache cache = null) : base(connectionString, cache) { } public int? GetLanguageId(string code) { if (string.IsNullOrWhiteSpace(code)) { return null; } code = code.Trim().ToLower(); var language = _database.Language.FirstOrDefault(o => o.Name == code); return language?.Id; } } }
mit
C#
aac763c4ac20216bf2e9a145fba99559a47d00e4
Update VProperty to have methods for getting and setting the Value as different data types
BenVlodgi/VMFParser
VMFParser/VProperty.cs
VMFParser/VProperty.cs
namespace VMFParser { public class VProperty : IVNode, IDeepCloneable<VProperty> { public string Name { get; private set; } public string Value { get; set; } /// <summary>Initializes a new instance of the <see cref="VProperty"/> class from the name and value of a property.</summary> public VProperty(string name, string value) { Name = name; Value = value; } /// <summary>Initializes a new instance of the <see cref="VProperty"/> class from text.</summary> public VProperty(string text) { var texts = text.Trim().Split(new char[] { ' ', '\t' }, 2); Name = texts[0].Trim('"'); Value = texts[1].Trim('"'); } /// <summary>Generates the VMF text representation of this Property.</summary> public string ToVMFString() { return string.Format("\"{0}\" \"{1}\"", Name, Value); } /// <summary> This is used mostly for debug visualization.</summary> public override string ToString() { return base.ToString() + " (" + Name + ")"; } IVNode IDeepCloneable<IVNode>.DeepClone() => DeepClone(); public VProperty DeepClone() { return new VProperty(Name, Value); } public int GetValueAsInt(int defaultValue = 0) { return int.TryParse(Value, out int val) ? val : defaultValue; } public void SetValueAsInt(int value) { Value = value.ToString(); } public decimal GetValueAsDecimal(decimal defaultValue = 0M) { return decimal.TryParse(Value, out decimal val) ? val : defaultValue; } public void SetValueAsAxis(decimal value) { Value = value.ToString(); // TODO: investigate using next line instead //Value = value.ToString("E6", System.Globalization.CultureInfo.CreateSpecificCulture("sv-SE")); } public Axis GetValueAsAxis() { return Axis.TryParse(Value, out Axis val) ? val : val; } public void SetValueAsAxis(Axis value) { Value = value.ToVMFString(); } } }
namespace VMFParser { public class VProperty : IVNode, IDeepCloneable<VProperty> { public string Name { get; private set; } public string Value { get; set; } /// <summary>Initializes a new instance of the <see cref="VProperty"/> class from the name and value of a property.</summary> public VProperty(string name, string value) { Name = name; Value = value; } /// <summary>Initializes a new instance of the <see cref="VProperty"/> class from text.</summary> public VProperty(string text) { var texts = text.Trim().Split(new char[] { ' ', '\t' }, 2); Name = texts[0].Trim('"'); Value = texts[1].Trim('"'); } /// <summary>Generates the VMF text representation of this Property.</summary> public string ToVMFString() { return string.Format("\"{0}\" \"{1}\"", Name, Value); } public override string ToString() { return base.ToString() + " (" + Name + ")"; } IVNode IDeepCloneable<IVNode>.DeepClone() => DeepClone(); public VProperty DeepClone() { return new VProperty(Name, Value); } } }
mit
C#
235ab8e7d3c3a5537d57c6b2a4bc980c4fba5e46
fix ThrowOnFail
shinji-yoshida/UniPromise,shinji-yoshida/UniPromise
Assets/Scripts/UniPromise/Promise.cs
Assets/Scripts/UniPromise/Promise.cs
using System; namespace UniPromise { public abstract class Promise<T> : IDisposable { public abstract State State { get; } public bool IsPending { get { return this.State == State.Pending; } } public bool IsNotPending { get { return this.State != State.Pending; } } public bool IsResolved { get { return this.State == State.Resolved; } } public bool IsRejected { get { return this.State == State.Rejected; } } public bool IsDisposed { get { return this.State == State.Disposed; } } public abstract Promise<T> Done(Action<T> doneCallback); public abstract Promise<T> Fail(Action<Exception> failedCallback); public abstract Promise<T> Disposed(Action disposedCallback); public Promise<T> Finally(Action callback, bool includeDisposed=true) { Done (_ => callback ()); Fail (_ => callback ()); if(includeDisposed) Disposed (callback); return this; } public Promise<T> ThrowOnFail () { return Fail(e => {throw new Exception("thrown by ThrowOnFail", e);}); } public abstract Promise<U> Then<U>(Func<T, Promise<U>> done); public abstract Promise<U> Then<U>(Func<T, Promise<U>> done, Func<Exception, Promise<U>> fail); public abstract Promise<U> Then<U>( Func<T, Promise<U>> done, Func<Exception, Promise<U>> fail, Func<Promise<U>> disposed); [Obsolete("This function is identical to Then().")] public Promise<U> ThenWithCatch<U>(Func<T, Promise<U>> done) { return Then(t => { try{ return done(t); } catch(Exception e) { return new RejectedPromise<U>(e); } }); } public Promise<U> Select<U>(Func<T, U> selector) { return Then (t => Promises.Resolved (selector (t))); } [Obsolete("This function is identical to Select().")] public Promise<U> SelectWithCatch<U>(Func<T, U> selector) { var result = new Deferred<U>(); Done(t => { try { result.Resolve(selector(t)); } catch(Exception e) { result.Reject(e); } }); Fail(e => result.Reject(e)); Disposed(() => result.Dispose()); return result; } public Promise<T> Where(Predicate<T> condition) { return Then (t => { if(condition(t)) return Promises.Resolved(t); else return Promises.Disposed<T>(); }); } public abstract Promise<T> Clone(); public abstract void Dispose (); } }
using System; namespace UniPromise { public abstract class Promise<T> : IDisposable { public abstract State State { get; } public bool IsPending { get { return this.State == State.Pending; } } public bool IsNotPending { get { return this.State != State.Pending; } } public bool IsResolved { get { return this.State == State.Resolved; } } public bool IsRejected { get { return this.State == State.Rejected; } } public bool IsDisposed { get { return this.State == State.Disposed; } } public abstract Promise<T> Done(Action<T> doneCallback); public abstract Promise<T> Fail(Action<Exception> failedCallback); public abstract Promise<T> Disposed(Action disposedCallback); public Promise<T> Finally(Action callback, bool includeDisposed=true) { Done (_ => callback ()); Fail (_ => callback ()); if(includeDisposed) Disposed (callback); return this; } public Promise<T> ThrowOnFail () { return Fail(e => {new Exception("thrown by ThrowOnFail", e);}); } public abstract Promise<U> Then<U>(Func<T, Promise<U>> done); public abstract Promise<U> Then<U>(Func<T, Promise<U>> done, Func<Exception, Promise<U>> fail); public abstract Promise<U> Then<U>( Func<T, Promise<U>> done, Func<Exception, Promise<U>> fail, Func<Promise<U>> disposed); [Obsolete("This function is identical to Then().")] public Promise<U> ThenWithCatch<U>(Func<T, Promise<U>> done) { return Then(t => { try{ return done(t); } catch(Exception e) { return new RejectedPromise<U>(e); } }); } public Promise<U> Select<U>(Func<T, U> selector) { return Then (t => Promises.Resolved (selector (t))); } [Obsolete("This function is identical to Select().")] public Promise<U> SelectWithCatch<U>(Func<T, U> selector) { var result = new Deferred<U>(); Done(t => { try { result.Resolve(selector(t)); } catch(Exception e) { result.Reject(e); } }); Fail(e => result.Reject(e)); Disposed(() => result.Dispose()); return result; } public Promise<T> Where(Predicate<T> condition) { return Then (t => { if(condition(t)) return Promises.Resolved(t); else return Promises.Disposed<T>(); }); } public abstract Promise<T> Clone(); public abstract void Dispose (); } }
mit
C#
ea15df4a3619e91553626417fd253e51c28ea809
Add exception display test
caronyan/CSharpRecipe
CSharpRecipe/CSharpRecipe/Program.cs
CSharpRecipe/CSharpRecipe/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Recipe.ClassAndGeneric; using Recipe.DebugAndException; namespace CSharpRecipe { class Program { static void Main(string[] args) { #region Test IEnumerable<T> //IEnumerable<int> iterable = EnumeratorTest.CreateEnumerable(); //IEnumerator<int> iterator = iterable.GetEnumerator(); //Console.WriteLine("Start to iterate"); //while (true) //{ // Console.WriteLine("Calling MoveNext()..."); // bool result = iterator.MoveNext(); // Console.WriteLine($"...MoveNext result={result}"); // if (!result) // { // break; // } // Console.WriteLine("Fetching Current..."); // Console.WriteLine($"...Current result={iterator.Current}"); //} #endregion #region Test Reflection Exception ReflectException.ReflectionException(); #endregion Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Recipe.ClassAndGeneric; namespace CSharpRecipe { class Program { static void Main(string[] args) { IEnumerable<int> iterable = EnumeratorTest.CreateEnumerable(); IEnumerator<int> iterator = iterable.GetEnumerator(); Console.WriteLine("Start to iterate"); while (true) { Console.WriteLine("Calling MoveNext()..."); bool result = iterator.MoveNext(); Console.WriteLine($"...MoveNext result={result}"); if (!result) { break; } Console.WriteLine("Fetching Current..."); Console.WriteLine($"...Current result={iterator.Current}"); } Console.ReadKey(); } } }
mit
C#
6704112a51b0be3ec7a8c38f096374e06560a1d2
Update for base class
tobyclh/UnityCNTK,tobyclh/UnityCNTK
Assets/UnityCNTK/SynthesisModel.cs
Assets/UnityCNTK/SynthesisModel.cs
using System.Collections; using System.Collections.Generic; using UnityEngine.Assertions; using System.Linq; using UnityEngine; using UnityEditor; using CNTK; using System; namespace UnityCNTK { public class SynthesisModel : Model { public Texture2D textureReference; public string namingRules; public override void Evaluate(DeviceDescriptor device) { throw new NotImplementedException(); } public override void LoadModel() { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine.Assertions; using System.Linq; using UnityEngine; using UnityEditor; using CNTK; using System; namespace UnityCNTK { public class SynthesisModel : Model { public Texture2D textureReference; public string namingRules; public override void Evaluate() { throw new NotImplementedException(); } public override void LoadModel() { throw new NotImplementedException(); } } }
mit
C#
6c381cf2033d0e355fdfb66012b5d479e47a300a
Correct detection of scrape requests
dipeshc/BTDeploy
src/MonoTorrent/MonoTorrent.Tracker/Listeners/ManualListener.cs
src/MonoTorrent/MonoTorrent.Tracker/Listeners/ManualListener.cs
using System; using System.Collections.Generic; using System.Text; using MonoTorrent.BEncoding; using System.Net; namespace MonoTorrent.Tracker.Listeners { public class ManualListener : ListenerBase { private bool running; public override bool Running { get { return running; } } public override void Start() { running = true; } public override void Stop() { running = false; } public BEncodedValue Handle(string rawUrl, IPAddress remoteAddress) { if (rawUrl == null) throw new ArgumentNullException("rawUrl"); if (remoteAddress == null) throw new ArgumentOutOfRangeException("remoteAddress"); rawUrl = rawUrl.Substring(rawUrl.LastIndexOf('/')); bool isScrape = rawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase); return Handle(rawUrl, remoteAddress, isScrape); } } }
using System; using System.Collections.Generic; using System.Text; using MonoTorrent.BEncoding; using System.Net; namespace MonoTorrent.Tracker.Listeners { public class ManualListener : ListenerBase { private bool running; public override bool Running { get { return running; } } public override void Start() { running = true; } public override void Stop() { running = false; } public BEncodedValue Handle(string rawUrl, IPAddress remoteAddress) { if (rawUrl == null) throw new ArgumentNullException("rawUrl"); if (remoteAddress == null) throw new ArgumentOutOfRangeException("remoteAddress"); bool isScrape = rawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase); return Handle(rawUrl, remoteAddress, isScrape); } } }
mit
C#
b64b55eb85e552029d613f3827b7c87862d2ce31
fix test
jonnii/SpeakEasy
src/SpeakEasy.Specifications/HttpClientSettingsSpecification.cs
src/SpeakEasy.Specifications/HttpClientSettingsSpecification.cs
using Machine.Specifications; using SpeakEasy.Authenticators; using SpeakEasy.Loggers; using SpeakEasy.Serializers; namespace SpeakEasy.Specifications { public class HttpClientSettingsSpecification { [Subject(typeof(HttpClientSettings))] public class in_general { Establish context = () => settings = new HttpClientSettings(); It should_have_null_authenticator = () => settings.Authenticator.ShouldBeOfType<NullAuthenticator>(); It should_have_null_logger = () => settings.Logger.ShouldBeOfType<NullLogger>(); It should_have_default_user_agent = () => settings.UserAgent.ShouldEqual("SpeakEasy"); static HttpClientSettings settings; } [Subject(typeof(HttpClientSettings))] public class default_settings_in_general : with_default_settings { It should_default_to_json_serializer = () => settings.DefaultSerializer.ShouldBeOfType<JsonDotNetSerializer>(); It should_have_json_deserializer = () => settings.Serializers.ShouldContain(d => d is JsonDotNetSerializer); It should_have_xml_deserializer = () => settings.Serializers.ShouldContain(d => d is DotNetXmlSerializer); } [Subject(typeof(HttpClientSettings))] public class when_customizing_serializer : with_default_settings { Because of = () => settings.Configure<JsonDotNetSerializer>(s => { called = true; }); It should_call_callback = () => called.ShouldEqual(true); static bool called; } public class with_default_settings { Establish context = () => settings = HttpClientSettings.Default; protected static HttpClientSettings settings; } } }
using Machine.Specifications; using SpeakEasy.Authenticators; using SpeakEasy.Loggers; using SpeakEasy.Serializers; namespace SpeakEasy.Specifications { public class HttpClientSettingsSpecification { [Subject(typeof(HttpClientSettings))] public class in_general { Establish context = () => settings = new HttpClientSettings(); It should_have_null_authenticator = () => settings.Authenticator.ShouldBeOfType<NullAuthenticator>(); It should_have_null_logger = () => settings.Authenticator.ShouldBeOfType<NullLogger>(); It should_have_default_user_agent = () => settings.UserAgent.ShouldEqual("SpeakEasy"); static HttpClientSettings settings; } [Subject(typeof(HttpClientSettings))] public class default_settings_in_general : with_default_settings { It should_default_to_json_serializer = () => settings.DefaultSerializer.ShouldBeOfType<JsonDotNetSerializer>(); It should_have_json_deserializer = () => settings.Serializers.ShouldContain(d => d is JsonDotNetSerializer); It should_have_xml_deserializer = () => settings.Serializers.ShouldContain(d => d is DotNetXmlSerializer); } [Subject(typeof(HttpClientSettings))] public class when_customizing_serializer : with_default_settings { Because of = () => settings.Configure<JsonDotNetSerializer>(s => { called = true; }); It should_call_callback = () => called.ShouldEqual(true); static bool called; } public class with_default_settings { Establish context = () => settings = HttpClientSettings.Default; protected static HttpClientSettings settings; } } }
apache-2.0
C#
f9fe0a99c0f8afa7bcca30deec73147f1a882ec3
Update index.cshtml
LeedsSharp/AppVeyorDemo
src/AppVeyorDemo/AppVeyorDemo/Views/index.cshtml
src/AppVeyorDemo/AppVeyorDemo/Views/index.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>AppVeyor - Leeds#</title> <style type="text/css"> body { text-align: center; } h1 { font-family: 'Segoe UI Light', 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif; } </style> </head> <body> <img src="https://pbs.twimg.com/profile_images/2269442372/5s66pnbt5v8tw6most5e.png" alt="AppVeyor logo" /> <h1>Hello AppVeyor</h1> <img src="https://ci.appveyor.com/api/projects/status/mvcbc69n47vl5rvx" title="Build status"/> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>AppVeyor - Leeds#</title> <style type="text/css"> body { text-align: center; } h1 { font-family: 'Segoe UI Light', 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif; } </style> </head> <body> <img src="Content/appveyor_logo.png" alt="AppVeyor logo" /> <h1>Hello AppVeyor</h1> <img src="https://ci.appveyor.com/api/projects/status/mvcbc69n47vl5rvx" title="Build status"/> </body> </html>
apache-2.0
C#
d8e0e5cc60f24baba5177eb304dc1ec97dea13ca
Fix wrong copy direction in CreateClipMergeTileOperation
MHeasell/Mappy,MHeasell/Mappy
Mappy/Operations/OperationFactory.cs
Mappy/Operations/OperationFactory.cs
namespace Mappy.Operations { using System.Drawing; using Data; using Mappy.Models; public static class OperationFactory { public static IReplayableOperation CreateClipMergeTileOperation(IMapTile src, IMapTile dst, int x, int y) { // construct the destination target Rectangle rect = new Rectangle(x, y, src.TileGrid.Width, src.TileGrid.Height); // clip to boundaries rect.Intersect(new Rectangle(0, 0, dst.TileGrid.Width, dst.TileGrid.Height)); int srcX = rect.X - x; int srcY = rect.Y - y; return new CompositeOperation( new CopyAreaOperation<Bitmap>(src.TileGrid, dst.TileGrid, srcX, srcY, rect.X, rect.Y, rect.Width, rect.Height), new CopyAreaOperation<int>(src.HeightGrid, dst.HeightGrid, srcX * 2, srcY * 2, rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2)); } public static IReplayableOperation CreateFlattenOperation(IMapModel model) { IReplayableOperation[] arr = new IReplayableOperation[model.FloatingTiles.Count + 1]; int i = 0; foreach (Positioned<IMapTile> t in model.FloatingTiles) { arr[i++] = OperationFactory.CreateClipMergeTileOperation(t.Item, model.Tile, t.Location.X, t.Location.Y); } arr[i] = new ClearTilesOperation(model); return new CompositeOperation(arr); } } }
namespace Mappy.Operations { using System.Drawing; using Data; using Mappy.Models; public static class OperationFactory { public static IReplayableOperation CreateClipMergeTileOperation(IMapTile src, IMapTile dst, int x, int y) { // construct the destination target Rectangle rect = new Rectangle(x, y, src.TileGrid.Width, src.TileGrid.Height); // clip to boundaries rect.Intersect(new Rectangle(0, 0, dst.TileGrid.Width, dst.TileGrid.Height)); int srcX = rect.X - x; int srcY = rect.Y - y; return new CompositeOperation( new CopyAreaOperation<Bitmap>(dst.TileGrid, src.TileGrid, srcX, srcY, rect.X, rect.Y, rect.Width, rect.Height), new CopyAreaOperation<int>(dst.HeightGrid, src.HeightGrid, srcX * 2, srcY * 2, rect.X * 2, rect.Y * 2, rect.Width * 2, rect.Height * 2)); } public static IReplayableOperation CreateFlattenOperation(IMapModel model) { IReplayableOperation[] arr = new IReplayableOperation[model.FloatingTiles.Count + 1]; int i = 0; foreach (Positioned<IMapTile> t in model.FloatingTiles) { arr[i++] = OperationFactory.CreateClipMergeTileOperation(t.Item, model.Tile, t.Location.X, t.Location.Y); } arr[i] = new ClearTilesOperation(model); return new CompositeOperation(arr); } } }
mit
C#
41c7fc25a635cba0dc1ce0476e2d8d267a8afcb2
Change variable to paradigm instead of controller to improve naming consistency
xfleckx/BeMoBI,xfleckx/BeMoBI
Assets/Paradigms/SearchAndFind/Scripts/SubjectInteractions.cs
Assets/Paradigms/SearchAndFind/Scripts/SubjectInteractions.cs
using UnityEngine; using System.Collections; namespace Assets.BeMoBI.Paradigms.SearchAndFind { /// <summary> /// Represents all possible interactions for subject regarding the paradigm or trial behaviour /// </summary> public class SubjectInteractions : MonoBehaviour { private const string SUBMIT_INPUT = "Subject_Submit"; private const string REQUIRE_PAUSE = "Subject_Requires_Break"; ParadigmController paradigm; void Awake() { paradigm = FindObjectOfType<ParadigmController>(); } // Update is called once per frame void Update () { if (Input.GetAxis(SUBMIT_INPUT) > 0) { paradigm.SubjectTriesToSubmit(); } if (Input.GetAxis(REQUIRE_PAUSE) > 0) { paradigm.ForceABreakInstantly(); } } } }
using UnityEngine; using System.Collections; namespace Assets.BeMoBI.Paradigms.SearchAndFind { /// <summary> /// Represents all possible interactions for subject regarding the paradigm or trial behaviour /// </summary> public class SubjectInteractions : MonoBehaviour { private const string SUBMIT_INPUT = "Subject_Submit"; private const string REQUIRE_PAUSE = "Subject_Requires_Break"; ParadigmController controller; public bool TestMode = false; private bool homeButtonIsDown = false; void Awake() { controller = FindObjectOfType<ParadigmController>(); } // Update is called once per frame void Update () { if (Input.GetAxis(SUBMIT_INPUT) > 0) { controller.SubjectTriesToSubmit(); } if (Input.GetAxis(REQUIRE_PAUSE) > 0) { controller.ForceABreakInstantly(); } } } }
mit
C#
5dbca23cdff30529c95514b713206c3088bcc00c
Bump the version.
kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,kirilsi/csharp-sparkpost,darrencauthon/csharp-sparkpost,SparkPost/csharp-sparkpost,ZA1/csharp-sparkpost
src/SparkPost/Properties/AssemblyInfo.cs
src/SparkPost/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("SparkPost")] [assembly: AssemblyDescription("SparkPost API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SparkPost")] [assembly: AssemblyProduct("SparkPost")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("a5dda3e3-7b3d-46c3-b4bb-c627fba37812")] // 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.2.*")] [assembly: AssemblyFileVersion("1.0.2.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SparkPost")] [assembly: AssemblyDescription("SparkPost API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SparkPost")] [assembly: AssemblyProduct("SparkPost")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("a5dda3e3-7b3d-46c3-b4bb-c627fba37812")] // 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.1.*")] [assembly: AssemblyFileVersion("1.0.1.0")]
apache-2.0
C#
ed720295c1a913c22003595aa85313002c51fcbb
fix #94 Tired figuring out what is happening there, just ignore
radasuka/ShinraMeter,neowutran/ShinraMeter,Seyuna/ShinraMeter,neowutran/TeraDamageMeter
NetworkSniffer/Packets/IpPacket.cs
NetworkSniffer/Packets/IpPacket.cs
// Copyright (c) CodesInChaos // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace NetworkSniffer.Packets { public enum IpProtocol : byte { Tcp = 6, Udp = 17, Error = 255 } public struct Ip4Packet { public readonly ArraySegment<byte> Packet; public byte VersionAndHeaderLength => Packet.Array[Packet.Offset + 0]; public byte DscpAndEcn => Packet.Array[Packet.Offset + 1]; public ushort TotalLength => ParserHelpers.GetUInt16BigEndian(Packet.Array, Packet.Offset + 2); public ushort Identification => ParserHelpers.GetUInt16BigEndian(Packet.Array, Packet.Offset + 4); public byte Flags => (byte)(Packet.Array[Packet.Offset + 6] >> 13); public ushort FragmentOffset => (ushort)(ParserHelpers.GetUInt16BigEndian(Packet.Array, Packet.Offset + 6) & 0x1FFF); public byte TimeToLive => Packet.Array[Packet.Offset + 8]; public IpProtocol Protocol => ((Packet.Offset + TotalLength) > Packet.Array.Length || TotalLength <= HeaderLength) ? IpProtocol.Error : (IpProtocol) Packet.Array[Packet.Offset + 9]; public ushort HeaderChecksum => ParserHelpers.GetUInt16BigEndian(Packet.Array, Packet.Offset + 10); public uint SourceIp => ParserHelpers.GetUInt32BigEndian(Packet.Array, Packet.Offset + 12); public uint DestinationIp => ParserHelpers.GetUInt32BigEndian(Packet.Array, Packet.Offset + 16); public int HeaderLength => (VersionAndHeaderLength & 0x0F)*4; public ArraySegment<byte> Payload { get { var headerLength = HeaderLength; if ((Packet.Offset + TotalLength) > Packet.Array.Length || TotalLength <= headerLength) { throw new Exception($"Wrong packet TotalLength:{TotalLength} headerLength:{headerLength} Packet.Array.Length:{Packet.Array.Length} SourceIp:{SourceIp} DestinationIp:{DestinationIp}"); } return new ArraySegment<byte>(Packet.Array, Packet.Offset + headerLength, TotalLength - headerLength); } } public Ip4Packet(ArraySegment<byte> packet) { Packet = packet; } } }
// Copyright (c) CodesInChaos // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace NetworkSniffer.Packets { public enum IpProtocol : byte { Tcp = 6, Udp = 17 } public struct Ip4Packet { public readonly ArraySegment<byte> Packet; public byte VersionAndHeaderLength => Packet.Array[Packet.Offset + 0]; public byte DscpAndEcn => Packet.Array[Packet.Offset + 1]; public ushort TotalLength => ParserHelpers.GetUInt16BigEndian(Packet.Array, Packet.Offset + 2); public ushort Identification => ParserHelpers.GetUInt16BigEndian(Packet.Array, Packet.Offset + 4); public byte Flags => (byte) (Packet.Array[Packet.Offset + 6] >> 13); public ushort FragmentOffset => (ushort) (ParserHelpers.GetUInt16BigEndian(Packet.Array, Packet.Offset + 6) & 0x1FFF); public byte TimeToLive => Packet.Array[Packet.Offset + 8]; public IpProtocol Protocol => (IpProtocol) Packet.Array[Packet.Offset + 9]; public ushort HeaderChecksum => ParserHelpers.GetUInt16BigEndian(Packet.Array, Packet.Offset + 10); public uint SourceIp => ParserHelpers.GetUInt32BigEndian(Packet.Array, Packet.Offset + 12); public uint DestinationIp => ParserHelpers.GetUInt32BigEndian(Packet.Array, Packet.Offset + 16); public int HeaderLength => (VersionAndHeaderLength & 0x0F)*4; public ArraySegment<byte> Payload { get { var headerLength = HeaderLength; if ((Packet.Offset + TotalLength) > Packet.Array.Length || TotalLength <= headerLength) { throw new Exception($"Wrong packet TotalLength:{TotalLength} headerLength:{headerLength} Packet.Array.Length:{Packet.Array.Length} SourceIp:{SourceIp} DestinationIp:{DestinationIp}"); } return new ArraySegment<byte>(Packet.Array, Packet.Offset + headerLength, TotalLength - headerLength); } } public Ip4Packet(ArraySegment<byte> packet) { Packet = packet; } } }
mit
C#
53f4aaba79151c2306bd6faf1212c52b1be3df7d
Implement conversion back from Enum to Google CONSTANTS.
modulexcite/DartVS,DartVS/DartVS,modulexcite/DartVS,DartVS/DartVS,DartVS/DartVS,modulexcite/DartVS
DanTup.DartAnalysis/Infrastructure/JsonSerialiser.cs
DanTup.DartAnalysis/Infrastructure/JsonSerialiser.cs
using System; using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json; namespace DanTup.DartAnalysis { /// <summary> /// Serialises and deserialises objects to/from JSON. /// </summary> class JsonSerialiser { JsonConverter[] converters = new[] { new GoogleEnumJsonConverter() }; /// <summary> /// Serialises the provided object into JSON. /// </summary> /// <param name="obj">The object to serialise.</param> /// <returns>String of JSON representing the provided object.</returns> public string Serialise(object obj) { return JsonConvert.SerializeObject(obj, converters); } /// <summary> /// Deserialises the provided JSON into an object of type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type to deserialise into.</typeparam> /// <param name="json">The string of JSON to deserialise.</param> /// <returns>A concrete object built from the provided JSON.</returns> public T Deserialise<T>(string json) { return (T)Deserialise(json, typeof(T)); } /// <summary> /// Deserialises the provided JSON into an object of the provided type. /// </summary> /// <param name="json">The string of JSON to deserialise.</param> /// <param name="t">The Type to be deserialised into.</param> /// <returns>A concrete object built from the provided JSON.</returns> public object Deserialise(string json, Type t) { return JsonConvert.DeserializeObject(json, t, converters); } } class GoogleEnumJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType.IsEnum && !objectType.GetCustomAttributes(typeof(FlagsAttribute), false).Any(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.String) throw new JsonSerializationException(string.Format("Cannot convert non-string value to {0}.", objectType)); var wantedEnumValue = reader.Value.ToString().Replace("_", ""); var matchingEnumValue = Enum .GetNames(objectType) .FirstOrDefault(ht => string.Equals(ht, wantedEnumValue, StringComparison.OrdinalIgnoreCase)); if (matchingEnumValue == null) throw new JsonSerializationException(string.Format("Cannot convert value {0} to {1}.", reader.Value, objectType)); return Enum.Parse(objectType, matchingEnumValue); } static Regex uppercaseCharactersExcludingFirst = new Regex("([A-Z])", RegexOptions.Compiled); public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var enumValue = value.ToString(); // Prefix any caps with underscores (except first). enumValue = enumValue[0] + uppercaseCharactersExcludingFirst.Replace(enumValue.Substring(1), "_$1"); // Uppercase the whole string. enumValue = enumValue.ToUpper(); writer.WriteValue(enumValue); } } }
using System; using System.Linq; using Newtonsoft.Json; namespace DanTup.DartAnalysis { /// <summary> /// Serialises and deserialises objects to/from JSON. /// </summary> class JsonSerialiser { JsonConverter[] converters = new[] { new GoogleEnumJsonConverter() }; /// <summary> /// Serialises the provided object into JSON. /// </summary> /// <param name="obj">The object to serialise.</param> /// <returns>String of JSON representing the provided object.</returns> public string Serialise(object obj) { return JsonConvert.SerializeObject(obj, converters); } /// <summary> /// Deserialises the provided JSON into an object of type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type to deserialise into.</typeparam> /// <param name="json">The string of JSON to deserialise.</param> /// <returns>A concrete object built from the provided JSON.</returns> public T Deserialise<T>(string json) { return (T)Deserialise(json, typeof(T)); } /// <summary> /// Deserialises the provided JSON into an object of the provided type. /// </summary> /// <param name="json">The string of JSON to deserialise.</param> /// <param name="t">The Type to be deserialised into.</param> /// <returns>A concrete object built from the provided JSON.</returns> public object Deserialise(string json, Type t) { return JsonConvert.DeserializeObject(json, t, converters); } } class GoogleEnumJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType.IsEnum && !objectType.GetCustomAttributes(typeof(FlagsAttribute), false).Any(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.String) throw new JsonSerializationException(string.Format("Cannot convert non-string value to {0}.", objectType)); var wantedEnumValue = reader.Value.ToString().Replace("_", ""); var matchingEnumValue = Enum .GetNames(objectType) .FirstOrDefault(ht => string.Equals(ht, wantedEnumValue, StringComparison.OrdinalIgnoreCase)); if (matchingEnumValue == null) throw new JsonSerializationException(string.Format("Cannot convert value {0} to {1}.", reader.Value, objectType)); return Enum.Parse(objectType, matchingEnumValue); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } }
mit
C#
3c93daae43f8b02376d5c28fd26e3129638623a3
Fix issue with HockeyClient.Configure(appId) method initialization without passing TelemetryConfiguration parameter.
ChristopheLav/HockeySDK-Windows,bitstadium/HockeySDK-Windows,dkackman/HockeySDK-Windows
Src/Kit.UWP/HockeyClientExtensionsUwp.cs
Src/Kit.UWP/HockeyClientExtensionsUwp.cs
namespace Microsoft.HockeyApp { using Extensibility.Implementation; using Extensibility.Windows; using Services; using Services.Device; /// <summary> /// Send information to the HockeyApp service. /// </summary> public static class HockeyClientExtensionsUwp { /// <summary> /// Bootstraps HockeyApp SDK. /// </summary> /// <param name="this"><see cref="HockeyClient"/></param> /// <param name="appId">The application identifier, which is a unique hash string which is automatically created when you add a new application to HockeyApp.</param> public static void Configure(this IHockeyClient @this, string appId) { Configure(@this, appId, null); } /// <summary> /// Bootstraps HockeyApp SDK. /// </summary> /// <param name="this"><see cref="HockeyClient"/></param> /// <param name="appId">The application identifier, which is a unique hash string which is automatically created when you add a new application to HockeyApp.</param> /// <param name="configuration">Telemetry Configuration.</param> public static void Configure(this IHockeyClient @this, string appId, TelemetryConfiguration configuration) { ServiceLocator.AddService<BaseStorageService>(new StorageService()); ServiceLocator.AddService<IApplicationService>(new ApplicationService()); ServiceLocator.AddService<IDeviceService>(new DeviceService()); ServiceLocator.AddService<Services.IPlatformService>(new PlatformService()); ServiceLocator.AddService<IHttpService>(new HttpClientTransmission()); ServiceLocator.AddService<IUnhandledExceptionTelemetryModule>(new UnhandledExceptionTelemetryModule()); WindowsAppInitializer.InitializeAsync(appId, configuration); } } }
namespace Microsoft.HockeyApp { using Extensibility.Implementation; using Extensibility.Windows; using Services; using Services.Device; /// <summary> /// Send information to the HockeyApp service. /// </summary> public static class HockeyClientExtensionsUwp { /// <summary> /// Bootstraps HockeyApp SDK. /// </summary> /// <param name="this"><see cref="HockeyClient"/></param> /// <param name="appId">The application identifier, which is a unique hash string which is automatically created when you add a new application to HockeyApp.</param> public static void Configure(this IHockeyClient @this, string appId) { WindowsAppInitializer.InitializeAsync(appId, null); } /// <summary> /// Bootstraps HockeyApp SDK. /// </summary> /// <param name="this"><see cref="HockeyClient"/></param> /// <param name="appId">The application identifier, which is a unique hash string which is automatically created when you add a new application to HockeyApp.</param> /// <param name="configuration">Telemetry Configuration.</param> public static void Configure(this IHockeyClient @this, string appId, TelemetryConfiguration configuration) { ServiceLocator.AddService<BaseStorageService>(new StorageService()); ServiceLocator.AddService<IApplicationService>(new ApplicationService()); ServiceLocator.AddService<IDeviceService>(new DeviceService()); ServiceLocator.AddService<Services.IPlatformService>(new PlatformService()); ServiceLocator.AddService<IHttpService>(new HttpClientTransmission()); ServiceLocator.AddService<IUnhandledExceptionTelemetryModule>(new UnhandledExceptionTelemetryModule()); WindowsAppInitializer.InitializeAsync(appId, configuration); } } }
mit
C#
3b6d9243c5e2785d4e7724b51c7507b6382adb0b
Fix ie config
rosolko/WebDriverManager.Net
WebDriverManager/DriverConfigs/Impl/InternetExplorerConfig.cs
WebDriverManager/DriverConfigs/Impl/InternetExplorerConfig.cs
using System; using System.Linq; using System.Net; using System.Runtime.InteropServices; using Microsoft.Win32; using AngleSharp.Html.Parser; namespace WebDriverManager.DriverConfigs.Impl { public class InternetExplorerConfig : IDriverConfig { public virtual string GetName() { return "InternetExplorer"; } public virtual string GetUrl32() { return "https://github.com/SeleniumHQ/selenium/releases/download/selenium-<version>/IEDriverServer_Win32_<version>.zip"; } public virtual string GetUrl64() { return "https://github.com/SeleniumHQ/selenium/releases/download/selenium-<version>/IEDriverServer_x64_<version>.zip"; } public virtual string GetBinaryName() { return "IEDriverServer.exe"; } public virtual string GetLatestVersion() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (var client = new WebClient()) { var htmlCode = client.DownloadString("https://github.com/SeleniumHQ/selenium/releases"); var parser = new HtmlParser(); var document = parser.ParseDocument(htmlCode); var version = document.QuerySelectorAll("[class='Link--primary']") .Select(element => element.TextContent) .FirstOrDefault() ?.Replace("Selenium", "") .Trim(' ', '\r', '\n'); return version; } } public virtual string GetMatchingBrowserVersion() { #if NETSTANDARD if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new PlatformNotSupportedException("Your operating system is not supported"); } #endif return (string)Registry.GetValue( @"HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer", "svcVersion", "Latest"); } } }
using System; using System.Runtime.InteropServices; using Microsoft.Win32; namespace WebDriverManager.DriverConfigs.Impl { public class InternetExplorerConfig : IDriverConfig { public virtual string GetName() { return "InternetExplorer"; } public virtual string GetUrl32() { return "https://github.com/SeleniumHQ/selenium/releases/download/selenium-<version>/IEDriverServer_Win32_<version>.zip"; } public virtual string GetUrl64() { return "https://github.com/SeleniumHQ/selenium/releases/download/selenium-<version>/IEDriverServer_x64_<version>.zip"; } public virtual string GetBinaryName() { return "IEDriverServer.exe"; } public virtual string GetLatestVersion() { return "4.3.0"; } public virtual string GetMatchingBrowserVersion() { #if NETSTANDARD if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new PlatformNotSupportedException("Your operating system is not supported"); } #endif return (string)Registry.GetValue( @"HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer", "svcVersion", "Latest"); } } }
mit
C#
d9d25d4ffb7f0e01c4015f1b3714cc22dc937554
Add square matrix multiplication test case.
scott-fleischman/algorithms-csharp
tests/Algorithms.Collections.Tests/SquareMatrixTests.cs
tests/Algorithms.Collections.Tests/SquareMatrixTests.cs
using System.Collections.Generic; using System.Globalization; using System.Text; using NUnit.Framework; namespace Algorithms.Collections.Tests { [TestFixture] public class SquareMatrixTests { [TestCaseSource("GetTestCases")] public void Multiply(TestCase testCase) { int[,] result = SquareMatrix.Multiply(testCase.Left, testCase.Right, (x, y) => x + y, (x, y) => x * y); CollectionAssert.AreEqual(result, testCase.Product); } public IEnumerable<TestCase> GetTestCases() { return new[] { new TestCase { Left = new[,] {{1, 2}, {3, 4}}, Right = new[,] {{4, 3}, {2, 1}}, Product = new[,] {{8, 5}, {20, 13}}, }, }; } public class TestCase { public int[,] Left { get; set; } public int[,] Right { get; set; } public int[,] Product { get; set; } public override string ToString() { return string.Format("{{Left={0}, Right={1}, Product={2}}}", RenderMatrix(Left), RenderMatrix(Right), RenderMatrix(Product)); } private static string RenderMatrix(int[,] matrix) { var builder = new StringBuilder(); builder.Append("{"); for (int row = 0; row < matrix.GetLength(0); row++) { if (row != 0) builder.Append(","); builder.Append("{"); for (int column = 0; column < matrix.GetLength(1); column++) { if (column != 0) builder.Append(","); builder.Append(matrix[row, column]); } builder.Append("}"); } builder.Append("}"); return builder.ToString(); } private static string RenderRow(int row, int[,] matrix, int padding) { var builder = new StringBuilder(); if (row < matrix.GetLength(row)) { for (int column = 0; column < matrix.GetLength(1); column++) builder.Append(matrix[row, column].ToString(CultureInfo.InvariantCulture).PadLeft(padding)); } return builder.ToString(); } } } }
using NUnit.Framework; namespace Algorithms.Collections.Tests { [TestFixture] public class SquareMatrixTests { } }
mit
C#