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
778441265e519577122454aa3c0819d2ece63d2f
Update OfData()
amatukaze/HeavenlyWind
src/Game/Sakuno.ING.Game.Provider/GameProvider.Extensions.cs
src/Game/Sakuno.ING.Game.Provider/GameProvider.Extensions.cs
using Sakuno.ING.Game.Json; using System; using System.Reactive.Linq; namespace Sakuno.ING.Game { internal static class SvDataObservableExtensions { public static IObservable<T> OfData<T>(this IObservable<SvData?> source) => source.OfType<SvData<T>>().Where(svdata => svdata.api_result == 1).Select(svdata => svdata.api_data); public static IObservable<TEvent> Parse<TRaw, TEvent>(this IObservable<SvData?> source, Func<TRaw, TEvent> eventSelector) { var events = source.OfType<SvData<TRaw>>().Where(svdata => svdata.api_result == 1).Select(svdata => eventSelector(svdata.api_data)).Publish(); events.Connect(); return events.AsObservable(); } } }
using Sakuno.ING.Game.Json; using System; using System.Reactive.Linq; namespace Sakuno.ING.Game { internal static class SvDataObservableExtensions { public static IObservable<TEvent> Parse<TRaw, TEvent>(this IObservable<SvData?> source, Func<TRaw, TEvent> eventSelector) { var events = source.OfType<SvData<TRaw>>().Where(svdata => svdata.api_result == 1).Select(svdata => eventSelector(svdata.api_data)).Publish(); events.Connect(); return events.AsObservable(); } public static IObservable<T> OfData<T>(this IObservable<SvData?> source) { var events = source.OfType<SvData<T>>().Where(svdata => svdata.api_result == 1).Select(svdata => svdata.api_data).Publish(); events.Connect(); return events.AsObservable(); } } }
mit
C#
c02e9c5ca95741fb22a518d831db16c9ec747110
Add comment to uSyncCore extension method
KevinJump/uSync,KevinJump/uSync,KevinJump/uSync
uSync.Core/uSyncCoreBuilderExtensions.cs
uSync.Core/uSyncCoreBuilderExtensions.cs
 using System.Linq; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Extensions; using uSync.Core.Cache; using uSync.Core.DataTypes; using uSync.Core.Dependency; using uSync.Core.Mapping; using uSync.Core.Serialization; using uSync.Core.Tracking; namespace uSync.Core { public static class uSyncCoreBuilderExtensions { /// <summary> /// Adds uSyncCore to project. /// </summary> /// <remarks> /// uSyncCore does not usally need to be registerd seperatly from /// uSync. unless you are using core features but not backoffice (files, handler) features /// </remarks> /// <param name="builder"></param> /// <returns></returns> public static IUmbracoBuilder AdduSyncCore(this IUmbracoBuilder builder) { // TODO: Check this - in theory, if SyncEnityCache is already registered we don't run again. if (builder.Services.FirstOrDefault(x => x.ServiceType == typeof(SyncEntityCache)) != null) return builder; // cache for entity items, we use it to speed up lookups. builder.Services.AddUnique<SyncEntityCache>(); // register *all* ConfigurationSerializers except those marked [HideFromTypeFinder] // has to happen before the DataTypeSerializer is loaded, because that is where // they are used builder.WithCollectionBuilder<ConfigurationSerializerCollectionBuilder>() .Add(() => builder.TypeLoader.GetTypes<IConfigurationSerializer>()); // value mappers, (map internal things in properties in and out of syncing process) builder.WithCollectionBuilder<SyncValueMapperCollectionBuilder>() .Add(() => builder.TypeLoader.GetTypes<ISyncMapper>()); // serializers - turn umbraco objects into / from xml in memeory. builder.WithCollectionBuilder<SyncSerializerCollectionBuilder>() .Add(builder.TypeLoader.GetTypes<ISyncSerializerBase>()); // the trackers, allow us to be more nuanced in tracking changes. builder.WithCollectionBuilder<SyncTrackerCollectionBuilder>() .Add(builder.TypeLoader.GetTypes<ISyncTrackerBase>()); // Dependency checkers tell you what other umbraco objects an item needs to work builder.WithCollectionBuilder<SyncDependencyCollectionBuilder>() .Add(builder.TypeLoader.GetTypes<ISyncDependencyItem>()); // the item factory lets us get to these collections from one place. builder.Services.AddUnique<ISyncItemFactory, SyncItemFactory>(); return builder; } } }
 using System.Linq; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Extensions; using uSync.Core.Cache; using uSync.Core.DataTypes; using uSync.Core.Dependency; using uSync.Core.Mapping; using uSync.Core.Serialization; using uSync.Core.Tracking; namespace uSync.Core { public static class uSyncCoreBuilderExtensions { public static IUmbracoBuilder AdduSyncCore(this IUmbracoBuilder builder) { // TODO: Check this - in theory, if SyncEnityCache is already registered we don't run again. if (builder.Services.FirstOrDefault(x => x.ServiceType == typeof(SyncEntityCache)) != null) return builder; // cache for entity items, we use it to speed up lookups. builder.Services.AddUnique<SyncEntityCache>(); // register *all* ConfigurationSerializers except those marked [HideFromTypeFinder] // has to happen before the DataTypeSerializer is loaded, because that is where // they are used builder.WithCollectionBuilder<ConfigurationSerializerCollectionBuilder>() .Add(() => builder.TypeLoader.GetTypes<IConfigurationSerializer>()); // value mappers, (map internal things in properties in and out of syncing process) builder.WithCollectionBuilder<SyncValueMapperCollectionBuilder>() .Add(() => builder.TypeLoader.GetTypes<ISyncMapper>()); // serializers - turn umbraco objects into / from xml in memeory. builder.WithCollectionBuilder<SyncSerializerCollectionBuilder>() .Add(builder.TypeLoader.GetTypes<ISyncSerializerBase>()); // the trackers, allow us to be more nuanced in tracking changes. builder.WithCollectionBuilder<SyncTrackerCollectionBuilder>() .Add(builder.TypeLoader.GetTypes<ISyncTrackerBase>()); // Dependency checkers tell you what other umbraco objects an item needs to work builder.WithCollectionBuilder<SyncDependencyCollectionBuilder>() .Add(builder.TypeLoader.GetTypes<ISyncDependencyItem>()); // the item factory lets us get to these collections from one place. builder.Services.AddUnique<ISyncItemFactory, SyncItemFactory>(); return builder; } } }
mpl-2.0
C#
5d659b38601b2620054b286c941a5d53f1da20ae
Revert "registration of api controllers fixed"
borismod/ReSharperTnT,borismod/ReSharperTnT
ReSharperTnT/Bootstrapper.cs
ReSharperTnT/Bootstrapper.cs
using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { static Bootstrapper() { Init(); } public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .Where(c=>c.Name.EndsWith("Controller")) .AsSelf(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }
using System.Reflection; using System.Web.Http; using Autofac; using Autofac.Integration.WebApi; namespace ReSharperTnT { public class Bootstrapper { public static void Init() { var bootstrapper = new Bootstrapper(); var container = bootstrapper.CreateContainer(); var autofacWebApiDependencyResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = autofacWebApiDependencyResolver; } private readonly IContainer _container; public Bootstrapper() { var builder = new ContainerBuilder(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(typeof (Bootstrapper).Assembly) .AsImplementedInterfaces(); _container = builder.Build(); } public IContainer CreateContainer() { return _container; } public T Get<T>() { return _container.Resolve<T>(); } } }
apache-2.0
C#
1c23e073f938b3a3b9aa05d2cea797d5219406c1
Convert Point2 (ints) to Vector2 (floats).
izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib
ChamberLib/Point2.cs
ChamberLib/Point2.cs
using System; namespace ChamberLib { public struct Point2 { public Point2(int x, int y) { X = x; Y = y; } public int X; public int Y; public static readonly Point2 Zero = new Point2(0, 0); public static readonly Point2 One = new Point2(1, 1); public static readonly Point2 UnitX = new Point2(1, 0); public static readonly Point2 UnitY = new Point2(0, 1); public static Point2 operator -(Point2 v) { return new Point2(-v.X, -v.Y); } public static Point2 operator -(Point2 x, Point2 y) { return new Point2(x.X - y.X, x.Y - y.Y); } public static Point2 operator +(Point2 x, Point2 y) { return new Point2(x.X + y.X, x.Y + y.Y); } public static bool operator ==(Point2 u, Point2 v) { return u.Equals(v); } public static bool operator !=(Point2 u, Point2 v) { return !u.Equals(v); } public bool Equals(Point2 other) { return (this.X == other.X && this.Y == other.Y); } public override bool Equals(object other) { if (other is Point2) { return Equals((Point2)other); } else { return false; } } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } public static Point2 Max(Point2 u, Point2 v) { return new Point2( Math.Max(u.X, v.X), Math.Max(u.Y, v.Y)); } public Vector2 ToVector2() { return new Vector2(X, Y); } } }
using System; namespace ChamberLib { public struct Point2 { public Point2(int x, int y) { X = x; Y = y; } public int X; public int Y; public static readonly Point2 Zero = new Point2(0, 0); public static readonly Point2 One = new Point2(1, 1); public static readonly Point2 UnitX = new Point2(1, 0); public static readonly Point2 UnitY = new Point2(0, 1); public static Point2 operator -(Point2 v) { return new Point2(-v.X, -v.Y); } public static Point2 operator -(Point2 x, Point2 y) { return new Point2(x.X - y.X, x.Y - y.Y); } public static Point2 operator +(Point2 x, Point2 y) { return new Point2(x.X + y.X, x.Y + y.Y); } public static bool operator ==(Point2 u, Point2 v) { return u.Equals(v); } public static bool operator !=(Point2 u, Point2 v) { return !u.Equals(v); } public bool Equals(Point2 other) { return (this.X == other.X && this.Y == other.Y); } public override bool Equals(object other) { if (other is Point2) { return Equals((Point2)other); } else { return false; } } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } public static Point2 Max(Point2 u, Point2 v) { return new Point2( Math.Max(u.X, v.X), Math.Max(u.Y, v.Y)); } } }
lgpl-2.1
C#
ce1f9e7b9259391fa4627febb1cde15fe565a7f2
update assm ver
jlucansky/refit,PKRoma/refit,jlucansky/refit,onovotny/refit,paulcbetts/refit,onovotny/refit,paulcbetts/refit
Refit/Properties/AssemblyInfo.cs
Refit/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Refit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("paul")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("2.5.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: InternalsVisibleTo("Refit")] [assembly: InternalsVisibleTo("Refit-Tests")] [assembly: InternalsVisibleTo("Refit.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Refit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("paul")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("2.4.1")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] [assembly: InternalsVisibleTo("Refit")] [assembly: InternalsVisibleTo("Refit-Tests")] [assembly: InternalsVisibleTo("Refit.Tests")]
mit
C#
105420a297cae1085a5d046bb62a658c0c334a7f
Add KEYS function in expression #743
mbdavid/LiteDB,falahati/LiteDB,89sos98/LiteDB,89sos98/LiteDB,falahati/LiteDB
LiteDB/Document/Expression/Functions/DataTypes.cs
LiteDB/Document/Expression/Functions/DataTypes.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace LiteDB { public partial class BsonExpression { public static IEnumerable<BsonValue> ARRAY(IEnumerable<BsonValue> values) { yield return new BsonArray(values); } public static IEnumerable<BsonValue> JSON(IEnumerable<BsonValue> values) { foreach (var value in values.Where(x => x.IsString)) { yield return JsonSerializer.Deserialize(value); } } public static IEnumerable<BsonValue> KEYS(IEnumerable<BsonValue> values) { foreach (var value in values.Where(x => x.IsDocument)) { foreach(var key in value.AsDocument.Keys) { yield return key; } } } public static IEnumerable<BsonValue> IS_DATE(IEnumerable<BsonValue> values) { foreach (var value in values) { yield return value.IsDateTime; } } public static IEnumerable<BsonValue> IS_NUMBER(IEnumerable<BsonValue> values) { foreach (var value in values) { yield return value.IsNumber; } } public static IEnumerable<BsonValue> IS_STRING(IEnumerable<BsonValue> values) { foreach (var value in values) { yield return value.IsString; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace LiteDB { public partial class BsonExpression { public static IEnumerable<BsonValue> ARRAY(IEnumerable<BsonValue> values) { yield return new BsonArray(values); } public static IEnumerable<BsonValue> JSON(IEnumerable<BsonValue> values) { foreach(var value in values.Where(x => x.IsString)) { yield return JsonSerializer.Deserialize(value); } } public static IEnumerable<BsonValue> IS_DATE(IEnumerable<BsonValue> values) { foreach (var value in values) { yield return value.IsDateTime; } } public static IEnumerable<BsonValue> IS_NUMBER(IEnumerable<BsonValue> values) { foreach (var value in values) { yield return value.IsNumber; } } public static IEnumerable<BsonValue> IS_STRING(IEnumerable<BsonValue> values) { foreach (var value in values) { yield return value.IsString; } } } }
mit
C#
7fa5fe3357463baefe03969207a058cfc5b87037
Update AbstractMusicNote names
MattJamesChampion/FretEngine
FretEngine/Common/DataTypes/AbstractMusicNote.cs
FretEngine/Common/DataTypes/AbstractMusicNote.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FretEngine.Common.DataTypes { public enum AbstractMusicNote { BSharpCNatural, CSharpDFlat, DNatural, DSharpEFlat, ENaturalFFlat, ESharpFNatural, FSharpGFlat, GNatural, GSharpAFlat, ANatural, ASharpBFlat, BNaturalCFlat } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FretEngine.Common.DataTypes { public enum AbstractMusicNote { CNatural, CSharpDFlat, DNatural, DSharpEFlat, ENatural, FNatural, FSharpGFlat, GNatural, GSharpAFlat, ANatural, ASharpBFlat, BNatural } }
mit
C#
13b9a046f53ef906b23593ed63c95a199278426e
Remove actions, moved to Utils.SynchronizeModule
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.Launchpad/SettingsLaunchpad.ascx.cs
R7.University.Launchpad/SettingsLaunchpad.ascx.cs
using System; using System.Web.UI.WebControls; using System.Linq; using DotNetNuke.Entities.Modules; using DotNetNuke.Services.Exceptions; using DotNetNuke.UI.UserControls; using R7.University; namespace R7.University.Launchpad { public partial class SettingsLaunchpad : ModuleSettingsBase { public void OnInit() { // fill PageSize combobox comboPageSize.AddItem("10", "10"); comboPageSize.AddItem("25", "25"); comboPageSize.AddItem("50", "50"); comboPageSize.AddItem("100", "100"); // fill tables list listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Positions", "positions")); listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Divisions", "divisions")); listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Employees", "employees")); } /// <summary> /// Handles the loading of the module setting for this control /// </summary> public override void LoadSettings () { try { if (!IsPostBack) { var settings = new LaunchpadSettings (this); // TODO: Allow select nearest pagesize value comboPageSize.Select (settings.PageSize.ToString(), false); // check table list items var tableNames = settings.Tables.Split(';'); foreach (var tableName in tableNames) { var item = listTables.FindItemByValue(tableName); if (item != null) item.Checked = true; } } } catch (Exception ex) { Exceptions.ProcessModuleLoadException (this, ex); } } /// <summary> /// handles updating the module settings for this control /// </summary> public override void UpdateSettings () { try { var settings = new LaunchpadSettings (this); settings.PageSize = int.Parse(comboPageSize.SelectedValue); settings.Tables = Utils.FormatList(";", listTables.CheckedItems.Select(i => i.Value).ToArray()); Utils.SynchronizeModule(this); } catch (Exception ex) { Exceptions.ProcessModuleLoadException (this, ex); } } } }
using System; using System.Web.UI.WebControls; using System.Linq; using DotNetNuke.Entities.Modules; using DotNetNuke.Services.Exceptions; using DotNetNuke.UI.UserControls; using R7.University; namespace R7.University.Launchpad { public partial class SettingsLaunchpad : ModuleSettingsBase { public void OnInit() { // fill PageSize combobox comboPageSize.AddItem("10", "10"); comboPageSize.AddItem("25", "25"); comboPageSize.AddItem("50", "50"); comboPageSize.AddItem("100", "100"); // fill tables list listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Positions", "positions")); listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Divisions", "divisions")); listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Employees", "employees")); } /// <summary> /// Handles the loading of the module setting for this control /// </summary> public override void LoadSettings () { try { if (!IsPostBack) { var settings = new LaunchpadSettings (this); // TODO: Allow select nearest pagesize value comboPageSize.Select (settings.PageSize.ToString(), false); // check table list items var tableNames = settings.Tables.Split(';'); foreach (var tableName in tableNames) { var item = listTables.FindItemByValue(tableName); if (item != null) item.Checked = true; } } } catch (Exception ex) { Exceptions.ProcessModuleLoadException (this, ex); } } /// <summary> /// handles updating the module settings for this control /// </summary> public override void UpdateSettings () { try { var settings = new LaunchpadSettings (this); settings.PageSize = int.Parse(comboPageSize.SelectedValue); settings.Tables = Utils.FormatList(";", listTables.CheckedItems.Select(i => i.Value).ToArray()); // NOTE: update module cache (temporary fix before 7.2.0)? // more info: https://github.com/dnnsoftware/Dnn.Platform/pull/21 var moduleController = new ModuleController(); moduleController.ClearCache(TabId); Utils.SynchronizeModule(this); } catch (Exception ex) { Exceptions.ProcessModuleLoadException (this, ex); } } } }
agpl-3.0
C#
cc9431c2dac19b232be8c91bc9920f07d33ff584
Add implicit client flow.
affecto/dotnet-AuthenticationServer
Source/AuthenticationServer/Configuration/Flow.cs
Source/AuthenticationServer/Configuration/Flow.cs
namespace Affecto.AuthenticationServer.Configuration { public enum Flow { ResourceOwner, Implicit } }
namespace Affecto.AuthenticationServer.Configuration { public enum Flow { ResourceOwner } }
mit
C#
115496594e2709b0abba0b518963b19eabd26eca
Add a JsonObject.FromString convenience method
GNOME/hyena,arfbtwn/hyena,dufoli/hyena,GNOME/hyena,arfbtwn/hyena,dufoli/hyena
Hyena/Hyena.Json/JsonObject.cs
Hyena/Hyena.Json/JsonObject.cs
// // JsonObject.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, 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.Linq; using System.Collections.Generic; using System.Text; namespace Hyena.Json { public class JsonObject : Dictionary<string, object>, IJsonCollection { public void Dump () { Dump (1); } public void Dump (int level) { Console.Write (ToString ()); } public override string ToString () { return new Serializer (this).Serialize (); } public static JsonObject FromString (string input) { return new Deserializer (input).Deserialize () as JsonObject; } } }
// // JsonObject.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, 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.Linq; using System.Collections.Generic; using System.Text; namespace Hyena.Json { public class JsonObject : Dictionary<string, object>, IJsonCollection { public void Dump () { Dump (1); } public void Dump (int level) { Console.Write (ToString ()); } public override string ToString () { return new Serializer (this).Serialize (); } } }
mit
C#
79614d37b6df798c4df9e21e09f5de6f3ffa26a3
Update Skills/Index.html
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.WebApp/Views/Skills/Index.cshtml
NinjaHive.WebApp/Views/Skills/Index.cshtml
@using NinjaHive.Contract.DTOs @using NinjaHive.WebApp.Controllers @using NinjaHive.WebApp.Services @model Skill[] <div class="row"> <div class="col-md-12"> <br /> <p> @Html.ActionLink("Create Equipment Item", "Create", null, new { @class = "btn btn-default" }) </p> <hr /> <h4>List of items in the database</h4> </div> @foreach (var item in Model) { var itemId = item.Id; //var itemDetailsUrl = UrlProvider<SkillsController>.GetUrl(c => c.Edit(itemId)); <div class="col-md-2"> <div class="thumbnail"> <a href="" class="thumbnail"> <img src="/Content/Images/default_image.png" alt="..." /> </a> <div class="caption"> <p>@item.Name</p> <p> @*@Html.ActionLink("Delete", "Delete", item)<br />*@ @*<a href="@itemDetailsUrl"> Edit </a>*@ </p> </div> </div> </div> } </div>
@using NinjaHive.Contract.DTOs @using NinjaHive.WebApp.Controllers @using NinjaHive.WebApp.Services @model Skill[] <div class="row"> <div class="panel panel-default"> <div class="panel-body"> @{ var createUri = UrlProvider<SkillsController>.GetUrl(c => c.Create()); } <a href="@createUri" class="btn btn-default"> Create </a> </div> </div> </div> <div class="row"> <div class="col-md-3"> <div class="list-group"> @foreach (var skill in Model) { <button type="button" class="list-group-item"> @skill.Name </button> } </div> </div> <div class="col-md-9"> @*skill edit here*@ </div> </div>
apache-2.0
C#
19e737e45ab2b58554d1068833528b473bc333d2
hide reply.
Jetski5822/NGM.Forum
Views/Parts.Thread.Manage.cshtml
Views/Parts.Thread.Manage.cshtml
@using NGM.Forum @using NGM.Forum.Extensions @using NGM.Forum.Models @{ var postPart = (PostPart)Model.ContentPart; } <div class="item-properties actions"> @if (!postPart.ThreadPart.IsClosed) { <a href="@Url.PostReply(postPart)">@T("Reply to this Thread")</a> } </div>
@using NGM.Forum @using NGM.Forum.Extensions @using NGM.Forum.Models @{ var postPart = (PostPart)Model.ContentPart; } <div class="item-properties actions"> <a href="@Url.PostReply(postPart)">@T("Reply to this Thread")</a> </div>
bsd-3-clause
C#
ee13ed524d3a56943af041b51d6a9ddf09126c38
Update TypeProcessor.cs
Fody/Virtuosity
Virtuosity.Fody/TypeProcessor.cs
Virtuosity.Fody/TypeProcessor.cs
using Mono.Cecil; public partial class ModuleWeaver { public void ProcessType(TypeDefinition typeDefinition) { WriteDebug($"\t{typeDefinition.FullName}"); foreach (var method in typeDefinition.Methods) { if (method.IsConstructor) { continue; } ProcessMethod(method); } } void ProcessMethod(MethodDefinition method) { if (method == null) { return; } if (method.IsFinal && method.IsVirtual) { method.IsFinal = false; AddMethodToCache(method); return; } if (method.IsFinal) { return; } if (method.IsVirtual) { return; } if (method.IsStatic) { return; } if (method.IsPrivate) { return; } if (MethodIsSerializationCallback(method)) { return; } AddMethodToCache(method); method.IsVirtual = true; method.IsNewSlot = true; } bool MethodIsSerializationCallback(MethodDefinition method) { return method.CustomAttributes.ContainsAttribute("OnSerializingAttribute") || method.CustomAttributes.ContainsAttribute("OnSerializedAttribute") || method.CustomAttributes.ContainsAttribute("OnDeserializingAttribute") || method.CustomAttributes.ContainsAttribute("OnDeserializedAttribute"); } }
using Mono.Cecil; public partial class ModuleWeaver { public void ProcessType(TypeDefinition typeDefinition) { LogDebug($"\t{typeDefinition.FullName}"); foreach (var method in typeDefinition.Methods) { if (method.IsConstructor) { continue; } ProcessMethod(method); } } void ProcessMethod(MethodDefinition method) { if (method == null) { return; } if (method.IsFinal && method.IsVirtual) { method.IsFinal = false; AddMethodToCache(method); return; } if (method.IsFinal) { return; } if (method.IsVirtual) { return; } if (method.IsStatic) { return; } if (method.IsPrivate) { return; } if (MethodIsSerializationCallback(method)) { return; } AddMethodToCache(method); method.IsVirtual = true; method.IsNewSlot = true; } bool MethodIsSerializationCallback(MethodDefinition method) { return method.CustomAttributes.ContainsAttribute("OnSerializingAttribute") || method.CustomAttributes.ContainsAttribute("OnSerializedAttribute") || method.CustomAttributes.ContainsAttribute("OnDeserializingAttribute") || method.CustomAttributes.ContainsAttribute("OnDeserializedAttribute"); } }
mit
C#
21fae893a55dd748dc3838852f88ad0b18d68ecd
Add friendly API for NetworkListener
gnamma/client
Assets/Scripts/NetworkListener.cs
Assets/Scripts/NetworkListener.cs
using UnityEngine; using System.Collections; using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; using System.IO; public class NetworkListener : MonoBehaviour { public string host; public int port; private TcpClient client; public void Connect() { Connect(host, port); } public void Connect(string host, int port) { client = new TcpClient(); client.Connect(host, port); } private void Send(object cmd) { string toSend = JsonUtility.ToJson(cmd); Debug.Log(toSend); byte[] data; data = Encoding.Default.GetBytes(toSend + "\n"); client.GetStream().Write(data, 0, data.Length); } private void Receive<T>(ref T blob) { new Thread(() => { Protocol.ConnectVerdict conver = new Protocol.ConnectVerdict(); StreamReader reader = new StreamReader(client.GetStream()); string rec = reader.ReadLine(); try { conver = JsonUtility.FromJson<Protocol.ConnectVerdict>(rec); Debug.Log(conver.message); } catch (Exception e) { Debug.Log("Error umarshalling JSON"); Debug.Log(e); } }).Start(); } }
using UnityEngine; using System.Collections; using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; using System.IO; public class NetworkListener : MonoBehaviour { public string host; public int port; private TcpClient client; private byte[] datalen = new byte[4]; void Start () { client = new TcpClient(); client.Connect(host, port); NetworkStream stream = client.GetStream(); Protocol.ConnectRequest cr = new Protocol.ConnectRequest(); cr.command = "connect_request"; cr.username = "paked"; cr.sent_at = 22; Protocol.ConnectVerdict cv = new Protocol.ConnectVerdict(); Send(cr, stream); Receive(ref cv); } private void Send(object cmd, NetworkStream stream) { string toSend = JsonUtility.ToJson(cmd); Debug.Log(toSend); byte[] data; data = Encoding.Default.GetBytes(toSend + "\n"); stream.Write(data, 0, data.Length); } private void Receive<T>(ref T blob) { new Thread(() => { Protocol.ConnectVerdict conver = new Protocol.ConnectVerdict(); StreamReader reader = new StreamReader(client.GetStream()); string rec = reader.ReadLine(); try { conver = JsonUtility.FromJson<Protocol.ConnectVerdict>(rec); Debug.Log(conver.message); } catch (Exception e) { Debug.Log("Error umarshalling JSON"); Debug.Log(e); } }).Start(); } }
mit
C#
c52838bd4cb080dae54c90c97a774abcad602a32
Initialize CommandDispatcher with an alias matcher
appharbor/appharbor-cli
src/AppHarbor/CommandDispatcher.cs
src/AppHarbor/CommandDispatcher.cs
using System; using System.Linq; using Castle.MicroKernel; namespace AppHarbor { public class CommandDispatcher { private readonly IAliasMatcher _aliasMatcher; private readonly ITypeNameMatcher _typeNameMatcher; private readonly IKernel _kernel; public CommandDispatcher(IAliasMatcher aliasMatcher, ITypeNameMatcher typeNameMatcher, IKernel kernel) { _aliasMatcher = aliasMatcher; _typeNameMatcher = typeNameMatcher; _kernel = kernel; } public void Dispatch(string[] args) { var commandArgument = args.Any() ? string.Concat(args.Skip(1).FirstOrDefault(), args[0]) : "help"; Type matchingType = null; if (_typeNameMatcher.IsSatisfiedBy(commandArgument)) { matchingType = _typeNameMatcher.GetMatchedType(commandArgument); } var command = (ICommand)_kernel.Resolve(matchingType); try { command.Execute(args.Skip(2).ToArray()); } catch (CommandException exception) { Console.WriteLine(string.Format("Error: {0}", exception.Message)); } } } }
using System; using System.Linq; using Castle.MicroKernel; namespace AppHarbor { public class CommandDispatcher { private readonly ITypeNameMatcher _typeNameMatcher; private readonly IKernel _kernel; public CommandDispatcher(ITypeNameMatcher typeNameMatcher, IKernel kernel) { _typeNameMatcher = typeNameMatcher; _kernel = kernel; } public void Dispatch(string[] args) { var commandArgument = args.Any() ? string.Concat(args.Skip(1).FirstOrDefault(), args[0]) : "help"; Type matchingType = null; if (_typeNameMatcher.IsSatisfiedBy(commandArgument)) { matchingType = _typeNameMatcher.GetMatchedType(commandArgument); } var command = (ICommand)_kernel.Resolve(matchingType); try { command.Execute(args.Skip(2).ToArray()); } catch (CommandException exception) { Console.WriteLine(string.Format("Error: {0}", exception.Message)); } } } }
mit
C#
2ac11207ce09255090058a603d244256719a58d2
Refactor and tweak Koren triode model to hopefully make it faster
dsharlet/LiveSPICE
Circuit/Components/KorenTriode.cs
Circuit/Components/KorenTriode.cs
using ComputerAlgebra; using System.ComponentModel; namespace Circuit { /// <summary> /// Base class for a triode. /// </summary> [Category("Vacuum Tubes")] [DisplayName("Triode (Koren)")] [Description("Triode implemented using Norman Koren's model.")] public class KorenTriode : Triode { private double mu = 100.0; private double ex = 1.4; private double kg = 1060.0; private double kp = 600.0; private double kvb = 300; private Quantity rgk = new Quantity(1e6, Units.Ohm); private Quantity vg = new Quantity(0.33, Units.V); [Serialize] public double Mu { get { return mu; } set { mu = value; NotifyChanged("Mu"); } } [Serialize] public double Ex { get { return ex; } set { ex = value; NotifyChanged("Ex"); } } [Serialize] public double Kg { get { return kg; } set { kg = value; NotifyChanged("Kg"); } } [Serialize] public double Kp { get { return kp; } set { kp = value; NotifyChanged("Kp"); } } [Serialize] public double Kvb { get { return kvb; } set { kvb = value; NotifyChanged("Kvb"); } } [Serialize] public Quantity Rgk { get { return rgk; } set { if (rgk.Set(value)) NotifyChanged("Rgk"); } } [Serialize] public Quantity Vg { get { return vg; } set { if (vg.Set(value)) NotifyChanged("Vg"); } } protected override void Analyze(Analysis Mna, Expression Vpk, Expression Vgk, out Expression Ip, out Expression Ig) { Expression E1 = Ln1Exp(Kp * (1.0 / Mu + Vgk * (Kvb + Vpk ^ 2) ^ (-0.5))) * Vpk / Kp; Ip = (Call.Max(E1, 0) ^ Ex) / Kg; Ig = Call.Max(Vgk - Vg, 0) / Rgk; } // ln(1+e^x) = x for large x, and large x causes numerical issues. private static Expression Ln1Exp(Expression x) { return Call.If(x > 50, x, Call.Ln(1 + Call.Exp(x))); } } }
using ComputerAlgebra; using System.ComponentModel; namespace Circuit { /// <summary> /// Base class for a triode. /// </summary> [Category("Vacuum Tubes")] [DisplayName("Triode (Koren)")] [Description("Triode implemented using Norman Koren's model.")] public class KorenTriode : Triode { private double mu = 100.0; private double ex = 1.4; private double kg = 1060.0; private double kp = 600.0; private double kvb = 300; private Quantity rgk = new Quantity(1e6, Units.Ohm); private Quantity vg = new Quantity(0.33, Units.V); [Serialize] public double Mu { get { return mu; } set { mu = value; NotifyChanged("Mu"); } } [Serialize] public double Ex { get { return ex; } set { ex = value; NotifyChanged("Ex"); } } [Serialize] public double Kg { get { return kg; } set { kg = value; NotifyChanged("Kg"); } } [Serialize] public double Kp { get { return kp; } set { kp = value; NotifyChanged("Kp"); } } [Serialize] public double Kvb { get { return kvb; } set { kvb = value; NotifyChanged("Kvb"); } } [Serialize] public Quantity Rgk { get { return rgk; } set { if (rgk.Set(value)) NotifyChanged("Rgk"); } } [Serialize] public Quantity Vg { get { return vg; } set { if (vg.Set(value)) NotifyChanged("Vg"); } } protected override void Analyze(Analysis Mna, Expression Vpk, Expression Vgk, out Expression Ip, out Expression Ig) { Expression ex = Kp * (1.0 / Mu + Vgk * (Kvb + Vpk * Vpk) ^ (-0.5)); // ln(1+e^x) = x for large x, and large x causes numerical issues. Expression E1 = Call.If(ex > 5, ex, Call.Ln(1 + LinExp(ex))) * Vpk / Kp; Ip = Call.If(E1 > 0, (E1 ^ Ex) / Kg, 0); Ig = Call.If(Vgk > Vg, (Vgk - Vg) / Rgk, 0); } } }
mit
C#
0e8a87b6e2eb62be10e2108f981469b7ab265dec
Remove guitar model prop
michaelp0730/MichaelsMusic,michaelp0730/MichaelsMusic,michaelp0730/MichaelsMusic
MichaelsMusic/Models/Guitar.cs
MichaelsMusic/Models/Guitar.cs
namespace MichaelsMusic.Models { public class Guitar : Item { public string Binding { get; set; } public string BodyMaterial { get; set; } public string BodyStyle { get; set; } public string Bridge { get; set; } public string BridgePickup { get; set; } public string Capacitors { get; set; } public bool CarvedTop { get; set; } public bool CoilTap { get; set; } public string Controls { get; set; } public int? FingerboardRadius { get; set; } public string Finish { get; set; } public string Fretboard { get; set; } public int? Frets { get; set; } public string Fretwire { get; set; } public string Headstock { get; set; } public string InlayMaterial { get; set; } public string InlayShape { get; set; } public bool IsHardtail { get; set; } public string Knobs { get; set; } public string MiddlePickup { get; set; } public string NeckBinding { get; set; } public string NeckFinish { get; set; } public string NeckJoint { get; set; } public string NeckMaterial { get; set; } public string NeckPickup { get; set; } public string NeckShape { get; set; } public string Nut { get; set; } public string PickupSelector { get; set; } public string ScaleLength { get; set; } public int? Strings { get; set; } public string Tuners { get; set; } } }
namespace MichaelsMusic.Models { public class Guitar : Item { public string Binding { get; set; } public string BodyMaterial { get; set; } public string BodyStyle { get; set; } public string Bridge { get; set; } public string BridgePickup { get; set; } public string Capacitors { get; set; } public bool CarvedTop { get; set; } public bool CoilTap { get; set; } public string Controls { get; set; } public int? FingerboardRadius { get; set; } public string Finish { get; set; } public string Fretboard { get; set; } public int? Frets { get; set; } public string Fretwire { get; set; } public string Headstock { get; set; } public string InlayMaterial { get; set; } public string InlayShape { get; set; } public bool IsHardtail { get; set; } public bool IsTopJack { get; set; } public string Knobs { get; set; } public string MiddlePickup { get; set; } public string NeckBinding { get; set; } public string NeckFinish { get; set; } public string NeckJoint { get; set; } public string NeckMaterial { get; set; } public string NeckPickup { get; set; } public string NeckShape { get; set; } public string Nut { get; set; } public string PickupSelector { get; set; } public string ScaleLength { get; set; } public int? Strings { get; set; } public string Tuners { get; set; } } }
mit
C#
b3e59c10b8b8dd151f7b83d5cb02ee4223380b89
Update class documentation for keyboard constants.
CoraleStudios/Colore,danpierce1/Colore,WolfspiritM/Colore,Sharparam/Colore
Colore/Razer/Keyboard/Constants.cs
Colore/Razer/Keyboard/Constants.cs
// --------------------------------------------------------------------------------------- // <copyright file="Constants.cs" company=""> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees // and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility // for any harm caused, direct or indirect, to any Razer peripherals // via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore.Razer.Keyboard { /// <summary> /// Holds various keyboard constants used in Razer's API. /// </summary> public static class Constants { /// <summary> /// The maximum number of rows on the keyboard /// </summary> public static readonly Size MaxRows = 6; /// <summary> /// The maximum number of columns on the keyboard /// </summary> public static readonly Size MaxColumns = 22; /// <summary> /// The maximum number of keys on the keyboard /// </summary> public static readonly Size MaxKeys = MaxRows * MaxColumns; /// <summary> /// The maximum number of custom effects based on the maximum keys /// </summary> public static readonly Size MaxCustomEffects = MaxKeys; // <summary> // A grid representation of the keyboard // </summary> //Todo: Speak with Razer to implement //public static readonly Int32 RZKEY_GRID_LAYOUT[MAX_ROW][MAX_COLUMN] = {}; } }
// --------------------------------------------------------------------------------------- // <copyright file="Constants.cs" company=""> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees // and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility // for any harm caused, direct or indirect, to any Razer peripherals // via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore.Razer.Keyboard { /// <summary> /// The definitions of generic constant values used in the project /// </summary> public static class Constants { /// <summary> /// The maximum number of rows on the keyboard /// </summary> public static readonly Size MaxRows = 6; /// <summary> /// The maximum number of columns on the keyboard /// </summary> public static readonly Size MaxColumns = 22; /// <summary> /// The maximum number of keys on the keyboard /// </summary> public static readonly Size MaxKeys = MaxRows * MaxColumns; /// <summary> /// The maximum number of custom effects based on the maximum keys /// </summary> public static readonly Size MaxCustomEffects = MaxKeys; // <summary> // A grid representation of the keyboard // </summary> //Todo: Speak with Razer to implement //public static readonly Int32 RZKEY_GRID_LAYOUT[MAX_ROW][MAX_COLUMN] = {}; } }
mit
C#
27ce510fd3ad7c22cc0d21a0c1efa20cfe04d62e
remove obsolete warnings from usage.
Jaxelr/Nancy.Template.Webservice,Jaxelr/Nancy.Template.Webservice
Content/src/Modules/HelloModule.cs
Content/src/Modules/HelloModule.cs
using System.Diagnostics; using Nancy; using Nancy.Metadata.Modules; using Nancy.Metadata.OpenApi.Core; using Nancy.Metadata.OpenApi.Fluent; using Nancy.Template.WebService.Extensions; using Nancy.Template.WebService.Models.Entities; using Nancy.Template.WebService.Models.Operations; using Nancy.Template.WebService.Repositories; namespace Nancy.Template.WebService.Modules { public class SampleMetadataModule : MetadataModule<OpenApiRouteMetadata> { public SampleMetadataModule() { Describe[nameof(Hello)] = desc => new OpenApiRouteMetadata(desc) .With(i => i.WithResponseModel(HttpStatusCode.OK, typeof(HelloResponse), "Hello Response") .WithDescription("This operation returns the hello world message", tags: new string[] { "Hello" }) .WithResponseModel(HttpStatusCode.BadRequest, typeof(string), "Failed Validation Response") .WithRequestParameter("name", description: "A string to return as part of hello world", loc: Loc.Query, type: typeof(string))); } } public class SampleModule : NancyModule { private readonly Stopwatch watch; private readonly IHelloRepository repo; public SampleModule(Stopwatch watch, IHelloRepository repo) : base("api") { this.repo = repo; this.watch = watch; this.watch.Restart(); this.GetHandler<HelloRequest, HelloResponse>(nameof(Hello), HelloOp); } public HelloResponse HelloOp(HelloRequest user) => new HelloResponse { Response = repo.SayHello(user.Name) }; } }
using System.Diagnostics; using Nancy; using Nancy.Metadata.Modules; using Nancy.Metadata.OpenApi.Core; using Nancy.Metadata.OpenApi.Fluent; using Nancy.Template.WebService.Extensions; using Nancy.Template.WebService.Models.Entities; using Nancy.Template.WebService.Models.Operations; using Nancy.Template.WebService.Repositories; namespace Nancy.Template.WebService.Modules { public class SampleMetadataModule : MetadataModule<OpenApiRouteMetadata> { public SampleMetadataModule() { Describe[nameof(Hello)] = desc => new OpenApiRouteMetadata(desc) .With(i => i.WithResponseModel("200", typeof(HelloResponse), "Hello Response") .WithDescription("This operation returns the hello world message", tags: new string[] { "Hello" }) .WithResponseModel("400", typeof(string), "Failed Validation Response") .WithRequestParameter("name", description: "A string to return as part of hello world", loc: Loc.Query, type: typeof(string))); } } public class SampleModule : NancyModule { private readonly Stopwatch watch; private readonly IHelloRepository repo; public SampleModule(Stopwatch watch, IHelloRepository repo) : base("api") { this.repo = repo; this.watch = watch; this.watch.Restart(); this.GetHandler<HelloRequest, HelloResponse>(nameof(Hello), HelloOp); } public HelloResponse HelloOp(HelloRequest user) => new HelloResponse { Response = repo.SayHello(user.Name) }; } }
mit
C#
7a384ebd9ba441d23aa458268c78069ba1ca6f08
Bump version.
r3c/cottle,r3c/cottle
Cottle/Properties/AssemblyInfo.cs
Cottle/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle ("Cottle")] [assembly: AssemblyDescription ("Fast, lightweight &amp; extensible open-source template engine for any text-based target format (e.g. HTML, JavaScript, CSS, plain text...). Its mini-language supports text substitution, functions &amp; variables, flow control and more.")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Remi Caput")] [assembly: AssemblyProduct ("Cottle")] [assembly: AssemblyCopyright ("Copyright r3c 2014")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible (false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid ("1fb9a1d7-2971-4b15-a351-b889df3ae0aa")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.2")] [assembly: AssemblyFileVersion("1.4.0.2")]
using System.Reflection; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle ("Cottle")] [assembly: AssemblyDescription ("Fast, lightweight &amp; extensible open-source template engine for any text-based target format (e.g. HTML, JavaScript, CSS, plain text...). Its mini-language supports text substitution, functions &amp; variables, flow control and more.")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Remi Caput")] [assembly: AssemblyProduct ("Cottle")] [assembly: AssemblyCopyright ("Copyright r3c 2014")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible (false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid ("1fb9a1d7-2971-4b15-a351-b889df3ae0aa")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.1")] [assembly: AssemblyFileVersion("1.4.0.1")]
mit
C#
455b8a39351bdfcc2a74dca9938b81fab0ea7443
Sort SC constants.
PenguinF/sandra-three
Eutherion/Win/Native/Constants.cs
Eutherion/Win/Native/Constants.cs
#region License /********************************************************************************* * Constants.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion namespace Eutherion.Win.Native { /// <summary> /// Contains constants for results of the <see cref="WM.NCHITTEST"/> message. /// </summary> public static class HT { public const int CLIENT = 1; public const int CAPTION = 2; public const int LEFT = 10; public const int RIGHT = 11; public const int TOP = 12; public const int TOPLEFT = 13; public const int TOPRIGHT = 14; public const int BOTTOM = 15; public const int BOTTOMLEFT = 16; public const int BOTTOMRIGHT = 17; } /// <summary> /// Constains constants for native system commands, e.g. the WParam of the <see cref="WM.SYSCOMMAND"/> message. /// See also: https://docs.microsoft.com/en-us/windows/win32/menurc/wm-syscommand /// </summary> public static class SC { public const int MASK = 0xfff0; public const int MINIMIZE = 0xf020; public const int MAXIMIZE = 0xf030; public const int RESTORE = 0xf120; } /// <summary> /// Constains constants for the <see cref="NativeMethods.TrackPopupMenuEx"/> P/Invoke call. /// </summary> public static class TPM { public const uint RETURNCMD = 0x0100; public const uint LEFTBUTTON = 0x0; } /// <summary> /// Contains constants for native Windows messages. /// </summary> public static class WM { public const int QUERYOPEN = 0x13; public const int WINDOWPOSCHANGED = 0x47; public const int COPYDATA = 0x4A; public const int NCCALCSIZE = 0x83; public const int NCHITTEST = 0x84; public const int NCRBUTTONUP = 0xa5; public const int SYSCOMMAND = 0x0112; public const int SIZING = 0x214; public const int MOVING = 0x216; public const int DWMCOMPOSITIONCHANGED = 0x031e; } }
#region License /********************************************************************************* * Constants.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion namespace Eutherion.Win.Native { /// <summary> /// Contains constants for results of the <see cref="WM.NCHITTEST"/> message. /// </summary> public static class HT { public const int CLIENT = 1; public const int CAPTION = 2; public const int LEFT = 10; public const int RIGHT = 11; public const int TOP = 12; public const int TOPLEFT = 13; public const int TOPRIGHT = 14; public const int BOTTOM = 15; public const int BOTTOMLEFT = 16; public const int BOTTOMRIGHT = 17; } /// <summary> /// Constains constants for native system commands, e.g. the WParam of the <see cref="WM.SYSCOMMAND"/> message. /// </summary> public static class SC { public const int MASK = 0xfff0; public const int RESTORE = 0xf120; public const int MAXIMIZE = 0xf030; public const int MINIMIZE = 0xf020; } /// <summary> /// Constains constants for the <see cref="NativeMethods.TrackPopupMenuEx"/> P/Invoke call. /// </summary> public static class TPM { public const uint RETURNCMD = 0x0100; public const uint LEFTBUTTON = 0x0; } /// <summary> /// Contains constants for native Windows messages. /// </summary> public static class WM { public const int QUERYOPEN = 0x13; public const int WINDOWPOSCHANGED = 0x47; public const int COPYDATA = 0x4A; public const int NCCALCSIZE = 0x83; public const int NCHITTEST = 0x84; public const int NCRBUTTONUP = 0xa5; public const int SYSCOMMAND = 0x0112; public const int SIZING = 0x214; public const int MOVING = 0x216; public const int DWMCOMPOSITIONCHANGED = 0x031e; } }
apache-2.0
C#
cb73f867f383e9f546c7f3bd550ac45efa1792a7
fix typo
Fody/Fody,GeertvanHorrik/Fody
FodyCommon/ExceptionExtensions.cs
FodyCommon/ExceptionExtensions.cs
using System; using System.Text; public static class ExceptionExtensions { public static string ToFriendlyString(this Exception exception) { var stringBuilder = new StringBuilder(); stringBuilder.Append("An unhandled exception occurred:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append("Exception:"); stringBuilder.Append(Environment.NewLine); while (exception != null) { stringBuilder.Append(exception.Message); stringBuilder.Append(Environment.NewLine); stringBuilder.Append("Type:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append(exception.GetType().ToString()); stringBuilder.Append(Environment.NewLine); foreach (var i in exception.Data) { stringBuilder.Append("Data :"); stringBuilder.Append(i); stringBuilder.Append(Environment.NewLine); } if (exception.StackTrace != null) { stringBuilder.Append("StackTrace:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append(exception.StackTrace); stringBuilder.Append(Environment.NewLine); } if (exception.Source != null) { stringBuilder.Append("Source:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append(exception.Source); stringBuilder.Append(Environment.NewLine); } if (exception.TargetSite != null) { stringBuilder.Append("TargetSite:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append(exception.TargetSite); stringBuilder.Append(Environment.NewLine); } exception = exception.InnerException; } return stringBuilder.ToString(); } }
using System; using System.Text; public static class ExceptionExtensions { public static string ToFriendlyString(this Exception exception) { var stringBuilder = new StringBuilder(); stringBuilder.Append("An unhandled exception occurred:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append("Exception:"); stringBuilder.Append(Environment.NewLine); while (exception != null) { stringBuilder.Append(exception.Message); stringBuilder.Append(Environment.NewLine); stringBuilder.Append("Type:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append(exception.Type.ToString()); stringBuilder.Append(Environment.NewLine); foreach (var i in exception.Data) { stringBuilder.Append("Data :"); stringBuilder.Append(i); stringBuilder.Append(Environment.NewLine); } if (exception.StackTrace != null) { stringBuilder.Append("StackTrace:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append(exception.StackTrace); stringBuilder.Append(Environment.NewLine); } if (exception.Source != null) { stringBuilder.Append("Source:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append(exception.Source); stringBuilder.Append(Environment.NewLine); } if (exception.TargetSite != null) { stringBuilder.Append("TargetSite:"); stringBuilder.Append(Environment.NewLine); stringBuilder.Append(exception.TargetSite); stringBuilder.Append(Environment.NewLine); } exception = exception.InnerException; } return stringBuilder.ToString(); } }
mit
C#
523ac068f2b2295013d385bcc59bc3560c0bb9cd
Add inheit class 'AssuntoCursoUsuario'
fmassaretto/formacao-talentos,fmassaretto/formacao-talentos,fmassaretto/formacao-talentos
Fatec.Treinamento.Model/Assunto.cs
Fatec.Treinamento.Model/Assunto.cs
using Fatec.Treinamento.Model.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fatec.Treinamento.Model { public class Assunto : AssuntoCursoUsuario { public int Id { get; set; } public string Nome { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fatec.Treinamento.Model { public class Assunto { public int Id { get; set; } public string Nome { get; set; } } }
apache-2.0
C#
18908a0557bdb31a331d0f61a798113b26d0f948
Add a custom formatter to AboutMediaTypeFormatters.
panesofglass/WebApiKoans
Koans/AboutMediaTypeFormatters.cs
Koans/AboutMediaTypeFormatters.cs
using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Text; using System.Web.Http; using FSharpKoans.Core; namespace Koans { [Koan(Sort = 4)] public static partial class AboutMediaTypeFormatters { // JSON formatter // XML formatter // FormUrlEncoded formatter // Custom Formatter [Koan] public static void PlainTextFormatter() { var value = "This is a text/plain string."; var formatter = new PlainTextBufferedFormatter(); var content = new ObjectContent<string>(value, formatter); var result = content.ReadAsStringAsync().Result; Helpers.AssertEquality(Helpers.__, result); Helpers.AssertEquality("text/plain", content.Headers.ContentType.MediaType); Helpers.AssertEquality(Helpers.__, content.Headers.ContentLength); } } /// <summary> /// This sample formatter illustrates how to use the BufferedMediaTypeFormatter base class for /// writing a MediaTypeFormatter. The BufferedMediaTypeFormatter is useful when you either want /// to aggregate many small reads or writes or when you are writing synchronously to the underlying /// stream. /// </summary> public class PlainTextBufferedFormatter : BufferedMediaTypeFormatter { public PlainTextBufferedFormatter() { // Set supported media type for this media type formatter SupportedMediaTypes.Add(new MediaTypeHeaderValue(Helpers.__); // Set default supported character encodings for this media type formatter (UTF-8 and UTF-16) SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true)); } public override bool CanReadType(Type type) { return type == typeof(string); } public override bool CanWriteType(Type type) { return type == typeof(string); } public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) { // Get the preferred character encoding based on information in the request Encoding effectiveEncoding = SelectCharacterEncoding(content.Headers); // Create a stream reader and read the content synchronously using (StreamReader reader = new StreamReader(readStream, effectiveEncoding)) return reader.ReadToEnd(); } public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { // Get the preferred character encoding based on information in the request and what we support Encoding effectiveEncoding = SelectCharacterEncoding(content.Headers); // Create a stream writer and write the content synchronously using (StreamWriter writer = new StreamWriter(writeStream, effectiveEncoding)) writer.Write(value); } } public static partial class AboutMediaTypeFormatters { // Adding / Removing formatters } // Razor? }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FSharpKoans.Core; namespace Koans { [Koan(Sort = 4)] public static class AboutMediaTypeFormatters { // Custom Formatter // Adding / Removing formatters // Razor? } }
apache-2.0
C#
1d49c49c8dacb6f672488651f9928435fd9b85e5
add planId to the transaction table
ndrmc/cats,ndrmc/cats,ndrmc/cats
Models/Cats.Models/Transaction.cs
Models/Cats.Models/Transaction.cs
using System; using System.Collections.Generic; using Cats.Models; namespace Cats.Models { public partial class Transaction { public System.Guid TransactionID { get; set; } public Nullable<int> PartitionID { get; set; } public System.Guid TransactionGroupID { get; set; } public int LedgerID { get; set; } public Nullable<int> HubOwnerID { get; set; } public Nullable<int> AccountID { get; set; } public Nullable<int> HubID { get; set; } public Nullable<int> StoreID { get; set; } public Nullable<int> Stack { get; set; } public Nullable<int> ProjectCodeID { get; set; } public Nullable<int> ShippingInstructionID { get; set; } public int ProgramID { get; set; } public Nullable<int> ParentCommodityID { get; set; } public Nullable<int> CommodityID { get; set; } public Nullable<int> CommodityGradeID { get; set; } public decimal QuantityInMT { get; set; } public decimal QuantityInUnit { get; set; } public int UnitID { get; set; } public System.DateTime TransactionDate { get; set; } public Nullable<int> RegionID { get; set; } public Nullable<int> Month { get; set; } public Nullable<int> Round { get; set; } public Nullable<int> DonorID { get; set; } public Nullable<int> CommoditySourceID { get; set; } public Nullable<int> GiftTypeID { get; set; } public Nullable<int> FDPID { get; set; } public Nullable<int> TransactionType { get; set; } public Nullable<int> PlanId { get; set; } // public virtual Account Account { get; set; } //public virtual Commodity Commodity { get; set; } //public virtual Commodity Commodity1 { get; set; } // public virtual CommodityGrade CommodityGrade { get; set; } //public virtual Hub Hub { get; set; } // public virtual HubOwner HubOwner { get; set; } // public virtual Ledger Ledger { get; set; } //public virtual Program Program { get; set; } public virtual ProjectCode ProjectCode { get; set; } public virtual ShippingInstruction ShippingInstruction { get; set; } //public virtual Store Store { get; set; } public virtual TransactionGroup TransactionGroup { get; set; } public virtual Unit Unit { get; set; } } }
using System; using System.Collections.Generic; using Cats.Models; namespace Cats.Models { public partial class Transaction { public System.Guid TransactionID { get; set; } public Nullable<int> PartitionID { get; set; } public System.Guid TransactionGroupID { get; set; } public int LedgerID { get; set; } public Nullable<int> HubOwnerID { get; set; } public Nullable<int> AccountID { get; set; } public Nullable<int> HubID { get; set; } public Nullable<int> StoreID { get; set; } public Nullable<int> Stack { get; set; } public Nullable<int> ProjectCodeID { get; set; } public Nullable<int> ShippingInstructionID { get; set; } public int ProgramID { get; set; } public Nullable<int> ParentCommodityID { get; set; } public Nullable<int> CommodityID { get; set; } public Nullable<int> CommodityGradeID { get; set; } public decimal QuantityInMT { get; set; } public decimal QuantityInUnit { get; set; } public int UnitID { get; set; } public System.DateTime TransactionDate { get; set; } public Nullable<int> RegionID { get; set; } public Nullable<int> Month { get; set; } public Nullable<int> Round { get; set; } public Nullable<int> DonorID { get; set; } public Nullable<int> CommoditySourceID { get; set; } public Nullable<int> GiftTypeID { get; set; } public Nullable<int> FDPID { get; set; } public Nullable<int> TransactionType { get; set; } // public virtual Account Account { get; set; } //public virtual Commodity Commodity { get; set; } //public virtual Commodity Commodity1 { get; set; } // public virtual CommodityGrade CommodityGrade { get; set; } //public virtual Hub Hub { get; set; } // public virtual HubOwner HubOwner { get; set; } // public virtual Ledger Ledger { get; set; } //public virtual Program Program { get; set; } public virtual ProjectCode ProjectCode { get; set; } public virtual ShippingInstruction ShippingInstruction { get; set; } //public virtual Store Store { get; set; } public virtual TransactionGroup TransactionGroup { get; set; } public virtual Unit Unit { get; set; } } }
apache-2.0
C#
5ec3fa5bf4861fa26f7fdeeddec207e61855ca5a
Update Index.cshtml
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Home/Index.cshtml
Anlab.Mvc/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <h2 style="color: blue">PLEASE NOTE: There will be a modest increase in our rates effective in early October.</h2> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses. </p> <p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the operation of a number of analytical methods and instruments.</p> <p>Please Note: Dirk Holstege has recently retired as Laboratory Director of the UC Davis Analytical Laboratory. We thank him for his nearly twenty years of service as Director of the Analytical Lab and his thirty-two years of service as a UC Davis employee. We wish him all the best in his retirement.<br/> <br/> Traci Francis, Laboratory Supervisor, is serving as Interim Director. </p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> </address> </div>
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> @*<h2 style="color: blue">PLEASE NOTE: The Analytical Lab will be closed on July 4th and 5th.</h2>*@ <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses. </p> <p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the operation of a number of analytical methods and instruments.</p> <p>Please Note: Dirk Holstege has recently retired as Laboratory Director of the UC Davis Analytical Laboratory. We thank him for his nearly twenty years of service as Director of the Analytical Lab and his thirty-two years of service as a UC Davis employee. We wish him all the best in his retirement.<br/> <br/> Traci Francis, Laboratory Supervisor, is serving as Interim Director. </p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> </address> </div>
mit
C#
f1e4ed7e1bd0193d34e85b134428b849e846e3f1
Update AppConst.cs
Mikejinhua/UnitySocketProtobuf3Demo,Mikejinhua/UnitySocketProtobuf3Demo,Mikejinhua/UnitySocketProtobuf3Demo,Mikejinhua/UnitySocketProtobuf3Demo
Client/Assets/Scripts/AppConst.cs
Client/Assets/Scripts/AppConst.cs
using UnityEngine; using System.Collections; public class AppConst { public static int SocketPort = 3563; //Socket服务器端口 public static string SocketAddress = "127.0.0.1"; //Socket服务器地址 }
using UnityEngine; using System.Collections; public class AppConst { public static int SocketPort = 3563; //Socket服务器端口 public static string SocketAddress = "192.168.3.188"; //Socket服务器地址 }
mit
C#
55bea79f5c966cc508f47a2bbee12ca0cc9329c5
Add more usings to Sandbox
JohanLarsson/Gu.Roslyn.Asserts
Gu.Roslyn.Asserts.Tests/Sandbox.cs
Gu.Roslyn.Asserts.Tests/Sandbox.cs
// ReSharper disable UnusedVariable // ReSharper disable RedundantNameQualifier namespace Gu.Roslyn.Asserts.Tests { using System; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using NUnit.Framework; [Explicit("Sandbox")] public static class Sandbox { [TestCase(typeof(SyntaxTriviaList))] [TestCase(typeof(CSharpSyntaxNode))] [TestCase(typeof(CompilationUnitSyntax))] public static void FindReferences(Type type) { foreach (var assembly in type.Assembly.GetReferencedAssemblies()) { Console.WriteLine(assembly); } } [Test] public static void References() { var assembly = typeof(Sandbox).GetTypeInfo().Assembly; var referencedAssemblies = assembly.GetReferencedAssemblies(); } } }
// ReSharper disable UnusedVariable // ReSharper disable RedundantNameQualifier namespace Gu.Roslyn.Asserts.Tests { using System; using System.Reflection; using NUnit.Framework; [Explicit("Sandbox")] public static class Sandbox { [Test] public static void FindReferences() { foreach (var assembly in typeof(Sandbox).Assembly.GetReferencedAssemblies()) { Console.WriteLine(assembly); } } [Test] public static void References() { var assembly = typeof(Sandbox).GetTypeInfo().Assembly; var referencedAssemblies = assembly.GetReferencedAssemblies(); } } }
mit
C#
13254bcbd8104a3b8970d835451ef64de18cee10
Update Feature1.cs
ershadnozari/GitTest
ConsoleApp/ConsoleApp/Feature1.cs
ConsoleApp/ConsoleApp/Feature1.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp { class Feature1 { // Added code in VS // Added code in GitHub } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp { class Feature1 { // Added code in VS } }
mit
C#
161e8d75f44b96790c47c0ba2080518e22abe25d
Bump minor version due to public API change
dustyburwell/garlic
Garlic/Properties/AssemblyInfo.cs
Garlic/Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Garlic")] [assembly: AssemblyDescription("Google Analytics Client for .Net")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCompany("Dusty Burwell")] [assembly: AssemblyProduct("Garlic Google Analytics Client")] [assembly: AssemblyCopyright("Copyright © Dusty Burwell 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
using System.Reflection; [assembly: AssemblyTitle("Garlic")] [assembly: AssemblyDescription("Google Analytics Client for .Net")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCompany("Dusty Burwell")] [assembly: AssemblyProduct("Garlic Google Analytics Client")] [assembly: AssemblyCopyright("Copyright © Dusty Burwell 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("1.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")]
mit
C#
dfe407fda0dbf714d084ed843a2551a5a54e9bb6
change name of primary key
pashchuk/Hospital-MVVM-
Hospital/DesktopApp/Model/Note.cs
Hospital/DesktopApp/Model/Note.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesktopApp.Model { public class Note { #region Properties public int Id { get; set; } public string NoteText { get; set; } public DateTime Date { get; set; } #endregion #region Navigation Properties public virtual Doctor Doctor { get; set; } public virtual Card Card { get; set; } #endregion public Note() { Date = DateTime.Now; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesktopApp.Model { public class Note { #region Properties public int NoteId { get; set; } public string NoteText { get; set; } public DateTime Date { get; set; } #endregion #region Navigation Properties public virtual Doctor Doctor { get; set; } public virtual Card Card { get; set; } #endregion public Note() { Date = DateTime.Now; } } }
mit
C#
4fa3c87e7fb7ef16a1889a164e53fcd6718f9d60
Refactor long line
Sitecore/Sitecore-Instance-Manager
src/SIM.Tool.Base/AuthenticationHelper.cs
src/SIM.Tool.Base/AuthenticationHelper.cs
namespace SIM.Tool.Base { using System; using System.Threading; using System.Web; using System.Windows; using SIM.Instances; using Sitecore.Diagnostics.Base; using JetBrains.Annotations; using SIM.Core; using SIM.Extensions; public static class AuthenticationHelper { internal static void LoginAsAdmin([NotNull] Instance instance, [NotNull] Window owner, [CanBeNull] string pageUrl = null, [CanBeNull] string browser = null, [CanBeNull] string[] parameters = null) { Assert.ArgumentNotNull(instance, nameof(instance)); Assert.ArgumentNotNull(owner, nameof(owner)); if (!InstanceHelperEx.PreheatInstance(instance, owner)) { return; } // Generating unique url to authenticate user var url = CoreInstanceAuth.GenerateAuthUrl(); var destFileName = CoreInstanceAuth.CreateAuthFile(instance, url); // Schedule deletion of the file var async = new Action(() => DeleteFile(destFileName)); async.BeginInvoke(null, null); var userName = CoreAppSettings.AppLoginAsAdminUserName.Value; var isFrontEnd = false; var clipboard = pageUrl == "$(clipboard)"; if (clipboard) { pageUrl = string.Empty; } if (string.IsNullOrEmpty(pageUrl)) { var value = CoreAppSettings.AppLoginAsAdminPageUrl.Value; if (!string.IsNullOrEmpty(value) && !value.EqualsIgnoreCase("/sitecore") && !value.EqualsIgnoreCase("sitecore")) { pageUrl = value; if (!value.StartsWith("/sitecore/")) { isFrontEnd = true; } } } var querystring = ""; querystring += string.IsNullOrEmpty(pageUrl) ? string.Empty : "&page=" + pageUrl; querystring += string.IsNullOrEmpty(userName) || userName.EqualsIgnoreCase("admin") || userName.EqualsIgnoreCase("sitecore\\admin") ? string.Empty : "&user=" + HttpUtility.UrlEncode(userName); querystring = querystring.TrimStart('&'); if (!string.IsNullOrEmpty(querystring)) { querystring = "?" + querystring; } if (clipboard) { Clipboard.SetDataObject(instance.GetUrl(url + querystring)); } else { InstanceHelperEx.BrowseInstance(instance, owner, url + querystring, isFrontEnd, browser, parameters); } } private static void DeleteFile(string destFileName) { Thread.Sleep(CoreInstanceAuth.LifetimeSeconds * 1000); FileSystem.FileSystem.Local.File.Delete(destFileName); } } }
namespace SIM.Tool.Base { using System; using System.Threading; using System.Web; using System.Windows; using SIM.Instances; using Sitecore.Diagnostics.Base; using JetBrains.Annotations; using SIM.Core; using SIM.Extensions; public static class AuthenticationHelper { internal static void LoginAsAdmin([NotNull] Instance instance, [NotNull] Window owner, [CanBeNull] string pageUrl = null, [CanBeNull] string browser = null, [CanBeNull] string[] parameters = null) { Assert.ArgumentNotNull(instance, nameof(instance)); Assert.ArgumentNotNull(owner, nameof(owner)); if (!InstanceHelperEx.PreheatInstance(instance, owner)) { return; } // Generating unique url to authenticate user var url = CoreInstanceAuth.GenerateAuthUrl(); var destFileName = CoreInstanceAuth.CreateAuthFile(instance, url); // Schedule deletion of the file var async = new Action(() => DeleteFile(destFileName)); async.BeginInvoke(null, null); var userName = CoreAppSettings.AppLoginAsAdminUserName.Value; var isFrontEnd = false; var clipboard = pageUrl == "$(clipboard)"; if (clipboard) { pageUrl = string.Empty; } if (string.IsNullOrEmpty(pageUrl)) { var value = CoreAppSettings.AppLoginAsAdminPageUrl.Value; if (!string.IsNullOrEmpty(value) && !value.EqualsIgnoreCase("/sitecore") && !value.EqualsIgnoreCase("sitecore")) { pageUrl = value; if (!value.StartsWith("/sitecore/")) { isFrontEnd = true; } } } var querystring = (string.IsNullOrEmpty(pageUrl) ? string.Empty : "&page=" + pageUrl) + (string.IsNullOrEmpty(userName) || userName.EqualsIgnoreCase("admin") || userName.EqualsIgnoreCase("sitecore\\admin") ? string.Empty : "&user=" + HttpUtility.UrlEncode(userName)); querystring = querystring.TrimStart('&'); if (!string.IsNullOrEmpty(querystring)) { querystring = "?" + querystring; } if (clipboard) { Clipboard.SetDataObject(instance.GetUrl(url + querystring)); } else { InstanceHelperEx.BrowseInstance(instance, owner, url + querystring, isFrontEnd, browser, parameters); } } private static void DeleteFile(string destFileName) { Thread.Sleep(CoreInstanceAuth.LifetimeSeconds * 1000); FileSystem.FileSystem.Local.File.Delete(destFileName); } } }
mit
C#
814cafb7eb541a4080d6ac9e521f8ba2f39bf35b
Fix possible cause of null bytes in config file
canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor
src/SyncTrayzor/Utils/AtomicFileStream.cs
src/SyncTrayzor/Utils/AtomicFileStream.cs
using System; using System.IO; using System.Runtime.InteropServices; namespace SyncTrayzor.Utils { public class AtomicFileStream : FileStream { private const string DefaultTempFileSuffix = ".tmp"; private readonly string path; private readonly string tempPath; public AtomicFileStream(string path) : this(path, TempFilePath(path)) { } public AtomicFileStream(string path, string tempPath) : base(tempPath, FileMode.Create, FileAccess.ReadWrite) { this.path = path ?? throw new ArgumentNullException("path"); this.tempPath = tempPath ?? throw new ArgumentNullException("tempPath"); } private static string TempFilePath(string path) { return path + DefaultTempFileSuffix; } protected override void Dispose(bool disposing) { base.Dispose(disposing); bool success = NativeMethods.MoveFileEx(this.tempPath, this.path, MoveFileFlags.ReplaceExisting | MoveFileFlags.WriteThrough); if (!success) Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); } [Flags] private enum MoveFileFlags { None = 0, ReplaceExisting = 1, CopyAllowed = 2, DelayUntilReboot = 4, WriteThrough = 8, CreateHardlink = 16, FailIfNotTrackable = 32, } private static class NativeMethods { [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool MoveFileEx( [In] string lpExistingFileName, [In] string lpNewFileName, [In] MoveFileFlags dwFlags); } } }
using System; using System.IO; using System.Runtime.InteropServices; namespace SyncTrayzor.Utils { public class AtomicFileStream : FileStream { private const string DefaultTempFileSuffix = ".tmp"; private readonly string path; private readonly string tempPath; public AtomicFileStream(string path) : this(path, TempFilePath(path)) { } public AtomicFileStream(string path, string tempPath) : base(tempPath, FileMode.Create, FileAccess.ReadWrite) { this.path = path ?? throw new ArgumentNullException("path"); this.tempPath = tempPath ?? throw new ArgumentNullException("tempPath"); } private static string TempFilePath(string path) { return path + DefaultTempFileSuffix; } public override void Close() { base.Close(); bool success = NativeMethods.MoveFileEx(this.tempPath, this.path, MoveFileFlags.ReplaceExisting | MoveFileFlags.WriteThrough); if (!success) Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error()); } [Flags] private enum MoveFileFlags { None = 0, ReplaceExisting = 1, CopyAllowed = 2, DelayUntilReboot = 4, WriteThrough = 8, CreateHardlink = 16, FailIfNotTrackable = 32, } private static class NativeMethods { [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool MoveFileEx( [In] string lpExistingFileName, [In] string lpNewFileName, [In] MoveFileFlags dwFlags); } } }
mit
C#
2e5832e01273499099bba3890f3f30fb613ae950
update version number
AMVSoftware/NSaga
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")] [assembly: AssemblyInformationalVersion("1.1.1+2.Branch.master.Sha.25d0abd7591766e152a1b7c418fb8e9a395eea03")]
using System.Reflection; [assembly: AssemblyVersion("1.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")] [assembly: AssemblyInformationalVersion("1.1.1-DotnetVersion.1+1.Branch.DotnetVersion.Sha.fba8c84a3df1c7f3007b43101b7d646630e866c2")]
mit
C#
6cc486a2e935ba8beabda7c528eb7b9369d00859
Switch to version 1.2.2-new-subs01
AtwooTM/Zebus,biarne-a/Zebus,Abc-Arbitrage/Zebus,rbouallou/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.2.2")] [assembly: AssemblyFileVersion("1.2.2")] [assembly: AssemblyInformationalVersion("1.2.2-new-subs01")]
using System.Reflection; [assembly: AssemblyVersion("1.2.13")] [assembly: AssemblyFileVersion("1.2.13")] [assembly: AssemblyInformationalVersion("1.2.13")]
mit
C#
db7123bbb24afe84e32baf5e408c0afe01ab87fd
Update DownloadTest.cs
gregyjames/OctaneDownloader
OctaneTestProject/DownloadTest.cs
OctaneTestProject/DownloadTest.cs
using System.IO; using NUnit.Framework; using OctaneEngine; namespace OctaneTestProject { [TestFixture] public class DownloadTest { [SetUp] public void Init() { } [TearDown] public void CleanUp() { File.Delete("Chershire_Cat.24ee16b9.png"); } [Test] public void DownloadFile() { var url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png"; var outFile = "Chershire_Cat.24ee16b9.png"; Engine.DownloadFile(url, 4, 256, false,outFile, b => { if (b) { Assert.IsTrue(File.Exists(outFile)); } }).Wait(); } } }
using System.IO; using NUnit.Framework; using OctaneEngine; namespace OctaneTestProject { [TestFixture] public class DownloadTest { [SetUp] public void Init() { } [TearDown] public void CleanUp() { File.Delete("Chershire_Cat.24ee16b9.jpeg"); } [Test] public void DownloadFile() { var url = "http://ipv4.download.thinkbroadband.com/5MB.zip"; var outFile = "Chershire_Cat.24ee16b9.jpeg"; Engine.DownloadFile(url, 4, 256, false,outFile, b => { if (b) { Assert.IsTrue(File.Exists(outFile)); } }).Wait(); } } }
mit
C#
b21eaad1fb5cf45705d4f6c4f7ff10528110a403
Test erroroutput tweak
stilldesign/PhysX.Net,stilldesign/PhysX.Net,danteinforno/PhysX.Net,stilldesign/PhysX.Net,danteinforno/PhysX.Net,danteinforno/PhysX.Net
PhysX.Net-3.0/Test/ErrorOutput.cs
PhysX.Net-3.0/Test/ErrorOutput.cs
using System; using System.Collections.Generic; using System.Linq; namespace PhysX.Test { public class ErrorLog : PhysX.ErrorCallback { private List<string> _errors; public ErrorLog() { _errors = new List<string>(); } public override void ReportError(ErrorCode errorCode, string message, string file, int lineNumber) { _errors.Add(string.Format("Code: {0}, Message: {1}", errorCode, message)); } public override string ToString() { if (_errors.Count == 0) return "No errors"; else return string.Format("{0} errors. Last error: {1}", _errors.Count, _errors[_errors.Count - 1]); } } }
using System; using System.Collections.Generic; using System.Linq; namespace PhysX.Test { public class ErrorLog : PhysX.ErrorCallback { private List<string> _errors; public ErrorLog() { _errors = new List<string>(); } public override void ReportError(ErrorCode errorCode, string message, string file, int lineNumber) { _errors.Add(string.Format("Code: {0}, Message: {1}", errorCode, message)); } } }
mit
C#
c90a246e6b0bab1d4190cd3ab11601f36b6f633b
Update Win32 Console Blink
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
NET/Demos/Console/Blink/Program.cs
NET/Demos/Console/Blink/Program.cs
using System; using Treehopper; using System.Threading.Tasks; using Treehopper.Libraries; using System.Diagnostics; using System.Collections.Generic; namespace Blink { /// <summary> /// This demo blinks the built-in LED using basic procedural programming. /// </summary> /// <remarks> /// <para> /// This example illustrates how to work with Treehopper boards procedurally to blink an LED. /// </para> /// </remarks> class Program { static void Main(string[] args) { RunBlink().Wait(); } static async Task RunBlink() { while(true) { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. TreehopperUsb Board = await ConnectionService.Instance.First(); Console.WriteLine("Found board: " + Board); // You must explicitly open a board before communicating with it await Board.Connect(); while(Board.IsConnected) { // toggle the LED Board.Led = !Board.Led; // wait 500 ms await Task.Delay(500); } // We arrive here when the board has been disconnected Console.WriteLine("Board has been disconnected."); } } } }
using System; using Treehopper; using System.Threading.Tasks; using Treehopper.Libraries; using System.Diagnostics; using System.Collections.Generic; namespace Blink { /// <summary> /// This demo blinks an LED attached to pin 1, using basic procedural programming. /// </summary> /// <remarks> /// <para> /// Treehopper provides an asynchronous, event-driven API that helps your apps respond to plug / unplug detection. /// While this is the recommended way of working with TreehopperUsb references, many users new to C# and high-level languages /// in general may be uncomfortable with event-driven programming. To learn more about asynchronous usage, check out the /// BlinkEventDriven example. /// </para> /// <para> /// This example illustrates how to work with Treehopper boards procedurally to blink an LED. /// </para> /// </remarks> class Program { static void Main(string[] args) { RunBlink(); } static async void RunBlink() { while(true) { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. TreehopperUsb Board = await ConnectionService.Instance.First(); Console.WriteLine("Found board: " + Board); // You must explicitly open a board before communicating with it await Board.Connect(); Board.Pins[0].Mode = PinMode.PushPullOutput; while(true) { //Board.Led = !Board.Led; Board.Pins[0].DigitalValue = !Board.Pins[0].DigitalValue; await Task.Delay(1000); } // We arrive here when the board has been disconnected Console.WriteLine("Board has been disconnected."); } } } }
mit
C#
a8f67e58088e06be3df6df51f35551d85db1f7f9
Apply policy when loading reflection only assemblys
PMudra/ApiCheck
ApiCheck/Loader/AssemblyLoader.cs
ApiCheck/Loader/AssemblyLoader.cs
using System; using System.IO; using System.Reflection; namespace ApiCheck.Loader { public sealed class AssemblyLoader : IDisposable { public AssemblyLoader() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnReflectionOnlyAssemblyResolve; } public void Dispose() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomainOnReflectionOnlyAssemblyResolve; } private Assembly CurrentDomainOnReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = new AssemblyName(args.Name); string path = Path.Combine(Path.GetDirectoryName(args.RequestingAssembly.Location), assemblyName.Name + ".dll"); if (File.Exists(path)) { return Assembly.ReflectionOnlyLoadFrom(path); } return Assembly.ReflectionOnlyLoad(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } public Assembly ReflectionOnlyLoad(string path) { return Assembly.ReflectionOnlyLoadFrom(path); } } }
using System; using System.IO; using System.Reflection; namespace ApiCheck.Loader { public sealed class AssemblyLoader : IDisposable { public AssemblyLoader() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomainOnReflectionOnlyAssemblyResolve; } public void Dispose() { AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomainOnReflectionOnlyAssemblyResolve; } private Assembly CurrentDomainOnReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = new AssemblyName(args.Name); string path = Path.Combine(Path.GetDirectoryName(args.RequestingAssembly.Location), assemblyName.Name + ".dll"); if (File.Exists(path)) { return Assembly.ReflectionOnlyLoadFrom(path); } return Assembly.ReflectionOnlyLoad(args.Name); } public Assembly ReflectionOnlyLoad(string path) { return Assembly.ReflectionOnlyLoadFrom(path); } } }
mit
C#
1dea048ed692994d4a3c40e9b6d8b99b48da350f
Add NotNull attributes
IronLanguages/ironpython3,IronLanguages/ironpython3,IronLanguages/ironpython3,IronLanguages/ironpython3,IronLanguages/ironpython3,IronLanguages/ironpython3
Src/IronPython.Modules/audioop.cs
Src/IronPython.Modules/audioop.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #nullable enable using System.Runtime.CompilerServices; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Types; using NotNullOnReturnAttribute = System.Diagnostics.CodeAnalysis.NotNullAttribute; using NotNullAttribute = Microsoft.Scripting.Runtime.NotNullAttribute; [assembly: PythonModule("audioop", typeof(IronPython.Modules.PythonAudioOp))] namespace IronPython.Modules { public static class PythonAudioOp { [SpecialName] public static void PerformModuleReload([NotNullOnReturn] PythonContext/*!*/ context, [NotNullOnReturn] PythonDictionary/*!*/ dict) { context.EnsureModuleException("audiooperror", dict, "error", "audioop"); } private static PythonType error(CodeContext/*!*/ context) => (PythonType)context.LanguageContext.GetModuleState("audiooperror"); public static Bytes byteswap(CodeContext/*!*/ context, [NotNull] IBufferProtocol fragment, int width) { if (width < 1 || width > 4) { throw PythonExceptions.CreateThrowable(error(context), "Size should be 1, 2, 3 or 4"); } using var buffer = fragment.GetBuffer(); if (buffer.NumBytes() % width != 0) { throw PythonExceptions.CreateThrowable(error(context), "not a whole number of frames"); } var array = buffer.ToArray(); if (width == 2) { for (var i = 0; i < array.Length; i += width) { array.ByteSwap(i, i + 1); } } else if (width == 3) { for (var i = 0; i < array.Length; i += width) { array.ByteSwap(i, i + 2); } } else if (width == 4) { for (var i = 0; i < array.Length; i += width) { array.ByteSwap(i, i + 3); array.ByteSwap(i + 1, i + 2); } } return Bytes.Make(array); } private static void ByteSwap(this byte[] array, int i, int j) { var tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #nullable enable using System.Runtime.CompilerServices; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Types; using NotNullAttribute = Microsoft.Scripting.Runtime.NotNullAttribute; [assembly: PythonModule("audioop", typeof(IronPython.Modules.PythonAudioOp))] namespace IronPython.Modules { public static class PythonAudioOp { [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.EnsureModuleException("audiooperror", dict, "error", "audioop"); } private static PythonType error(CodeContext/*!*/ context) => (PythonType)context.LanguageContext.GetModuleState("audiooperror"); public static Bytes byteswap(CodeContext/*!*/ context, [NotNull] IBufferProtocol fragment, int width) { if (width < 1 || width > 4) { throw PythonExceptions.CreateThrowable(error(context), "Size should be 1, 2, 3 or 4"); } using var buffer = fragment.GetBuffer(); if (buffer.NumBytes() % width != 0) { throw PythonExceptions.CreateThrowable(error(context), "not a whole number of frames"); } var array = buffer.ToArray(); if (width == 2) { for (var i = 0; i < array.Length; i += width) { array.ByteSwap(i, i + 1); } } else if (width == 3) { for (var i = 0; i < array.Length; i += width) { array.ByteSwap(i, i + 2); } } else if (width == 4) { for (var i = 0; i < array.Length; i += width) { array.ByteSwap(i, i + 3); array.ByteSwap(i + 1, i + 2); } } return Bytes.Make(array); } private static void ByteSwap(this byte[] array, int i, int j) { var tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } }
apache-2.0
C#
eb829a9276058401ab6dbc2b27aa2afcf10be1b1
Use single arrow character for backspace.
mrward/xamarin-calculator
Calculator.Droid/ButtonAdapter.cs
Calculator.Droid/ButtonAdapter.cs
 using Android.Content; using Android.Views; using Android.Widget; namespace Calculator.Droid { public class ButtonAdapter : BaseAdapter { Context context; string[] buttons = new string[] { "←", "C", "±", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "0", ".", null, "=" }; public ButtonAdapter (Context context) { this.context = context; } public override Java.Lang.Object GetItem (int position) { return null; } public override long GetItemId (int position) { return 0; } public override View GetView (int position, View convertView, ViewGroup parent) { Button button = null; string text = buttons [position]; if (convertView != null) { button = (Button)convertView; } else { button = new Button (context); } if (text != null) { button.Text = text; } else { button.Visibility = ViewStates.Invisible; } return button; } public override int Count { get { return buttons.Length; } } } }
 using Android.Content; using Android.Views; using Android.Widget; namespace Calculator.Droid { public class ButtonAdapter : BaseAdapter { Context context; string[] buttons = new string[] { "<-", "C", "±", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "0", ".", null, "=" }; public ButtonAdapter (Context context) { this.context = context; } public override Java.Lang.Object GetItem (int position) { return null; } public override long GetItemId (int position) { return 0; } public override View GetView (int position, View convertView, ViewGroup parent) { Button button = null; string text = buttons [position]; if (convertView != null) { button = (Button)convertView; } else { button = new Button (context); } if (text != null) { button.Text = text; } else { button.Visibility = ViewStates.Invisible; } return button; } public override int Count { get { return buttons.Length; } } } }
mit
C#
d586dc36d4b1a94fa3bd96f59b6aa4031e28d07f
change validation code a little, nothing major
ahives/HareDu,ahives/HareDu
src/HareDu/Arg.cs
src/HareDu/Arg.cs
// Copyright 2012-2013 Albert L. Hives, Chris Patterson, et al. // // 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 HareDu { using System; internal class Arg { public static void Validate(string value, string paramName, Action logging) { if (string.IsNullOrWhiteSpace(value)) { if (!logging.IsNull()) logging(); throw new ArgumentException(string.Format("{0} is null, empty, or consists of all whitespaces", paramName)); } } public static void Validate<T>(T value, string paramName) where T : class { if (value.IsNull()) throw new ArgumentNullException(paramName); } } }
// Copyright 2012-2013 Albert L. Hives, Chris Patterson, et al. // // 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 HareDu { using System; internal class Arg { public static void Validate(string value, string paramName, Action logging) { if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value)) { if (!logging.IsNull()) logging(); throw new ArgumentException(string.Format("{0} is null, empty, or consists of all whitespaces", paramName)); } } public static void Validate<T>(T value, string paramName) where T : class { if (value.IsNull()) throw new ArgumentNullException(paramName); } } }
apache-2.0
C#
29aecbda6043e9d8526c3f2e249efa6739f01c30
Add threading to test server
mono/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,openmedicus/dbus-sharp,arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,arfbtwn/dbus-sharp
src/TestServer.cs
src/TestServer.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using NDesk.DBus; using org.freedesktop.DBus; using System.IO; using System.Net; using System.Net.Sockets; using Mono.Unix; using System.Threading; public class TestServer { //TODO: complete this test daemon/server example, and a client //TODO: maybe generalise it and integrate it into the core public static void Main (string[] args) { bool isServer; if (args.Length == 1 && args[0] == "server") isServer = true; else if (args.Length == 1 && args[0] == "client") isServer = false; else { Console.Error.WriteLine ("Usage: test-server [server|client]"); return; } string addr = "unix:abstract=/tmp/dbus-ABCDEFGHIJ"; Connection conn; ObjectPath myOpath = new ObjectPath ("/test"); string myNameReq = "org.ndesk.test"; if (!isServer) { conn = new Connection (false); conn.Open (addr); DemoObject demo = conn.GetObject<DemoObject> (myNameReq, myOpath); //float ret = demo.Hello ("hi from test client", 21); float ret = 200; while (ret > 5) { ret = demo.Hello ("hi from test client", (int)ret); Console.WriteLine ("Returned float: " + ret); System.Threading.Thread.Sleep (1000); } } else { string path; bool abstr; Address.Parse (addr, out path, out abstr); AbstractUnixEndPoint ep = new AbstractUnixEndPoint (path); Socket server = new Socket (AddressFamily.Unix, SocketType.Stream, 0); server.Bind (ep); //server.Listen (1); server.Listen (5); while (true) { Console.WriteLine ("Waiting for client on " + addr); Socket client = server.Accept (); Console.WriteLine ("Client accepted"); //this might well be wrong, untested and doesn't yet work here onwards conn = new Connection (false); //conn.Open (path, @abstract); conn.sock = client; conn.sock.Blocking = true; conn.ns = new NetworkStream (conn.sock); //ConnectionHandler.Handle (conn); //in reality a thread per connection is of course too expensive ConnectionHandler hnd = new ConnectionHandler (conn); new Thread (new ThreadStart (hnd.Handle)).Start (); Console.WriteLine (); } } } } public class ConnectionHandler { protected Connection conn; public ConnectionHandler (Connection conn) { this.conn = conn; } public void Handle () { ConnectionHandler.Handle (conn); } public static void Handle (Connection conn) { //Connection.tmpConn = conn; DemoObject demo = new DemoObject (); conn.Marshal (demo, "org.ndesk.test"); //TODO: handle lost connections etc. properly instead of stupido try/catch try { while (true) conn.Iterate (); } catch (Exception e) { //Console.Error.WriteLine (e); } } } [Interface ("org.ndesk.test")] public class DemoObject : MarshalByRefObject { public float Hello (string arg0, int arg1) { Console.WriteLine ("Got a Hello(" + arg0 + ", " + arg1 +")"); return (float)arg1/2; } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using NDesk.DBus; using org.freedesktop.DBus; using System.IO; using System.Net; using System.Net.Sockets; using Mono.Unix; public class TestServer { //TODO: complete this test daemon/server example, and a client //TODO: maybe generalise it and integrate it into the core public static void Main (string[] args) { bool isServer; if (args.Length == 1 && args[0] == "server") isServer = true; else if (args.Length == 1 && args[0] == "client") isServer = false; else { Console.Error.WriteLine ("Usage: test-server [server|client]"); return; } string addr = "unix:abstract=/tmp/dbus-ABCDEFGHIJ"; Connection conn; DemoObject demo; ObjectPath myOpath = new ObjectPath ("/test"); string myNameReq = "org.ndesk.test"; if (!isServer) { conn = new Connection (false); conn.Open (addr); demo = conn.GetObject<DemoObject> (myNameReq, myOpath); float ret = demo.Hello ("hi from test client", 21); Console.WriteLine ("Returned float: " + ret); } else { string path; bool abstr; Address.Parse (addr, out path, out abstr); AbstractUnixEndPoint ep = new AbstractUnixEndPoint (path); Socket server = new Socket (AddressFamily.Unix, SocketType.Stream, 0); server.Bind (ep); server.Listen (1); Console.WriteLine ("Waiting for client on " + addr); Socket client = server.Accept (); Console.WriteLine ("Client accepted"); //this might well be wrong, untested and doesn't yet work here onwards conn = new Connection (false); //conn.Open (path, @abstract); conn.sock = client; conn.sock.Blocking = true; conn.ns = new NetworkStream (conn.sock); Connection.tmpConn = conn; demo = new DemoObject (); conn.Marshal (demo, "org.ndesk.test"); //TODO: handle lost connections etc. while (true) conn.Iterate (); } } } [Interface ("org.ndesk.test")] public class DemoObject : MarshalByRefObject { public float Hello (string arg0, int arg1) { Console.WriteLine ("Got a Hello(" + arg0 + ", " + arg1 +")"); return (float)arg1/2; } }
mit
C#
36305b7423f2d87cb65bd1cf16d13cc4eca1f25a
Bump Assembly version
msarchet/Imager
Imager/Properties/AssemblyInfo.cs
Imager/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("Imager")] [assembly: AssemblyDescription("A library for generating test images")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Imager")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("98006566-32fd-4b6d-9d44-041a654e56d8")] // 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("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.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("Imager")] [assembly: AssemblyDescription("A library for generating test images")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Imager")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("98006566-32fd-4b6d-9d44-041a654e56d8")] // 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("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
188474b6f9fc9398faa533ddaacbcaa3be43b571
Update AndroidAttitudeProbe.cs
predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus
Sensus.Android.Shared/Probes/Movement/AndroidAttitudeProbe.cs
Sensus.Android.Shared/Probes/Movement/AndroidAttitudeProbe.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Android.Hardware; using Sensus.Probes.Movement; namespace Sensus.Android.Probes.Movement { class AndroidAttitudeProbe : AttitudeProbe { private AndroidSensorListener _attitudeListener; public AndroidAttitudeProbe() { _attitudeListener = new AndroidSensorListener(SensorType.RotationVector, async e => { // should get x, y,z, w values await StoreDatumAsync(new AttitudeDatum(DateTimeOffset.UtcNow, e.Values[0], e.Values[1], e.Values[2], e.Values[3])); }); } protected override async Task InitializeAsync() { await base.InitializeAsync(); _attitudeListener.Initialize(MinDataStoreDelay); } protected override async Task StartListeningAsync() { await base.StartListeningAsync(); } protected override async Task StopListeningAsync() { await base.StopListeningAsync(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Android.Hardware; using Sensus.Probes.Movement; namespace Sensus.Android.Probes.Movement { class AndroidAttitudeProbe : AttitudeProbe { private AndroidSensorListener _attitudeListener; public AndroidAttitudeProbe() { _attitudeListener = new AndroidSensorListener(SensorType.RotationVector, async e => { // should get x, y,z, w values await StoreDatumAsync(new AttitudeDatum(DateTimeOffset.UtcNow, e.Values[0], e.Values[1], e.Values[2], e.Values[3])); }); } protected override async Task InitializeAsync() { await base.InitializeAsync(); _attitudeListener.Initialize(MinDataStoreDelay); } protected override async Task StartListeningAsync() { await base.StartListeningAsync(); } protected override async Task StopListeningAsync() { await base.StopListeningAsync(); } } }
apache-2.0
C#
5fc45187d20a47207ed3630587ec30526479a117
Add default values to APP trending data folder paths
GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA
Source/Libraries/openXDA.Configuration/TrendingDataSection.cs
Source/Libraries/openXDA.Configuration/TrendingDataSection.cs
//****************************************************************************************************** // TrendingDataSection.cs - Gbtc // // Copyright © 2022, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 08/26/2022 - Stephen C. Wills // Generated original version of source code. // //****************************************************************************************************** using System.ComponentModel; using System.Configuration; namespace openXDA.Configuration { public class TrendingDataSection { #region [ Members ] // Nested Types public class RMSSubSection { [Setting] [DefaultValue(@"Trms.dat")] public string FolderPath { get; set; } } public class FlickerSubSection { [Setting] [DefaultValue(@"FkrR[0-9]*\.dat")] public string FolderPath { get; set; } } public class TriggerSubSection { [Setting] [DefaultValue(@"TrR[0-9]*\.dat")] public string FolderPath { get; set; } } // Constants public const string CategoryName = "TrendingData"; #endregion #region [ Properties ] /// <summary> /// Gets RMS folder path settings. /// </summary> [Category] public RMSSubSection RMS { get; } = new RMSSubSection(); /// <summary> /// Gets flicker folder path settings. /// </summary> [Category] public FlickerSubSection Flicker { get; } = new FlickerSubSection(); /// <summary> /// Gets trigger folder path settings. /// </summary> [Category] public TriggerSubSection Trigger { get; } = new TriggerSubSection(); #endregion } }
//****************************************************************************************************** // TrendingDataSection.cs - Gbtc // // Copyright © 2022, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 08/26/2022 - Stephen C. Wills // Generated original version of source code. // //****************************************************************************************************** using System.ComponentModel; using System.Configuration; namespace openXDA.Configuration { public class TrendingDataSection { #region [ Members ] // Nested Types public class SubSection { [Setting] [DefaultValue("")] public string FolderPath { get; set; } } // Constants public const string CategoryName = "TrendingData"; #endregion #region [ Properties ] /// <summary> /// Gets RMS folder path settings. /// </summary> [Category] public SubSection RMS { get; } = new SubSection(); /// <summary> /// Gets flicker folder path settings. /// </summary> [Category] public SubSection Flicker { get; } = new SubSection(); /// <summary> /// Gets trigger folder path settings. /// </summary> [Category] public SubSection Trigger { get; } = new SubSection(); #endregion } }
mit
C#
a338d06aedb68f967b30dd54dea58e357c445bc7
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.35.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.34.*")]
mit
C#
ff93de86929a0635a2b56af793d2776ce94871eb
apply ToStringMembers()
TakeAsh/cs-WpfUtility
WpfUtility/DataGridExAttribute.cs
WpfUtility/DataGridExAttribute.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TakeAshUtility; namespace WpfUtility { [AttributeUsage(AttributeTargets.Property)] public class DataGridExAttribute : Attribute { public DataGridExAttribute() { } public DataGridExAttribute(string header) { Header = header; } [ToStringMember] public string Header { get; set; } [ToStringMember] public bool Ignore { get; set; } [ToStringMember] public string StringFormat { get; set; } public override string ToString() { return this.ToStringMembers(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WpfUtility { [AttributeUsage(AttributeTargets.Property)] public class DataGridExAttribute : Attribute { public DataGridExAttribute() { } public DataGridExAttribute(string header) { Header = header; } public string Header { get; set; } public bool Ignore { get; set; } public string StringFormat { get; set; } public override string ToString() { return String.Join(", ", new[] { "Header:{" + Header + "}", "Ignore:" + Ignore, "StringFormat:{" + StringFormat + "}", }); } } }
mit
C#
85d4e91a70d08343e2b4fdd2828b987c1d2de55b
Update assembly info
Deadpikle/NetSparkle,Deadpikle/NetSparkle
AssemblyInfo.cs
AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NetSparkle")] [assembly: AssemblyDescription("NetSparkle is an auto update framework for .NET developers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NetSparkle")] [assembly: AssemblyCopyright("Portions Copyright © Dirk Eisenberg 2010, Deadpikle 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("279448fc-5103-475e-b209-68f3268df7b5")] // 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("0.10.0")] [assembly: AssemblyFileVersion("0.10.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("NetSparkle")] [assembly: AssemblyDescription("NetSparkle is an auto update framework for .NET developers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NetSparkle")] [assembly: AssemblyCopyright("Portions Copyright © Dirk Eisenberg 2010")] [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("7891583a-a852-4093-9774-3518ed86c978")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0")] [assembly: AssemblyFileVersion("1.2.0")]
mit
C#
a74f099203dd2670a167f17acf2aaabb32df56f9
Reset score to 500
sundbe10/GGJ17
Assets/GameManager.cs
Assets/GameManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameManager : Singleton<GameManager> { enum State{ ACTIVE, ENDED } State _state = State.ACTIVE; public static int score = 500; public static bool gameActive = true; GameObject[] players; // Use this for initialization void Start () { players = GameObject.FindGameObjectsWithTag("Player"); Debug.Log(players[0]); } // Update is called once per frame void Update () { switch(_state){ case State.ACTIVE: CheckScores(); break; case State.ENDED: if (Input.GetButton("Submit")) SceneManager.LoadScene("Scenes/Main"); break; } } void CheckScores(){ foreach(GameObject player in players){ if(player.GetComponentInChildren<ScoreManager>().score > score){ EndGame(player); } } } void EndGame(GameObject winner){ gameActive = false; _state = State.ENDED; foreach(GameObject player in players){ player.GetComponentsInChildren<PlayerScript>()[0].SetAI(); } WanderingCamera cameraWander = GameObject.Find("CameraWander").GetComponent<WanderingCamera>(); cameraWander.enabled = true; var lookTarget = GameObject.Find("Look Target").transform; lookTarget.position = winner.transform.Find("body_components/base").transform.position + Vector3.up*2; GameObject.Find("Winner").GetComponent<Image>().enabled = true; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameManager : Singleton<GameManager> { enum State{ ACTIVE, ENDED } State _state = State.ACTIVE; public static int score = 20; public static bool gameActive = true; GameObject[] players; // Use this for initialization void Start () { players = GameObject.FindGameObjectsWithTag("Player"); Debug.Log(players[0]); } // Update is called once per frame void Update () { switch(_state){ case State.ACTIVE: CheckScores(); break; case State.ENDED: if (Input.GetButton("Submit")) SceneManager.LoadScene("Scenes/Main"); break; } } void CheckScores(){ foreach(GameObject player in players){ if(player.GetComponentInChildren<ScoreManager>().score > score){ EndGame(player); } } } void EndGame(GameObject winner){ gameActive = false; _state = State.ENDED; foreach(GameObject player in players){ player.GetComponentsInChildren<PlayerScript>()[0].SetAI(); } WanderingCamera cameraWander = GameObject.Find("CameraWander").GetComponent<WanderingCamera>(); cameraWander.enabled = true; var lookTarget = GameObject.Find("Look Target").transform; lookTarget.position = winner.transform.Find("body_components/base").transform.position + Vector3.up*2; GameObject.Find("Winner").GetComponent<Image>().enabled = true; } }
mit
C#
0a09b70c9de3f2be6fca21d9cb97401e6efcee89
Disable maximum request body size
FubarDevelopment/WebDavServer,FubarDevelopment/WebDavServer,FubarDevelopment/WebDavServer
sample/FubarDev.WebDavServer.Sample.AspNetCore/Program.cs
sample/FubarDev.WebDavServer.Sample.AspNetCore/Program.cs
using System; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.HttpSys; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace FubarDev.WebDavServer.Sample.AspNetCore { public class Program { public static bool IsKestrel { get; private set; } public static bool DisableBasicAuth { get; private set; } public static bool IsWindows => Environment.OSVersion.Platform == PlatformID.Win32NT; public static void Main(string[] args) { BuildWebHost(args).Run(); } private static IWebHost BuildWebHost(string[] args) { var tempHost = BuildWebHost(args, whb => whb); var config = tempHost.Services.GetRequiredService<IConfiguration>(); DisableBasicAuth = config.GetValue<bool>("disable-basic-auth"); return BuildWebHost( args, builder => ConfigureHosting(builder, config)); } private static IWebHost BuildWebHost(string[] args, Func<IWebHostBuilder, IWebHostBuilder> customConfig) => customConfig(WebHost.CreateDefaultBuilder(args)) .UseStartup<Startup>() .Build(); private static IWebHostBuilder ConfigureHosting(IWebHostBuilder builder, IConfiguration configuration) { var forceKestrelUse = configuration.GetValue<bool>("use-kestrel"); if (!forceKestrelUse && IsWindows) { builder = builder .UseHttpSys( opt => { opt.Authentication.Schemes = AuthenticationSchemes.NTLM; opt.Authentication.AllowAnonymous = true; opt.MaxRequestBodySize = null; }); } else { IsKestrel = true; builder = builder .UseKestrel( opt => { opt.Limits.MaxRequestBodySize = null; }); } return builder; } } }
using System; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.HttpSys; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace FubarDev.WebDavServer.Sample.AspNetCore { public class Program { public static bool IsKestrel { get; private set; } public static bool DisableBasicAuth { get; private set; } public static bool IsWindows => Environment.OSVersion.Platform == PlatformID.Win32NT; public static void Main(string[] args) { BuildWebHost(args).Run(); } private static IWebHost BuildWebHost(string[] args) { var tempHost = BuildWebHost(args, whb => whb); var config = tempHost.Services.GetRequiredService<IConfiguration>(); DisableBasicAuth = config.GetValue<bool>("disable-basic-auth"); return BuildWebHost( args, builder => ConfigureHosting(builder, config)); } private static IWebHost BuildWebHost(string[] args, Func<IWebHostBuilder, IWebHostBuilder> customConfig) => customConfig(WebHost.CreateDefaultBuilder(args)) .UseStartup<Startup>() .Build(); private static IWebHostBuilder ConfigureHosting(IWebHostBuilder builder, IConfiguration configuration) { var forceKestrelUse = configuration.GetValue<bool>("use-kestrel"); if (!forceKestrelUse && IsWindows) { builder = builder .UseHttpSys( opt => { opt.Authentication.Schemes = AuthenticationSchemes.NTLM; opt.Authentication.AllowAnonymous = true; }); } else { IsKestrel = true; } return builder; } } }
mit
C#
6d0e80254ea157732e40d66ed41d7f204c4cd26e
Add missing ArgumentNullException
tgstation/tgstation-server,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Host/Security/IdentityCacheObject.cs
src/Tgstation.Server.Host/Security/IdentityCacheObject.cs
using System; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.Core; namespace Tgstation.Server.Host.Security { /// <summary> /// For keeping a specific <see cref="ISystemIdentity"/> alive for a period of time /// </summary> sealed class IdentityCacheObject : IDisposable { /// <summary> /// The <see cref="ISystemIdentity"/> the <see cref="IdentityCache"/> manages /// </summary> public ISystemIdentity SystemIdentity { get; } /// <summary> /// The <see cref="cancellationTokenSource"/> for the <see cref="IdentityCache"/> /// </summary> readonly CancellationTokenSource cancellationTokenSource; /// <summary> /// The <see cref="Task"/> to clean up <see cref="SystemIdentity"/> /// </summary> readonly Task task; /// <summary> /// Construct an <see cref="IdentityCache"/> /// </summary> /// <param name="systemIdentity">The value of <see cref="SystemIdentity"/></param> /// <param name="asyncDelayer">The <see cref="IAsyncDelayer"/> used to delay the expiry</param> /// <param name="onExpiry">The <see cref="Action"/> to take on expiry</param> /// <param name="expiry">The <see cref="DateTimeOffset"/></param> public IdentityCacheObject(ISystemIdentity systemIdentity, IAsyncDelayer asyncDelayer, Action onExpiry, DateTimeOffset expiry) { SystemIdentity = systemIdentity ?? throw new ArgumentNullException(nameof(systemIdentity)); if (asyncDelayer == null) throw new ArgumentNullException(nameof(asyncDelayer)); if (onExpiry == null) throw new ArgumentNullException(nameof(onExpiry)); var now = DateTimeOffset.Now; if (expiry < now) throw new ArgumentOutOfRangeException(nameof(expiry), expiry, "expiry must be greater than DateTimeOffset.Now!"); cancellationTokenSource = new CancellationTokenSource(); async Task DisposeOnExipiry(CancellationToken cancellationToken) { using (SystemIdentity) try { await asyncDelayer.Delay(expiry - now, cancellationToken).ConfigureAwait(false); } finally { onExpiry(); } } task = DisposeOnExipiry(cancellationTokenSource.Token); } /// <inheritdoc /> public void Dispose() { cancellationTokenSource.Cancel(); try { task.GetAwaiter().GetResult(); } catch (OperationCanceledException) { } cancellationTokenSource.Dispose(); } } }
using System; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.Core; namespace Tgstation.Server.Host.Security { /// <summary> /// For keeping a specific <see cref="ISystemIdentity"/> alive for a period of time /// </summary> sealed class IdentityCacheObject : IDisposable { /// <summary> /// The <see cref="ISystemIdentity"/> the <see cref="IdentityCache"/> manages /// </summary> public ISystemIdentity SystemIdentity { get; } /// <summary> /// The <see cref="cancellationTokenSource"/> for the <see cref="IdentityCache"/> /// </summary> readonly CancellationTokenSource cancellationTokenSource; /// <summary> /// The <see cref="Task"/> to clean up <see cref="SystemIdentity"/> /// </summary> readonly Task task; /// <summary> /// Construct an <see cref="IdentityCache"/> /// </summary> /// <param name="systemIdentity">The value of <see cref="SystemIdentity"/></param> /// <param name="asyncDelayer">The <see cref="IAsyncDelayer"/> used to delay the expiry</param> /// <param name="onExpiry">The <see cref="Action"/> to take on expiry</param> /// <param name="expiry">The <see cref="DateTimeOffset"/></param> public IdentityCacheObject(ISystemIdentity systemIdentity, IAsyncDelayer asyncDelayer, Action onExpiry, DateTimeOffset expiry) { SystemIdentity = systemIdentity ?? throw new ArgumentNullException(nameof(systemIdentity)); if (onExpiry == null) throw new ArgumentNullException(nameof(onExpiry)); var now = DateTimeOffset.Now; if (expiry < now) throw new ArgumentOutOfRangeException(nameof(expiry), expiry, "expiry must be greater than DateTimeOffset.Now!"); cancellationTokenSource = new CancellationTokenSource(); async Task DisposeOnExipiry(CancellationToken cancellationToken) { using (SystemIdentity) try { await asyncDelayer.Delay(expiry - now, cancellationToken).ConfigureAwait(false); } finally { onExpiry(); } } task = DisposeOnExipiry(cancellationTokenSource.Token); } /// <inheritdoc /> public void Dispose() { cancellationTokenSource.Cancel(); try { task.GetAwaiter().GetResult(); } catch (OperationCanceledException) { } cancellationTokenSource.Dispose(); } } }
agpl-3.0
C#
b430cf34e73760e136cebc4f87045826b76557be
remove unfnished comment.
smoogipoo/osu,2yangk23/osu,DrabWeb/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,EVAST9919/osu,naoey/osu,johnneijzen/osu,peppy/osu,naoey/osu,naoey/osu,UselessToucan/osu,EVAST9919/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu-new,2yangk23/osu,NeoAdonis/osu,DrabWeb/osu,DrabWeb/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,ZLima12/osu,ppy/osu
build.cake
build.cake
#addin "nuget:?package=CodeFileSanity" #addin "nuget:?package=JetBrains.ReSharper.CommandLineTools" #tool "nuget:?package=NVika.MSBuild" #tool "nuget:?package=NuGet.CommandLine" /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var framework = Argument("framework", "netcoreapp2.1"); var configuration = Argument("configuration", "Release"); var osuDesktop = new FilePath("./osu.Desktop/osu.Desktop.csproj"); var osuSolution = new FilePath("./osu.sln"); var testProjects = GetFiles("**/*.Tests.csproj"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Compile") .Does(() => { DotNetCoreBuild(osuDesktop.FullPath, new DotNetCoreBuildSettings { Framework = framework, Configuration = configuration }); }); Task("Test") .ContinueOnError() .DoesForEach(testProjects, testProject => { DotNetCoreTest(testProject.FullPath, new DotNetCoreTestSettings { Framework = framework, Configuration = configuration, Logger = $"trx;LogFileName={testProject.GetFilename()}.trx", ResultsDirectory = "./TestResults/" }); }); // windows only because both inspectcore and nvike depend on net45 Task("InspectCode") .WithCriteria(IsRunningOnWindows()) .IsDependentOn("Compile") .Does(() => { var NVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); var NugetToolPath = GetFiles("./tools/NuGet.CommandLine.*/tools/NuGet.exe").First(); StartProcess(NugetToolPath, $"restore {osuSolution}"); InspectCode(osuSolution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); StartProcess(NVikaToolPath, @"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = ".", IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
#addin "nuget:?package=CodeFileSanity" #addin "nuget:?package=JetBrains.ReSharper.CommandLineTools" #tool "nuget:?package=NVika.MSBuild" #tool "nuget:?package=NuGet.CommandLine" /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var framework = Argument("framework", "netcoreapp2.1"); var configuration = Argument("configuration", "Release"); var osuDesktop = new FilePath("./osu.Desktop/osu.Desktop.csproj"); var osuSolution = new FilePath("./osu.sln"); var testProjects = GetFiles("**/*.Tests.csproj"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Compile") .Does(() => { DotNetCoreBuild(osuDesktop.FullPath, new DotNetCoreBuildSettings { Framework = framework, Configuration = configuration }); }); Task("Test") .ContinueOnError() .DoesForEach(testProjects, testProject => { DotNetCoreTest(testProject.FullPath, new DotNetCoreTestSettings { Framework = framework, Configuration = configuration, Logger = $"trx;LogFileName={testProject.GetFilename()}.trx", ResultsDirectory = "./TestResults/" }); }); // windows only because both inspectcore and nvike depend on net45 // will be ignored on linux Task("InspectCode") .WithCriteria(IsRunningOnWindows()) .IsDependentOn("Compile") .Does(() => { var NVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); var NugetToolPath = GetFiles("./tools/NuGet.CommandLine.*/tools/NuGet.exe").First(); StartProcess(NugetToolPath, $"restore {osuSolution}"); InspectCode(osuSolution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); StartProcess(NVikaToolPath, @"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = ".", IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
mit
C#
796f9a400985c9ebcafd10fdf82fdd4ff71851f8
Fix comment
Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module
Drivers/ManagePersonsPermissionCheckerTaskDisplayDriver.cs
Drivers/ManagePersonsPermissionCheckerTaskDisplayDriver.cs
using Lombiq.TrainingDemo.Activities; using Lombiq.TrainingDemo.ViewModels; using OrchardCore.Workflows.Display; using OrchardCore.Workflows.Models; namespace Lombiq.TrainingDemo.Drivers; // ActivityDisplayDriver is specifically for implementing Workflow Activity Tasks. // Don't forget to register this class with the service provider (see: Startup.cs). public class ManagePersonsPermissionCheckerTaskDisplayDriver : ActivityDisplayDriver<ManagePersonsPermissionCheckerTask, ManagePersonsPermissionCheckerTaskViewModel> { protected override void EditActivity( ManagePersonsPermissionCheckerTask activity, ManagePersonsPermissionCheckerTaskViewModel model) => model.UserName = activity.UserName.Expression; protected override void UpdateActivity( ManagePersonsPermissionCheckerTaskViewModel model, ManagePersonsPermissionCheckerTask activity) => activity.UserName = new WorkflowExpression<string>(model.UserName); }
using Lombiq.TrainingDemo.Activities; using Lombiq.TrainingDemo.ViewModels; using OrchardCore.Workflows.Display; using OrchardCore.Workflows.Models; namespace Lombiq.TrainingDemo.Drivers; // ActivityDisplayDrivers are specifically for implementing Workflow Activity Tasks. // Don't forget to register this class with the service provider (see: Startup.cs). public class ManagePersonsPermissionCheckerTaskDisplayDriver : ActivityDisplayDriver<ManagePersonsPermissionCheckerTask, ManagePersonsPermissionCheckerTaskViewModel> { protected override void EditActivity( ManagePersonsPermissionCheckerTask activity, ManagePersonsPermissionCheckerTaskViewModel model) => model.UserName = activity.UserName.Expression; protected override void UpdateActivity( ManagePersonsPermissionCheckerTaskViewModel model, ManagePersonsPermissionCheckerTask activity) => activity.UserName = new WorkflowExpression<string>(model.UserName); }
bsd-3-clause
C#
8824e0756465be09a594318a732f5f4e498d045d
Fix missing lines in WasapiRecorder
sndnv/noisecluster,sndnv/noisecluster,sndnv/noisecluster,sndnv/noisecluster
noisecluster-win/noisecluster/audio/capture/WasapiRecorder.cs
noisecluster-win/noisecluster/audio/capture/WasapiRecorder.cs
/** * Copyright 2017 https://github.com/sndnv * * 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 CSCore; using CSCore.SoundIn; using CSCore.Streams; namespace noisecluster.audio.capture { public class WasapiRecorder //TODO - make disposable? { private bool isRunning = false; //TODO - atomic? private WasapiCapture capture; private SoundInSource soundInSource; private IWaveSource convertedSource; private WasapiDataHandler dataHandler; private byte[] dataBuffer; public WasapiRecorder(WasapiDataHandler handler) { capture = new WasapiLoopbackCapture(); capture.Initialize(); soundInSource = new SoundInSource(capture) {FillWithZeros = false}; convertedSource = soundInSource //.ChangeSampleRate(48000) //TODO - ? .ToSampleSource() .ToWaveSource(16) //TODO - ? .ToStereo(); dataHandler = handler; dataBuffer = new byte[convertedSource.WaveFormat.BytesPerSecond]; soundInSource.DataAvailable += (sender, e) => { int read, total = 0; while ((read = convertedSource.Read(dataBuffer, 0, dataBuffer.Length)) > 0) { total += read; } dataHandler(dataBuffer, total); //TODO - safe to pass byte[] ? }; } public bool IsActive { get { return true; } //TODO } public void Start() { //TODO - log capture.Start(); } public void Stop() { //TODO - log capture.Stop(); } public delegate void WasapiDataHandler(byte[] data, int length); } }
/** * Copyright 2017 https://github.com/sndnv * * 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 CSCore; using CSCore.SoundIn; using CSCore.Streams; namespace noisecluster.audio.capture { { private WasapiCapture capture; private SoundInSource soundInSource; private IWaveSource convertedSource; private WasapiDataHandler dataHandler; private byte[] dataBuffer; public WasapiRecorder(WasapiDataHandler handler) { capture = new WasapiLoopbackCapture(); capture.Initialize(); soundInSource = new SoundInSource(capture) {FillWithZeros = false}; convertedSource = soundInSource //.ChangeSampleRate(48000) //TODO - ? .ToSampleSource() .ToWaveSource(16) //TODO - ? .ToStereo(); dataHandler = handler; dataBuffer = new byte[convertedSource.WaveFormat.BytesPerSecond]; soundInSource.DataAvailable += (sender, e) => { int read, total = 0; while ((read = convertedSource.Read(dataBuffer, 0, dataBuffer.Length)) > 0) { total += read; } dataHandler(dataBuffer, total); //TODO - safe to pass byte[] ? }; } public bool IsActive { get { return true; } //TODO } public void Start() { //TODO - log capture.Start(); } public void Stop() { //TODO - log capture.Stop(); } public delegate void WasapiDataHandler(byte[] data, int length); } }
apache-2.0
C#
43332674268836363a173af43337f46e1a544db7
Fix Prerendered test to actually dispose of AgateSetup when it exits.
eylvisaker/AgateLib
Tests/DisplayTests/Prerendered.cs
Tests/DisplayTests/Prerendered.cs
using System; using System.Collections.Generic; using AgateLib; using AgateLib.DisplayLib; using AgateLib.Geometry; using AgateLib.InputLib; namespace Tests.DisplayTests { class PrerenderedTest : IAgateTest { public string Name { get { return "Prerendering"; } } public string Category { get { return "Display"; } } public void Main(string[] args) { using (AgateSetup setup = new AgateSetup()) { setup.AskUser = true; setup.Initialize(true, false, true); if (setup.WasCanceled) return; DisplayWindow MainWindow = DisplayWindow.CreateWindowed("Test", 800, 600); FrameBuffer myBuffer = new FrameBuffer(200, 35); FontSurface font = FontSurface.AgateSans10; Display.RenderTarget = myBuffer; Display.BeginFrame(); Display.Clear(Color.Blue); font.Color = Color.Red; font.DrawText(3, 3, "HELLO WORLD"); Display.EndFrame(); Display.FlushDrawBuffer(); Display.RenderTarget = MainWindow.FrameBuffer; while (MainWindow.IsClosed == false) { Display.BeginFrame(); Display.Clear(Color.Black); myBuffer.RenderTarget.Draw(35, 35); font.DrawText(38, 73, "HELLO WORLD"); Display.EndFrame(); Core.KeepAlive(); } } } } }
using System; using System.Collections.Generic; using AgateLib; using AgateLib.DisplayLib; using AgateLib.Geometry; using AgateLib.InputLib; namespace Tests.DisplayTests { class PrerenderedTest : IAgateTest { public string Name { get { return "Prerendering"; } } public string Category { get { return "Display"; } } public void Main(string[] args) { AgateSetup AS = new AgateSetup(); AS.AskUser = true; AS.Initialize(true, false, true); if (AS.WasCanceled) return; DisplayWindow MainWindow = DisplayWindow.CreateWindowed ("Test", 800, 600); FrameBuffer myBuffer = new FrameBuffer(200,35); FontSurface font = FontSurface.AgateSans10; Display.RenderTarget = myBuffer; Display.BeginFrame(); Display.Clear(Color.Blue); font.Color = Color.Red; font.DrawText(3,3 , "HELLO WORLD"); Display.EndFrame(); Display.FlushDrawBuffer(); Display.RenderTarget = MainWindow.FrameBuffer; while (MainWindow.IsClosed == false) { Display.BeginFrame(); Display.Clear(Color.Black); myBuffer.RenderTarget.Draw(35,35); Display.EndFrame(); Core.KeepAlive(); } } } }
mit
C#
da5f2113d8a6cf5d629461c15ac58457dcf1bc7d
use Require.NotNull in Base58Alphabet
ssg/SimpleBase,ssg/SimpleBase32,ssg/SimpleBase
src/Base58Alphabet.cs
src/Base58Alphabet.cs
/* Copyright 2014-2016 Sedat Kapanoglu 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; namespace SimpleBase { public sealed class Base58Alphabet { public const int Length = 58; public string Value { get; private set; } public Base58Alphabet(string text) { Require.NotNull(text, "text"); if (text.Length != Length) { throw new ArgumentException("Base58 alphabets need to be 58-characters long", "text"); } this.Value = text; } public override string ToString() { return Value; } } }
using System; namespace SimpleBase { public sealed class Base58Alphabet { public const int Length = 58; public string Value { get; private set; } public Base58Alphabet(string text) { if (text == null) { throw new ArgumentNullException("text"); } if (text.Length != Length) { throw new ArgumentException("Base58 alphabets need to be 58-characters long", "text"); } this.Value = text; } public override string ToString() { return Value; } } }
apache-2.0
C#
addb1d197a66e6839e2ee7a1c9813880793cacbc
Tweak Crc32 comments.
drebrez/DiscUtils,breezechen/DiscUtils,breezechen/DiscUtils,quamotion/discutils
src/Crc32Algorithm.cs
src/Crc32Algorithm.cs
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils { internal enum Crc32Algorithm { /// <summary> /// Used in Ethernet, PKZIP, BZIP2, Gzip, PNG, etc. (aka CRC32) /// </summary> Common = 0, /// <summary> /// Used in iSCSI, SCTP, Btrfs, Vhdx. (aka CRC32C) /// </summary> Castagnoli = 1, /// <summary> /// Unknown usage. (aka CRC32K) /// </summary> Koopman = 2, /// <summary> /// Used in AIXM. (aka CRC32Q) /// </summary> Aeronautical = 3 } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils { internal enum Crc32Algorithm { /// <summary> /// Used in Ethernet, PKZIP, BZIP2, Gzip, PNG, etc. /// </summary> Common = 0, /// <summary> /// Used in iSCSI, SCTP, Btrfs, Vhdx. /// </summary> Castagnoli = 1, /// <summary> /// Unknown usage. /// </summary> Koopman = 2, /// <summary> /// Used in AIXM. /// </summary> Aeronautical = 3 } }
mit
C#
e9a36d6cbe8fda2a7b17b1410eac7a7b92537337
change ip block to 4 hours
bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core
src/Core/Services/Implementations/AzureQueueBlockIpService.cs
src/Core/Services/Implementations/AzureQueueBlockIpService.cs
using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using System; namespace Bit.Core.Services { public class AzureQueueBlockIpService : IBlockIpService { private readonly CloudQueue _blockIpQueue; private readonly CloudQueue _unblockIpQueue; private bool _didInit = false; public AzureQueueBlockIpService( GlobalSettings globalSettings) { var storageAccount = CloudStorageAccount.Parse(globalSettings.Storage.ConnectionString); var queueClient = storageAccount.CreateCloudQueueClient(); _blockIpQueue = queueClient.GetQueueReference("blockip"); _unblockIpQueue = queueClient.GetQueueReference("unblockip"); } public async Task BlockIpAsync(string ipAddress, bool permanentBlock) { await InitAsync(); var message = new CloudQueueMessage(ipAddress); await _blockIpQueue.AddMessageAsync(message); if(!permanentBlock) { await _unblockIpQueue.AddMessageAsync(message, null, new TimeSpan(4, 0, 0), null, null); } } private async Task InitAsync() { if(_didInit) { return; } await _blockIpQueue.CreateIfNotExistsAsync(); await _unblockIpQueue.CreateIfNotExistsAsync(); _didInit = true; } } }
using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using System; namespace Bit.Core.Services { public class AzureQueueBlockIpService : IBlockIpService { private readonly CloudQueue _blockIpQueue; private readonly CloudQueue _unblockIpQueue; private bool _didInit = false; public AzureQueueBlockIpService( GlobalSettings globalSettings) { var storageAccount = CloudStorageAccount.Parse(globalSettings.Storage.ConnectionString); var queueClient = storageAccount.CreateCloudQueueClient(); _blockIpQueue = queueClient.GetQueueReference("blockip"); _unblockIpQueue = queueClient.GetQueueReference("unblockip"); } public async Task BlockIpAsync(string ipAddress, bool permanentBlock) { await InitAsync(); var message = new CloudQueueMessage(ipAddress); await _blockIpQueue.AddMessageAsync(message); if(!permanentBlock) { await _unblockIpQueue.AddMessageAsync(message, null, new TimeSpan(12, 0, 0), null, null); } } private async Task InitAsync() { if(_didInit) { return; } await _blockIpQueue.CreateIfNotExistsAsync(); await _unblockIpQueue.CreateIfNotExistsAsync(); _didInit = true; } } }
agpl-3.0
C#
5b24a580d65272e7e29723d1665eb608dc973e8e
Fix the GC total memory test.
ruben-ayrapetyan/coreclr,qiudesong/coreclr,wateret/coreclr,yeaicc/coreclr,AlexGhiondea/coreclr,cydhaselton/coreclr,James-Ko/coreclr,alexperovich/coreclr,krytarowski/coreclr,alexperovich/coreclr,cmckinsey/coreclr,pgavlin/coreclr,neurospeech/coreclr,yeaicc/coreclr,rartemev/coreclr,neurospeech/coreclr,pgavlin/coreclr,tijoytom/coreclr,YongseopKim/coreclr,cmckinsey/coreclr,russellhadley/coreclr,sagood/coreclr,sjsinju/coreclr,sagood/coreclr,russellhadley/coreclr,wtgodbe/coreclr,JonHanna/coreclr,kyulee1/coreclr,hseok-oh/coreclr,mskvortsov/coreclr,russellhadley/coreclr,alexperovich/coreclr,YongseopKim/coreclr,JosephTremoulet/coreclr,mskvortsov/coreclr,ruben-ayrapetyan/coreclr,gkhanna79/coreclr,mmitche/coreclr,gkhanna79/coreclr,rartemev/coreclr,AlexGhiondea/coreclr,mmitche/coreclr,yeaicc/coreclr,rartemev/coreclr,mmitche/coreclr,parjong/coreclr,qiudesong/coreclr,neurospeech/coreclr,yeaicc/coreclr,sagood/coreclr,dpodder/coreclr,ragmani/coreclr,ragmani/coreclr,yeaicc/coreclr,neurospeech/coreclr,ruben-ayrapetyan/coreclr,dpodder/coreclr,wateret/coreclr,yizhang82/coreclr,ragmani/coreclr,qiudesong/coreclr,cydhaselton/coreclr,poizan42/coreclr,krk/coreclr,russellhadley/coreclr,yeaicc/coreclr,James-Ko/coreclr,sjsinju/coreclr,sagood/coreclr,tijoytom/coreclr,krytarowski/coreclr,ruben-ayrapetyan/coreclr,mskvortsov/coreclr,jamesqo/coreclr,cshung/coreclr,krk/coreclr,cshung/coreclr,parjong/coreclr,yizhang82/coreclr,kyulee1/coreclr,mskvortsov/coreclr,poizan42/coreclr,JonHanna/coreclr,mmitche/coreclr,mmitche/coreclr,yizhang82/coreclr,wtgodbe/coreclr,JonHanna/coreclr,parjong/coreclr,sjsinju/coreclr,mskvortsov/coreclr,rartemev/coreclr,cydhaselton/coreclr,botaberg/coreclr,jamesqo/coreclr,mmitche/coreclr,krk/coreclr,cmckinsey/coreclr,botaberg/coreclr,cmckinsey/coreclr,kyulee1/coreclr,jamesqo/coreclr,parjong/coreclr,ragmani/coreclr,wtgodbe/coreclr,pgavlin/coreclr,qiudesong/coreclr,hseok-oh/coreclr,krytarowski/coreclr,cydhaselton/coreclr,jamesqo/coreclr,botaberg/coreclr,mskvortsov/coreclr,sjsinju/coreclr,jamesqo/coreclr,tijoytom/coreclr,hseok-oh/coreclr,wateret/coreclr,AlexGhiondea/coreclr,poizan42/coreclr,YongseopKim/coreclr,poizan42/coreclr,botaberg/coreclr,cshung/coreclr,yeaicc/coreclr,tijoytom/coreclr,wateret/coreclr,rartemev/coreclr,JosephTremoulet/coreclr,kyulee1/coreclr,AlexGhiondea/coreclr,dpodder/coreclr,parjong/coreclr,dpodder/coreclr,parjong/coreclr,pgavlin/coreclr,cshung/coreclr,gkhanna79/coreclr,cmckinsey/coreclr,JonHanna/coreclr,krytarowski/coreclr,wateret/coreclr,JosephTremoulet/coreclr,cydhaselton/coreclr,alexperovich/coreclr,krytarowski/coreclr,James-Ko/coreclr,JosephTremoulet/coreclr,neurospeech/coreclr,cshung/coreclr,botaberg/coreclr,ragmani/coreclr,cydhaselton/coreclr,yizhang82/coreclr,dpodder/coreclr,jamesqo/coreclr,krk/coreclr,krk/coreclr,JonHanna/coreclr,wtgodbe/coreclr,kyulee1/coreclr,sagood/coreclr,sjsinju/coreclr,pgavlin/coreclr,James-Ko/coreclr,AlexGhiondea/coreclr,JosephTremoulet/coreclr,wateret/coreclr,qiudesong/coreclr,hseok-oh/coreclr,poizan42/coreclr,tijoytom/coreclr,James-Ko/coreclr,cmckinsey/coreclr,sagood/coreclr,JonHanna/coreclr,JosephTremoulet/coreclr,AlexGhiondea/coreclr,botaberg/coreclr,James-Ko/coreclr,krk/coreclr,sjsinju/coreclr,russellhadley/coreclr,hseok-oh/coreclr,ruben-ayrapetyan/coreclr,yizhang82/coreclr,tijoytom/coreclr,YongseopKim/coreclr,YongseopKim/coreclr,ragmani/coreclr,ruben-ayrapetyan/coreclr,alexperovich/coreclr,dpodder/coreclr,cmckinsey/coreclr,cshung/coreclr,krytarowski/coreclr,gkhanna79/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,gkhanna79/coreclr,poizan42/coreclr,neurospeech/coreclr,alexperovich/coreclr,rartemev/coreclr,hseok-oh/coreclr,gkhanna79/coreclr,russellhadley/coreclr,pgavlin/coreclr,kyulee1/coreclr,qiudesong/coreclr,YongseopKim/coreclr,yizhang82/coreclr
tests/src/GC/API/GC/TotalMemory.cs
tests/src/GC/API/GC/TotalMemory.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. // Tests GC.TotalMemory using System; public class Test { public static int Main() { GC.Collect(); GC.Collect(); int[] array1 = new int[20000]; int memold = (int) GC.GetTotalMemory(false); Console.WriteLine("Total Memory: " + memold); array1=null; GC.Collect(); int[] array2 = new int[40000]; int memnew = (int) GC.GetTotalMemory(false); Console.WriteLine("Total Memory: " + memnew); GC.KeepAlive(array2); if(memnew >= memold) { Console.WriteLine("Test for GC.TotalMemory passed!"); return 100; } else { Console.WriteLine("Test for GC.TotalMemory failed!"); return 1; } } }
// 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. // Tests GC.TotalMemory using System; public class Test { public static int Main() { GC.Collect(); GC.Collect(); int[] array1 = new int[20000]; int memold = (int) GC.GetTotalMemory(false); Console.WriteLine("Total Memory: " + memold); array1=null; GC.Collect(); int[] array2 = new int[40000]; int memnew = (int) GC.GetTotalMemory(false); Console.WriteLine("Total Memory: " + memnew); if(memnew >= memold) { Console.WriteLine("Test for GC.TotalMemory passed!"); return 100; } else { Console.WriteLine("Test for GC.TotalMemory failed!"); return 1; } } }
mit
C#
7e61669f56ec3b7d80d4838fbf8f9b696ff3a5a8
Add some Menu docs
mminns/xwt,sevoku/xwt,hwthomas/xwt,iainx/xwt,akrisiun/xwt,directhex/xwt,mono/xwt,TheBrainTech/xwt,antmicro/xwt,residuum/xwt,hamekoz/xwt,steffenWi/xwt,mminns/xwt,cra0zy/xwt,lytico/xwt
Xwt/Xwt/Menu.cs
Xwt/Xwt/Menu.cs
// // Menu.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; namespace Xwt { [BackendType (typeof(IMenuBackend))] public class Menu: XwtComponent { MenuItemCollection items; public Menu () { items = new MenuItemCollection (this); } internal IMenuBackend Backend { get { return (IMenuBackend) BackendHost.Backend; } } public MenuItemCollection Items { get { return items; } } internal void InsertItem (int n, MenuItem item) { Backend.InsertItem (n, (IMenuItemBackend)BackendHost.ToolkitEngine.GetSafeBackend (item)); } internal void RemoveItem (MenuItem item) { Backend.RemoveItem ((IMenuItemBackend)BackendHost.ToolkitEngine.GetSafeBackend (item)); } /// <summary> /// Shows the menu at the current position of the cursor /// </summary> public void Popup () { Backend.Popup (); } /// <summary> /// Shows the menu at the specified location /// </summary> /// <param name="parentWidget">Widget upon which to show the menu</param> /// <param name="x">The x coordinate, relative to the widget origin</param> /// <param name="y">The y coordinate, relative to the widget origin</param> public void Popup (Widget parentWidget, double x, double y) { Backend.Popup ((IWidgetBackend)BackendHost.ToolkitEngine.GetSafeBackend (parentWidget), x, y); } /// <summary> /// Removes all separators of the menu which follow another separator /// </summary> public void CollapseSeparators () { bool wasSeparator = true; for (int n=0; n<Items.Count; n++) { if (Items[n] is SeparatorMenuItem) { if (wasSeparator) Items.RemoveAt (n--); else wasSeparator = true; } else wasSeparator = false; } if (Items.Count > 0 && Items[Items.Count - 1] is SeparatorMenuItem) Items.RemoveAt (Items.Count - 1); } } }
// // Menu.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; namespace Xwt { [BackendType (typeof(IMenuBackend))] public class Menu: XwtComponent { MenuItemCollection items; public Menu () { items = new MenuItemCollection (this); } internal IMenuBackend Backend { get { return (IMenuBackend) BackendHost.Backend; } } public MenuItemCollection Items { get { return items; } } internal void InsertItem (int n, MenuItem item) { Backend.InsertItem (n, (IMenuItemBackend)BackendHost.ToolkitEngine.GetSafeBackend (item)); } internal void RemoveItem (MenuItem item) { Backend.RemoveItem ((IMenuItemBackend)BackendHost.ToolkitEngine.GetSafeBackend (item)); } public void Popup () { Backend.Popup (); } public void Popup (Widget parentWidget, double x, double y) { Backend.Popup ((IWidgetBackend)BackendHost.ToolkitEngine.GetSafeBackend (parentWidget), x, y); } /// <summary> /// Removes all separators of the menu which follow another separator /// </summary> public void CollapseSeparators () { bool wasSeparator = true; for (int n=0; n<Items.Count; n++) { if (Items[n] is SeparatorMenuItem) { if (wasSeparator) Items.RemoveAt (n--); else wasSeparator = true; } else wasSeparator = false; } if (Items.Count > 0 && Items[Items.Count - 1] is SeparatorMenuItem) Items.RemoveAt (Items.Count - 1); } } }
mit
C#
daf57bdc31eaed586b153c3cb31f337b3f5407c4
Fix ordering
Peter-Juhasz/PackageDiscovery
src/PackageDiscovery/Program.cs
src/PackageDiscovery/Program.cs
using PackageDiscovery.Finders; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace PackageDiscovery { public class Program { internal const string DefaultOutputFileName = "output.tsv"; internal const string DefaultFieldSeparator = "\t"; public static void Main(string[] args) { // initialize IReadOnlyCollection<IPackageFinder> packageFinders = new IPackageFinder[] { new NuGetPackageFinder(), new NPMPackageFinder(), new BowerPackageFinder(), }; // process arguments IReadOnlyCollection<DirectoryInfo> directories = (args ?? Enumerable.Empty<string>()) .DefaultIfEmpty(Directory.GetCurrentDirectory()) .Select(p => new DirectoryInfo(p)) .ToList(); // find packages IReadOnlyCollection<Package> packages = ( from finder in packageFinders from directory in directories from package in finder.FindPackages(directory) select package ) .Distinct(p => new { p.Kind, p.Id, p.Version, p.IsDevelopmentPackage }) .OrderBy(p => p.Kind) .ThenBy(p => p.Id) .ThenBy(p => p.Version) .ThenBy(p => p.IsDevelopmentPackage) .ToList(); // write output if (File.Exists(DefaultOutputFileName)) File.Delete(DefaultOutputFileName); using (TextWriter writer = File.CreateText(DefaultOutputFileName)) { foreach (Package package in packages) { string row = String.Join(DefaultFieldSeparator, new object[] { package.Kind, package.Id, package.Version, package.IsDevelopmentPackage }); writer.WriteLine(row); } } } } }
using PackageDiscovery.Finders; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace PackageDiscovery { public class Program { internal const string DefaultOutputFileName = "output.tsv"; internal const string DefaultFieldSeparator = "\t"; public static void Main(string[] args) { // initialize IReadOnlyCollection<IPackageFinder> packageFinders = new IPackageFinder[] { new NuGetPackageFinder(), new NPMPackageFinder(), new BowerPackageFinder(), }; // process arguments IReadOnlyCollection<DirectoryInfo> directories = (args ?? Enumerable.Empty<string>()) .DefaultIfEmpty(Directory.GetCurrentDirectory()) .Select(p => new DirectoryInfo(p)) .ToList(); // find packages IReadOnlyCollection<Package> packages = ( from finder in packageFinders from directory in directories from package in finder.FindPackages(directory) select package ) .Distinct(p => new { p.Kind, p.Id, p.Version, p.IsDevelopmentPackage }) .OrderBy(p => p.Kind).ThenBy(p => p.Id).ThenBy(p => p.Version) .ToList(); // write output if (File.Exists(DefaultOutputFileName)) File.Delete(DefaultOutputFileName); using (TextWriter writer = File.CreateText(DefaultOutputFileName)) { foreach (Package package in packages) { string row = String.Join(DefaultFieldSeparator, new object[] { package.Kind, package.Id, package.Version, package.IsDevelopmentPackage }); writer.WriteLine(row); } } } } }
mit
C#
c019cb97ae05a670615f68f6653f27b4a3b88e09
Update Sensor.cs
Q42/Q42.HueApi,lbodtke/Q42.HueApi,jessejjohnson/Q42.HueApi
src/Q42.HueApi/Models/Sensor.cs
src/Q42.HueApi/Models/Sensor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Q42.HueApi.Models { [DataContract] public class Sensor { [IgnoreDataMember] public string Id { get; set; } [DataMember(Name = "state")] public SensorState State { get; set; } [DataMember(Name = "config")] public SensorConfig Config { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "type")] public string Type { get; set; } [DataMember(Name = "modelid")] public string ModelId { get; set; } [DataMember(Name = "manufacturername")] public string ManufacturerName { get; set; } [DataMember(Name = "swversion")] public string SwVersion { get; set; } [DataMember(Name = "uniqueid")] public string UniqueId { get; set; } } [DataContract] public class SensorState { [DataMember(Name = "daylight")] public bool Daylight { get; set; } [DataMember(Name = "lastupdated")] public string Lastupdated { get; set; } [DataMember(Name = "presence")] public bool Presence { get; set; } [DataMember(Name = "buttonevent")] public int? ButtonEvent { get; set; } [DataMember(Name = "status")] public int? status { get; set; } } [DataContract] public class SensorConfig { [DataMember(Name = "on")] public bool? On { get; set; } [DataMember(Name = "long")] public string Long { get; set; } [DataMember(Name = "lat")] public string Lat { get; set; } [DataMember(Name = "sunriseoffset")] public int? SunriseOffset { get; set; } [DataMember(Name = "sunsetoffset")] public int? SunsetOffset { get; set; } [DataMember(Name = "url")] public string Url { get; set; } [DataMember(Name = "reachable")] public bool? Reachable { get; set; } [DataMember(Name = "battery")] public int? Battery { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Q42.HueApi.Models { [DataContract] public class Sensor { [IgnoreDataMember] public string Id { get; set; } [DataMember(Name = "state")] public SensorState State { get; set; } [DataMember(Name = "config")] public SensorConfig Config { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "type")] public string Type { get; set; } [DataMember(Name = "modelid")] public string ModelId { get; set; } [DataMember(Name = "manufacturername")] public string ManufacturerName { get; set; } [DataMember(Name = "swversion")] public string SwVersion { get; set; } [DataMember(Name = "uniqueid")] public string UniqueId { get; set; } } [DataContract] public class SensorState { [DataMember(Name = "daylight")] public bool Daylight { get; set; } [DataMember(Name = "lastupdated")] public string Lastupdated { get; set; } [DataMember(Name = "presence")] public bool Presence { get; set; } [DataMember(Name = "buttonevent")] public int? ButtonEvent { get; set; } } [DataContract] public class SensorConfig { [DataMember(Name = "on")] public bool? On { get; set; } [DataMember(Name = "long")] public string Long { get; set; } [DataMember(Name = "lat")] public string Lat { get; set; } [DataMember(Name = "sunriseoffset")] public int? SunriseOffset { get; set; } [DataMember(Name = "sunsetoffset")] public int? SunsetOffset { get; set; } [DataMember(Name = "url")] public string Url { get; set; } [DataMember(Name = "reachable")] public bool? Reachable { get; set; } [DataMember(Name = "battery")] public int? Battery { get; set; } } }
mit
C#
50724b2876dd3a39f1f3bc84422fc784c0b6232d
remove build number / warning
nerai/Nibbler,nerai/Nibbler
src/Nibbler.Run/Program.cs
src/Nibbler.Run/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Nibbler.Core.Simple; using Unlog; namespace Nibbler.Run { class Program { static Program () { /* * Set up logging */ Unlog.FileLogTarget.ConvertAllFilesToHTML (); Log.AllowAsynchronousWriting = false; Log.AddDefaultFileTarget (); } static void Main (string[] args) { if (!Environment.Is64BitProcess) { Log.WriteLine ("Running as 32 bit process."); } var cr = new ControlledRun (false); cr.Run (); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Nibbler.Core.Simple; using Unlog; namespace Nibbler.Run { class Program { public static readonly string Version; static Program () { /* * Set up logging */ Unlog.FileLogTarget.ConvertAllFilesToHTML (); Log.AllowAsynchronousWriting = false; Log.AddDefaultFileTarget (); /* * Find build stamp (crude hack) */ var exe = typeof (Program).Assembly.ManifestModule.FullyQualifiedName; var stamp = File.GetLastWriteTimeUtc (exe); var id = stamp.Subtract (new DateTime (2014, 10, 26)).TotalDays; Version = "Nibbler Build A" + id.ToString ("0"); Version += " (" + stamp.ToString ("yyyy.MM.dd HH.mm") + ")"; Version += " (c) Sebastian Heuchler"; } static void Main (string[] args) { if (!Environment.Is64BitProcess) { Log.WriteLine ("WARNING: Running as 32 bit process. May crash on low memory."); } Log.WriteLine (Version); var cr = new ControlledRun (false); cr.Run (); } } }
mpl-2.0
C#
1a996b54c8e69a51910531f6e45e2c84964e6a0f
Fix handle null check
mono/maccore,jorik041/maccore,cwensley/maccore
src/QuickLook/Thumbnail.cs
src/QuickLook/Thumbnail.cs
// // MacOS Quicklook Thumbnail support // // Authors: // Miguel de Icaza // // 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. // #if MONOMAC using System; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; using System.Drawing; using System.Runtime.InteropServices; namespace MonoMac.QuickLook { public static partial class QLThumbnailImage { [DllImport(Constants.QuickLookLibrary)] extern static IntPtr QLThumbnailImageCreate (IntPtr allocator, IntPtr url, System.Drawing.SizeF maxThumbnailSize, IntPtr options); public static CGImage Create (NSUrl url, SizeF maxThumbnailSize, float scaleFactor = 1, bool iconMode = false) { NSMutableDictionary dictionary = null; if (scaleFactor != 1 && iconMode != false) { dictionary = new NSMutableDictionary (); dictionary.LowlevelSetObject ((NSNumber) scaleFactor, OptionScaleFactorKey.Handle); dictionary.LowlevelSetObject (iconMode ? CFBoolean.True.Handle : CFBoolean.False.Handle, OptionIconModeKey.Handle); } var handle = QLThumbnailImageCreate (IntPtr.Zero, url.Handle, maxThumbnailSize, dictionary == null ? IntPtr.Zero : dictionary.Handle); GC.KeepAlive (dictionary); if (handle != IntPtr.Zero) return new CGImage (handle, true); return null; } } } #endif
// // MacOS Quicklook Thumbnail support // // Authors: // Miguel de Icaza // // 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. // #if MONOMAC using System; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; using System.Drawing; using System.Runtime.InteropServices; namespace MonoMac.QuickLook { public static partial class QLThumbnailImage { [DllImport(Constants.QuickLookLibrary)] extern static IntPtr QLThumbnailImageCreate (IntPtr allocator, IntPtr url, System.Drawing.SizeF maxThumbnailSize, IntPtr options); public static CGImage Create (NSUrl url, SizeF maxThumbnailSize, float scaleFactor = 1, bool iconMode = false) { NSMutableDictionary dictionary = null; if (scaleFactor != 1 && iconMode != false) { dictionary = new NSMutableDictionary (); dictionary.LowlevelSetObject ((NSNumber) scaleFactor, OptionScaleFactorKey.Handle); dictionary.LowlevelSetObject (iconMode ? CFBoolean.True.Handle : CFBoolean.False.Handle, OptionIconModeKey.Handle); } var handle = QLThumbnailImageCreate (IntPtr.Zero, url.Handle, maxThumbnailSize, dictionary == null ? IntPtr.Zero : dictionary.Handle); GC.KeepAlive (dictionary); if (handle != null) return new CGImage (handle, true); return null; } } } #endif
apache-2.0
C#
90fd702d8b4d04f640eaf18fd4ebb0803990b286
Update Samples package 1.0.2.9000
episerver/EPiServer.Forms.Samples,episerver/EPiServer.Forms.Samples,episerver/EPiServer.Forms.Samples,episerver/EPiServer.Forms.Samples
AssemblyVersion.cs
AssemblyVersion.cs
using System.Reflection; [assembly: AssemblyCompany("EPiServer AB")] [assembly: AssemblyCopyright(" 2015 by EPiServer AB - All rights reserved")] [assembly: AssemblyTrademark("")] // 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.9000")] [assembly: AssemblyFileVersion("1.0.2.9000")]
using System.Reflection; [assembly: AssemblyCompany("EPiServer AB")] [assembly: AssemblyCopyright(" 2015 by EPiServer AB - All rights reserved")] [assembly: AssemblyTrademark("")] // 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.9000")] [assembly: AssemblyFileVersion("1.0.1.9000")]
apache-2.0
C#
dd207af8f0449ce46af5260b7269b656f1ccd98f
make ctrl+L generally destructive
kbilsted/KeyboordUsage
code/Configuration/UserStates/UserStateStandardConfiguraion.cs
code/Configuration/UserStates/UserStateStandardConfiguraion.cs
using System; using System.Collections.Generic; using System.Windows.Forms; using KeyboordUsage.Configuration.Keyboard; namespace KeyboordUsage.Configuration.UserStates { class UserStateStandardConfiguraion { private readonly CommandLineArgs commandLineArgs; public UserStateStandardConfiguraion(CommandLineArgs commandLineArgs) { this.commandLineArgs = commandLineArgs; } public UserState CreateDefaultState() { var stdKeyClassConfiguration = CreateStdKeyClassConfiguration(); var recodingSession = new RecodingSession(DateTime.Now, new Dictionary<Keys, int>(), new RatioCalculator()); return new UserState(AppConstants.CurrentVersion, recodingSession, new List<RecodingSession>(), CreateGuiConfiguration(), stdKeyClassConfiguration); } public GuiConfiguration CreateGuiConfiguration() { return new GuiConfiguration(10, 10, 1125, 550, 1); } public KeyClassConfiguration CreateStdKeyClassConfiguration() { var destructionKeys = KeyboardConstants.CombineKeysWithStandardModifiers(new[] { "Back", "Delete" }); destructionKeys.Add("L, Control"); destructionKeys.Add("Z, Control"); destructionKeys.Add("X, Control"); var navs = new [] { "Home", "PageUp", "End", "Next", "Up", "Left", "Down", "Right" }; var navKeys = KeyboardConstants.CombineKeysWithStandardModifiers(navs); navKeys.Add("G, Control"); if (commandLineArgs.UseVisualStudioNavigation) { navKeys.AddRange(KeyboardConstants.CombineKeysWithStandardModifiers(new[] {"F3", "F12"})); navKeys.AddRange(KeyboardConstants.KeysCombinedWithCodeModifiers(new[] {"T", "F6", "F7", "F8"})); navKeys.AddRange(KeyboardConstants.KeysCombinedWithControlAndShiftControl(new[] { "OemMinus", "Tab", "I" })); navKeys.Add("A, Shift, Control, Alt"); } var metaKeys = new List<string>() { "Escape", "F1", "F2", "F4", "F5", "F9", "F10", "F11", "LControlKey", "RLControlKey", "LWin", "LMenu", "RMenu", "Fn", "Apps" }; if (!commandLineArgs.UseVisualStudioNavigation) { metaKeys.AddRange(new [] { "F3", "F6", "F7", "F8", "F12"}); } var meta = KeyboardConstants.CombineKeysWithStandardModifiers(metaKeys.ToArray()); return new KeyClassConfiguration() { DestructiveKeyData = destructionKeys, MetaKeyData = meta, NaviationKeyData = navKeys, }; } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using KeyboordUsage.Configuration.Keyboard; namespace KeyboordUsage.Configuration.UserStates { class UserStateStandardConfiguraion { private readonly CommandLineArgs commandLineArgs; public UserStateStandardConfiguraion(CommandLineArgs commandLineArgs) { this.commandLineArgs = commandLineArgs; } public UserState CreateDefaultState() { var stdKeyClassConfiguration = CreateStdKeyClassConfiguration(); var recodingSession = new RecodingSession(DateTime.Now, new Dictionary<Keys, int>(), new RatioCalculator()); return new UserState(AppConstants.CurrentVersion, recodingSession, new List<RecodingSession>(), CreateGuiConfiguration(), stdKeyClassConfiguration); } public GuiConfiguration CreateGuiConfiguration() { return new GuiConfiguration(10, 10, 1125, 550, 1); } public KeyClassConfiguration CreateStdKeyClassConfiguration() { var destructionKeys = KeyboardConstants.CombineKeysWithStandardModifiers(new[] { "Back", "Delete" }); destructionKeys.Add("Z, Control"); destructionKeys.Add("X, Control"); var navs = new [] { "Home", "PageUp", "End", "Next", "Up", "Left", "Down", "Right" }; var navKeys = KeyboardConstants.CombineKeysWithStandardModifiers(navs); navKeys.Add("G, Control"); if (commandLineArgs.UseVisualStudioNavigation) { navKeys.AddRange(KeyboardConstants.CombineKeysWithStandardModifiers(new[] {"F3", "F12"})); navKeys.AddRange(KeyboardConstants.KeysCombinedWithCodeModifiers(new[] {"T", "F6", "F7", "F8"})); navKeys.AddRange(KeyboardConstants.KeysCombinedWithControlAndShiftControl(new[] { "OemMinus", "Tab", "I" })); navKeys.Add("A, Shift, Control, Alt"); } var metaKeys = new List<string>() { "Escape", "F1", "F2", "F4", "F5", "F9", "F10", "F11", "LControlKey", "RLControlKey", "LWin", "LMenu", "RMenu", "Fn", "Apps" }; if (!commandLineArgs.UseVisualStudioNavigation) { metaKeys.AddRange(new [] { "F3", "F6", "F7", "F8", "F12"}); } var meta = KeyboardConstants.CombineKeysWithStandardModifiers(metaKeys.ToArray()); return new KeyClassConfiguration() { DestructiveKeyData = destructionKeys, MetaKeyData = meta, NaviationKeyData = navKeys, }; } } }
apache-2.0
C#
b4145303cafe8775a213b5dd9217f93429b3ce45
Update server side API for single multiple answer question
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// Add single multiple answer question into SingleMultipleAnswerQuestion model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model /// </summary> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
mit
C#
9142565b86e33f558774f4b0d827091087e23f6e
Add support for CKAN 1.7 date format
opencolorado/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,DenverDev/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,DenverDev/.NET-Wrapper-for-CKAN-API
CkanDotNet.Api/Helper/DateHelper.cs
CkanDotNet.Api/Helper/DateHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; namespace CkanDotNet.Api.Helper { public static class DateHelper { /// <summary> /// Parse a date/time string. /// </summary> /// <param name="dateString"></param> /// <returns></returns> public static DateTime Parse(string dateString) { // Remove any line breaks dateString = dateString.Replace("\n", ""); dateString = dateString.Replace("\r", ""); // Remove any surrounding quotes if (dateString.StartsWith("\"") && dateString.EndsWith("\"")) { dateString = dateString.Substring(1, dateString.Length - 2); } var formats = new[] { "u", "s", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-dd HH:mm:ssZ", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:sszzzzzz", "yyyy-MM-ddTHH:mm:ss.ffffff", "yyyy-MM-dd HH:mm:ss.ffffff", "yyyy-MM-ddTHH:mm:ss.ffffffZ", "yyyy-MM-dd HH:mm:ss.ffffffZ", "yyyy-MM-ddTHH:mm:ss.fffZ", "M/d/yyyy h:mm:ss tt" // default format for invariant culture }; DateTime date; if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { if (date.Kind != DateTimeKind.Local) { date = TimeZoneInfo.ConvertTimeFromUtc(date, TimeZoneInfo.Local); } return date; } return DateTime.MinValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; namespace CkanDotNet.Api.Helper { public static class DateHelper { /// <summary> /// Parse a date/time string. /// </summary> /// <param name="dateString"></param> /// <returns></returns> public static DateTime Parse(string dateString) { // Remove any line breaks dateString = dateString.Replace("\n", ""); dateString = dateString.Replace("\r", ""); // Remove any surrounding quotes if (dateString.StartsWith("\"") && dateString.EndsWith("\"")) { dateString = dateString.Substring(1, dateString.Length - 2); } var formats = new[] { "u", "s", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-dd HH:mm:ssZ", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mm:sszzzzzz", "yyyy-MM-ddTHH:mm:ss.ffffff", "yyyy-MM-dd HH:mm:ss.ffffff", "M/d/yyyy h:mm:ss tt" // default format for invariant culture }; DateTime date; if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { date = TimeZoneInfo.ConvertTimeFromUtc(date,TimeZoneInfo.Local); return date; } return DateTime.MinValue; } } }
apache-2.0
C#
4bab901ba7288ab6e83c939297edcbe78674c0db
Update _TermsAndConditionBody.cshtml
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Web/Views/TermsAndConditions/_TermsAndConditionBody.cshtml
src/SFA.DAS.EmployerUsers.Web/Views/TermsAndConditions/_TermsAndConditionBody.cshtml
<p>To use this service you agree to:</p> <ul class="list list-bullet"> <li>sign out at the end of each session</li> <li>input truthful and accurate information</li> <li>adhere to the <a href="http://www.legislation.gov.uk/ukpga/1990/18/contents" target="_blank">Computer Misuse Act 1990</a></li> <li>use only a legitimate email address that you or people in your organisation has access to</li> <li>keep your sign in details secure and do not share them with third parties</li> <li>not use discriminatory wording as set out in the <a href="https://www.gov.uk/guidance/equality-act-2010-guidance#equalities-act-2010-legislation" target="_blank">Equality Act 2010</a></li> <li>make sure the published rates of pay comply with the <a href="https://www.gov.uk/national-minimum-wage-rates" target="_blank">National Minimum Wage</a> guidelines and are not misleading to candidates</li> <li>adhere to all relevant <a href="https://www.gov.uk/browse/employing-people" target="_blank">UK employment law</a></li> <li>if you are a commercial organisation as defined in <a href="https://www.legislation.gov.uk/ukpga/2015/30/section/54/enacted" target="_blank">section 54 of the Modern Slavery Act 2015</a>, adhere to the annual reporting requirements</li> <li>your apprenticeship adverts being publicly accessible, including the possibility of partner websites displaying them</li> <li>comply with the government safeguarding policies for <a href="https://www.gov.uk/government/publications/ofsted-safeguarding-policy" target="_blank">children</a> and <a href="https://www.gov.uk/government/publications/safeguarding-policy-protecting-vulnerable-adults" target="_blank">vulnerable adults</a></li> <li>not provide feedback on a training provider when you are an employer provider</li> <li>be an active and trading business at the point of creating an apprenticeship service account</li> <li>only add apprentices that are linked to the PAYE scheme registered in your employer account</li> <li>comply at all times with the Apprenticeship Agreement for Employers and Apprenticeship Funding Rules</li> </ul> <p>When you sign up for an apprenticeship service account we may need to verify and validate your company. You may not be granted an account if you fail the checks conducted by ESFA.</p> <p>Your contact details and information associated with your account will be collected and used for the support and administration of your account.</p> <p>We will not:</p> <ul class="list list-bullet"> <li>use or disclose this information for other purposes (except where we’re legally required to do so)</li> <li>use your details for any marketing purposes or for any reason unrelated to the use of your account</li> </ul> <p>We may update these terms and conditions at any time without notice. You’ll agree to any changes if you continue to use this service after the terms and conditions have been updated.</p>
<p>To use this service you agree to:</p> <ul class="list list-bullet"> <li>Sign out at the end of each session</li> <li>Input truthful and accurate information</li> <li>Adhere to the <a href="http://www.legislation.gov.uk/ukpga/1990/18/contents" target="_blank">Computer Misuse Act 1990</a></li> <li>Use only a legitimate email address that you or people in your organisation has access to</li> <li>Keep your sign in details secure and do not share them with third parties</li> <li>Not use discriminatory wording as set out in the <a href="https://www.gov.uk/guidance/equality-act-2010-guidance#equalities-act-2010-legislation" target="_blank">Equality Act 2010</a></li> <li>Make sure the published rates of pay comply with the <a href="https://www.gov.uk/national-minimum-wage-rates" target="_blank">National Minimum Wage</a> guidelines and are not misleading to candidates</li> <li>Adhere to all relevant <a href="https://www.gov.uk/browse/employing-people" target="_blank">UK employment law</a></li> <li>If you are a commercial organisation as defined in <a href="https://www.legislation.gov.uk/ukpga/2015/30/section/54/enacted" target="_blank">section 54 of the Modern Slavery Act 2015</a>, adhere to the annual reporting requirements</li> <li>Your apprenticeship adverts being publicly accessible, including the possibility of partner websites displaying them</li> <li>Comply with the government safeguarding policies for <a href="https://www.gov.uk/government/publications/ofsted-safeguarding-policy" target="_blank">children</a> and <a href="https://www.gov.uk/government/publications/safeguarding-policy-protecting-vulnerable-adults" target="_blank">vulnerable adults</a></li> <li>Not provide feedback on a training provider when you are an employer provider</li> <li>Be an active and trading business at the point of creating an apprenticeship service account</li> <li>Only add apprentices that are linked to the PAYE scheme registered in your employer account</li> <li>Comply at all times with the Apprenticeship Agreement for Employers and Apprenticeship Funding Rules</li> </ul> <p>When you sign up for an apprenticeship service account we may need to verify and validate your company. You may not be granted an account if you fail the checks conducted by ESFA.</p> <p>Your contact details and information associated with your account will be collected and used for the support and administration of your account.</p> <p>We will not:</p> <ul class="list list-bullet"> <li>Use or disclose this information for other purposes (except where we’re legally required to do so)</li> <li>Use your details for any marketing purposes or for any reason unrelated to the use of your account</li> </ul> <p>We may update these terms and conditions at any time without notice. You’ll agree to any changes if you continue to use this service after the terms and conditions have been updated.</p>
mit
C#
da41af6c12a1d265b595e2288eda3cf7c971d27f
Update DamageFlag2 info
HelloKitty/Booma.Proxy
src/Booma.Proxy.Packets.BlockServer/Commands/Command60/Sub60ObjectDamageRecievedCommand.cs
src/Booma.Proxy.Packets.BlockServer/Commands/Command60/Sub60ObjectDamageRecievedCommand.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; namespace Booma.Proxy { //TODO: Finish reverse engineering what each flag means. [Flags] public enum DamageFlag2 : byte { //Maybe? NormalSingleHit = 2, //Seems to be sent when the hit involves multiple hits. Like mechguns. MultipleHit = 3, NormalCreatureDeath = 10, NormalCreatureDeath2 = 11, //Sent sometimes when the creature dies? Maybe for playing no animation? NormalCreatureDeath3 = 14 } [Flags] public enum DamageFlag3 : byte { Unknown9 = 9, Unknown11 = 11, } //https://sylverant.net/wiki/index.php/Packet_0x60#Subcommand_0x0A [WireDataContract] [SubCommand60(SubCommand60OperationCode.ObjectDamageHit)] public sealed class Sub60ObjectDamageRecievedCommand : BaseSubCommand60, IMessageContextIdentifiable { /// <inheritdoc /> public byte Identifier => ObjectIdentifier.Identifier; //Most likely a creature, but could be other things. [WireMember(1)] public MapObjectIdentifier ObjectIdentifier { get; } //Why is this sent twice? Maybe when creatures deal damage to other creatures?? //This version is missing the objecttype/floor [WireMember(2)] private short ObjectIdentifier2 { get; } /// <summary> /// Usually the new health deficiet of the object/creature. /// </summary> [WireMember(3)] private ushort TotalDamageTaken { get; } /// <summary> /// Unknown, seems to always be 0. /// </summary> [WireMember(4)] private byte UnknownFlag1 { get; } [WireMember(5)] private DamageFlag2 UnknownFlag2 { get; } [WireMember(6)] private DamageFlag3 UnknownFlag3 { get; } [WireMember(7)] private byte UnknownFlag4 { get; } /// <inheritdoc /> public Sub60ObjectDamageRecievedCommand(MapObjectIdentifier objectIdentifier, ushort totalDamageTaken, byte[] flags) : this() { ObjectIdentifier = objectIdentifier; ObjectIdentifier2 = objectIdentifier.Identifier; //TODO: We are actually sending extra things we shouldn't here, we may need to change it TotalDamageTaken = totalDamageTaken; //TODO: Legacy reason UnknownFlag1 = flags[0]; UnknownFlag2 = (DamageFlag2)flags[1]; UnknownFlag3 = (DamageFlag3)flags[2]; UnknownFlag4 = flags[3]; } /// <summary> /// Serializer ctor. /// </summary> private Sub60ObjectDamageRecievedCommand() { CommandSize = 0x0C / 4; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; namespace Booma.Proxy { //TODO: Finish reverse engineering what each flag means. [Flags] public enum DamageFlag2 : byte { Unknown2 = 2, NormalCreatureDeath = 10, NormalCreatureDeath2 = 11, //Sent sometimes when the creature dies? Maybe for playing no animation? NormalCreatureDeath3 = 14 } [Flags] public enum DamageFlag3 : byte { Unknown9 = 9, Unknown11 = 11, } //https://sylverant.net/wiki/index.php/Packet_0x60#Subcommand_0x0A [WireDataContract] [SubCommand60(SubCommand60OperationCode.ObjectDamageHit)] public sealed class Sub60ObjectDamageRecievedCommand : BaseSubCommand60, IMessageContextIdentifiable { /// <inheritdoc /> public byte Identifier => ObjectIdentifier.Identifier; //Most likely a creature, but could be other things. [WireMember(1)] public MapObjectIdentifier ObjectIdentifier { get; } //Why is this sent twice? Maybe when creatures deal damage to other creatures?? //This version is missing the objecttype/floor [WireMember(2)] private short ObjectIdentifier2 { get; } /// <summary> /// Usually the new health deficiet of the object/creature. /// </summary> [WireMember(3)] private ushort TotalDamageTaken { get; } /// <summary> /// Unknown, seems to always be 0. /// </summary> [WireMember(4)] private byte UnknownFlag1 { get; } [WireMember(5)] private DamageFlag2 UnknownFlag2 { get; } [WireMember(6)] private DamageFlag3 UnknownFlag3 { get; } [WireMember(7)] private byte UnknownFlag4 { get; } /// <inheritdoc /> public Sub60ObjectDamageRecievedCommand(MapObjectIdentifier objectIdentifier, ushort totalDamageTaken, byte[] flags) : this() { ObjectIdentifier = objectIdentifier; ObjectIdentifier2 = objectIdentifier.Identifier; //TODO: We are actually sending extra things we shouldn't here, we may need to change it TotalDamageTaken = totalDamageTaken; //TODO: Legacy reason UnknownFlag1 = flags[0]; UnknownFlag2 = (DamageFlag2)flags[1]; UnknownFlag3 = (DamageFlag3)flags[2]; UnknownFlag4 = flags[3]; } /// <summary> /// Serializer ctor. /// </summary> private Sub60ObjectDamageRecievedCommand() { CommandSize = 0x0C / 4; } } }
agpl-3.0
C#
969f7434e7743ed581b33d024f4bd8629589e15e
Fix Buffer Object
dimmpixeye/Unity3dTools
Runtime/LibEcs/BufferObject.cs
Runtime/LibEcs/BufferObject.cs
// Project : game.metro // Contacts : Pix - ask@pixeye.games using System; using System.Collections.Generic; using UnityEngine; namespace Pixeye.Framework { public sealed class BufferObject<T> where T : class { public static BufferObject<T> Instance = new BufferObject<T>(); public static Func<T> creator; public T[] source = new T[12]; public int length; public void Add(T obj) { if (length == source.Length) Array.Resize(ref source, length << 1); source[length++] = obj; } public T Add() { if (length == source.Length) Array.Resize(ref source, length << 1); ref var obj = ref source[length++]; if (obj == null) obj = creator(); return obj; } public void RemoveAt(int index) { if (index < --length) Array.Copy(source, index + 1, source, index, length - index); } public void SetElement(int index, T arg) { source[index] = arg; } public static T AddDefault() { var source = Instance; if (source.length == source.source.Length) Array.Resize(ref source.source, source.length << 1); ref var obj = ref source.source[source.length++]; if (obj == null) obj = creator(); return obj; } } }
// Project : game.metro // Contacts : Pix - ask@pixeye.games using System; using System.Collections.Generic; using UnityEngine; namespace Pixeye.Framework { public sealed class BufferObject<T> where T : class { public static BufferObject<T> Instance = new BufferObject<T>(); public static Func<T> creator; public T[] source = new T[12]; public int length; public void Add(T obj) { if (length == source.Length) Array.Resize(ref source, length << 1); source[length++] = obj; } public void RemoveAt(int index) { if (index < --length) Array.Copy(source, index + 1, source, index, length - index); } public void SetElement(int index, T arg) { source[index] = arg; } public static T Add() { var source = Instance; if (source.length == source.source.Length) Array.Resize(ref source.source, source.length << 1); var l = source.length++; ref var obj = ref source.source[l]; if (obj == null) obj = creator(); return obj; } public static T Create() { var source = Instance; if (source.length == source.source.Length) Array.Resize(ref source.source, source.length << 1); var l = source.length; ref var obj = ref source.source[l]; if (obj == null) obj = creator(); return obj; } public static void Deploy() { Instance.length++; } } }
mit
C#
74219fc286d5547410a3c05d3941f8feb1525eba
Bump version 1.0.5.0
arbitertl/jsondiffpatch.net,wbish/jsondiffpatch.net
Src/Properties/AssemblyInfo.cs
Src/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("JsonDiffPatch.Net")] [assembly: AssemblyDescription("JSON object diffs and reversible patching (jsondiffpatch compatible)")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("William Bishop")] [assembly: AssemblyProduct("JsonDiffPatch.Net")] [assembly: AssemblyCopyright("Copyright © William Bishop 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)] #if !PORTABLE45 // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("50825ac2-b521-47d9-9a68-df6689df61cc")] #endif // 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.5.0")] [assembly: AssemblyFileVersion("1.0.5.0")]
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("JsonDiffPatch.Net")] [assembly: AssemblyDescription("JSON object diffs and reversible patching (jsondiffpatch compatible)")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("William Bishop")] [assembly: AssemblyProduct("JsonDiffPatch.Net")] [assembly: AssemblyCopyright("Copyright © William Bishop 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)] #if !PORTABLE45 // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("50825ac2-b521-47d9-9a68-df6689df61cc")] #endif // 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.4.0")] [assembly: AssemblyFileVersion("1.0.4.0")]
mit
C#
bd8c5e6a10cd13a37b4182cb4e4dcc7cdfbc79c4
add telerik net35 check.
EPTamminga/Dnn.Platform,bdukes/Dnn.Platform,valadas/Dnn.Platform,EPTamminga/Dnn.Platform,robsiera/Dnn.Platform,bdukes/Dnn.Platform,RichardHowells/Dnn.Platform,RichardHowells/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,nvisionative/Dnn.Platform,valadas/Dnn.Platform,RichardHowells/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,mitchelsellers/Dnn.Platform,valadas/Dnn.Platform,robsiera/Dnn.Platform,nvisionative/Dnn.Platform,RichardHowells/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Extensions,nvisionative/Dnn.Platform,EPTamminga/Dnn.Platform,robsiera/Dnn.Platform,mitchelsellers/Dnn.Platform,dnnsoftware/Dnn.AdminExperience.Extensions,dnnsoftware/Dnn.AdminExperience.Extensions
src/Modules/Settings/Dnn.PersonaBar.Security/Components/Checks/CheckTelerikVulnerability.cs
src/Modules/Settings/Dnn.PersonaBar.Security/Components/Checks/CheckTelerikVulnerability.cs
using System; using System.Collections.Generic; using System.IO; using System.Xml; using DotNetNuke.Application; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using Assembly = System.Reflection.Assembly; namespace Dnn.PersonaBar.Security.Components.Checks { public class CheckTelerikVulnerability : IAuditCheck { public CheckResult Execute() { var result = new CheckResult(SeverityEnum.Unverified, "CheckTelerikVulnerability"); var fileSums = new List<string> { "1ccb4c868938c15d209cae7ace3161420d85f58cbe74a7b3dfb6a2dc9100f6a3", //Telerik 2013.2.717.40 "fb686c941d1504de1b21ec353e887d640a752d537c91a19d89a0bfbadad5b76f" //Telerik 2013.2.717.35 }; const string settingName = "Telerik.AsyncUpload.ConfigurationEncryptionKey"; var compareVersion = new Version(2017, 2, 621); var filePath = Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll"); result.Severity = SeverityEnum.Pass; if (File.Exists(filePath)) { var assemblyVersion = Assembly.LoadFile(filePath).GetName().Version; if ((assemblyVersion < compareVersion && !fileSums.Contains(Utility.GetFileCheckSum(filePath)))) { result.Severity = SeverityEnum.Failure; result.Notes.Add("Telerik.Web.UI.dll assembly has't been patched."); } if (string.IsNullOrEmpty(Config.GetSetting(settingName))) { result.Severity = SeverityEnum.Failure; result.Notes.Add("App Setting \"Telerik.AsyncUpload.ConfigurationEncryptionKey\" doesn't exist in web.config."); } } return result; } } }
using System; using System.Collections.Generic; using System.IO; using System.Xml; using DotNetNuke.Application; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using Assembly = System.Reflection.Assembly; namespace Dnn.PersonaBar.Security.Components.Checks { public class CheckTelerikVulnerability : IAuditCheck { public CheckResult Execute() { var result = new CheckResult(SeverityEnum.Unverified, "CheckTelerikVulnerability"); const string fileSum = "1ccb4c868938c15d209cae7ace3161420d85f58cbe74a7b3dfb6a2dc9100f6a3"; const string settingName = "Telerik.AsyncUpload.ConfigurationEncryptionKey"; var compareVersion = new Version(2017, 2, 621); var filePath = Path.Combine(Globals.ApplicationMapPath, "bin\\Telerik.Web.UI.dll"); if (File.Exists(filePath)) { var assemblyVersion = Assembly.LoadFile(filePath).GetName().Version; if ((assemblyVersion < compareVersion && Utility.GetFileCheckSum(filePath) != fileSum) || string.IsNullOrEmpty(Config.GetSetting(settingName))) { result.Severity = SeverityEnum.Failure; } else { result.Severity = SeverityEnum.Pass; } } else { result.Severity = SeverityEnum.Pass; } return result; } } }
mit
C#
61dd33fe78742a72a574ffda69452a4384a28757
Fix SQLite migration
tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Host/Database/Migrations/20201106082741_SLAddAdditionalDDParameters.cs
src/Tgstation.Server.Host/Database/Migrations/20201106082741_SLAddAdditionalDDParameters.cs
using Microsoft.EntityFrameworkCore.Migrations; using System; namespace Tgstation.Server.Host.Database.Migrations { /// <summary> /// Adds columns for GitHub deployments for SQLite. /// </summary> public partial class SLAddAdditionalDDParameters : Migration { /// <inheritdoc /> protected override void Up(MigrationBuilder migrationBuilder) { if (migrationBuilder == null) throw new ArgumentNullException(nameof(migrationBuilder)); migrationBuilder.AddColumn<string>( name: "AdditionalParameters", table: "DreamDaemonSettings", nullable: false, maxLength: 10000, defaultValue: String.Empty); } /// <inheritdoc /> protected override void Down(MigrationBuilder migrationBuilder) { if (migrationBuilder == null) throw new ArgumentNullException(nameof(migrationBuilder)); migrationBuilder.RenameTable( name: "DreamDaemonSettings", newName: "DreamDaemonSettings_down"); migrationBuilder.CreateTable( name: "DreamDaemonSettings", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), AllowWebClient = table.Column<bool>(nullable: false), SecurityLevel = table.Column<int>(nullable: false), Port = table.Column<ushort>(nullable: false), StartupTimeout = table.Column<uint>(nullable: false), HeartbeatSeconds = table.Column<uint>(nullable: false), AutoStart = table.Column<bool>(nullable: false), InstanceId = table.Column<long>(nullable: false), TopicRequestTimeout = table.Column<uint>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_DreamDaemonSettings", x => x.Id); table.ForeignKey( name: "FK_DreamDaemonSettings_Instances_InstanceId", column: x => x.InstanceId, principalTable: "Instances", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.Sql( $"INSERT INTO DreamDaemonSettings SELECT Id,AllowWebClient,SecurityLevel,Port,AutoStart,HeartbeatSeconds,StartupTimeout,InstanceId,TopicRequestTimeout FROM DreamDaemonSettings_down"); migrationBuilder.DropTable( name: "DreamDaemonSettings_down"); } } }
using Microsoft.EntityFrameworkCore.Migrations; using System; namespace Tgstation.Server.Host.Database.Migrations { /// <summary> /// Adds columns for GitHub deployments for SQLite. /// </summary> public partial class SLAddAdditionalDDParameters : Migration { /// <inheritdoc /> protected override void Up(MigrationBuilder migrationBuilder) { if (migrationBuilder == null) throw new ArgumentNullException(nameof(migrationBuilder)); migrationBuilder.AddColumn<string>( name: "AdditionalParameters", table: "DreamDaemonSettings", nullable: false, maxLength: 10000, defaultValue: String.Empty); } /// <inheritdoc /> protected override void Down(MigrationBuilder migrationBuilder) { if (migrationBuilder == null) throw new ArgumentNullException(nameof(migrationBuilder)); migrationBuilder.RenameTable( name: "DreamDaemonSettings", newName: "DreamDaemonSettings_down"); migrationBuilder.CreateTable( name: "DreamDaemonSettings", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("Sqlite:Autoincrement", true), AllowWebClient = table.Column<bool>(nullable: false), SecurityLevel = table.Column<int>(nullable: false), Port = table.Column<ushort>(nullable: false), StartupTimeout = table.Column<uint>(nullable: false), HeartbeatSeconds = table.Column<uint>(nullable: false), AutoStart = table.Column<bool>(nullable: false), InstanceId = table.Column<long>(nullable: false), TopicRequestTimeout = table.Column<uint>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_DreamDaemonSettings", x => x.Id); table.ForeignKey( name: "FK_DreamDaemonSettings_Instances_InstanceId", column: x => x.InstanceId, principalTable: "Instances", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.Sql( $"INSERT INTO DreamDaemonSettings SELECT Id,AllowWebClient,SecurityLevel,PrimaryPort,AutoStart,HeartbeatSeconds,StartupTimeout,InstanceId,TopicRequestTimeout FROM DreamDaemonSettings_down"); migrationBuilder.DropTable( name: "DreamDaemonSettings_down"); } } }
agpl-3.0
C#
a910d090cd92c2e487471f0997297d5ef162502c
Fix test
mattolenik/winston,mattolenik/winston,mattolenik/winston
Winston.Test/Cache/CacheFixture.cs
Winston.Test/Cache/CacheFixture.cs
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using fastJSON; using Winston.Cache; using Winston.OS; using Winston.Packaging; namespace Winston.Test.Cache { public class CacheFixture : IDisposable { public SqliteCache Cache { get; private set; } public TempDirectory Dir { get; private set; } public TempFile RepoFile { get; private set; } public PackageSource PackageSource { get; private set; } public CacheFixture() { Task.Run(async () => { Dir = new TempDirectory("winston-test-"); Cache = await SqliteCache.CreateAsync(Dir); PackageSource = new PackageSource("test") { Packages = new List<Package> { new Package {Name = "Pkg 1", Location = new Uri("http://winston.ms/test")}, new Package {Name = "Pkg 2", Description = "packages with even numbers, two"}, new Package {Name = "Pkg 3", Description = "number three is odd"}, new Package {Name = "Pkg 4", Description = "packages with even numbers, four"}, } }; RepoFile = new TempFile(); var json = JSON.ToJSON(PackageSource); File.WriteAllText(RepoFile, json); await Cache.AddIndexAsync(RepoFile); }).Wait(); } public void Dispose() { Cache?.Dispose(); Dir?.Dispose(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using fastJSON; using Winston.Cache; using Winston.OS; using Winston.Packaging; namespace Winston.Test.Cache { public class CacheFixture : IDisposable { public SqliteCache Cache { get; private set; } public TempDirectory Dir { get; private set; } public TempFile RepoFile { get; private set; } public PackageSource PackageSource { get; private set; } public CacheFixture() { Task.Run(async () => { Dir = new TempDirectory("winston-test-"); Cache = await SqliteCache.CreateAsync(Dir); PackageSource = new PackageSource("test") { Packages = new List<Package> { new Package {Name = "Pkg 1", Location = new Uri("http://winston.ms/test")}, new Package {Name = "Pkg 2", Description = "packages with even numbers, two"}, new Package {Name = "Pkg 3", Description = "number three is odd"}, new Package {Name = "Pkg 4", Description = "packages with even numbers, four"}, } }; RepoFile = new TempFile(); var json = JSON.ToJSON(PackageSource); File.WriteAllText(RepoFile, json); await Cache.AddRepoAsync(RepoFile); }).Wait(); } public void Dispose() { Cache?.Dispose(); Dir?.Dispose(); } } }
mit
C#
b11b32984bd1a7db33eb3ef1bb9283a99d646fdf
increase version number
eugenpodaru/resume,eugenpodaru/resume,eugenpodaru/resume
Resume/Properties/AssemblyInfo.cs
Resume/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("Resume")] [assembly: AssemblyDescription("Eugen Podaru's Resume")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Resume")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2fb77ae9-82dd-42fb-9501-5704907aadcb")] // 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("0.1.*")] [assembly: AssemblyFileVersion("0.1.1.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("Resume")] [assembly: AssemblyDescription("Eugen Podaru's Resume")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Resume")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2fb77ae9-82dd-42fb-9501-5704907aadcb")] // 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("0.1.*")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
69c39937b357d9fadd564ab77e798f98ef9ca890
Update StandaloneApp's Program.cs to make it more obvious how to configure DI services
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
samples/StandaloneApp/Program.cs
samples/StandaloneApp/Program.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Blazor.Browser.Rendering; using Microsoft.AspNetCore.Blazor.Browser.Services; namespace StandaloneApp { public class Program { public static void Main(string[] args) { var serviceProvider = new BrowserServiceProvider(configure => { // Add any custom services here }); new BrowserRenderer(serviceProvider).AddComponent<App>("app"); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Blazor.Browser.Rendering; namespace StandaloneApp { public class Program { public static void Main(string[] args) { new BrowserRenderer().AddComponent<App>("app"); } } }
apache-2.0
C#
e1b04c9463ae632f65b164a1ab390f62099f8411
Update param name to match IWebHookHandler
aspnet/WebHooks,PriyaChandak/DemoForProjectShare,garora/WebHooks,aspnet/WebHooks
samples/GenericReceivers/WebHooks/GenericJsonWebHookHandler.cs
samples/GenericReceivers/WebHooks/GenericJsonWebHookHandler.cs
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.WebHooks; using Newtonsoft.Json.Linq; namespace GenericReceivers.WebHooks { public class GenericJsonWebHookHandler : WebHookHandler { public GenericJsonWebHookHandler() { this.Receiver = "genericjson"; } public override Task ExecuteAsync(string receiver, WebHookHandlerContext context) { // Get JSON from WebHook JObject data = context.GetDataOrDefault<JObject>(); // Get the action for this WebHook coming from the action query parameter in the URI string action = context.Actions.FirstOrDefault(); return Task.FromResult(true); } } }
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.WebHooks; using Newtonsoft.Json.Linq; namespace GenericReceivers.WebHooks { public class GenericJsonWebHookHandler : WebHookHandler { public GenericJsonWebHookHandler() { this.Receiver = "genericjson"; } public override Task ExecuteAsync(string generator, WebHookHandlerContext context) { // Get JSON from WebHook JObject data = context.GetDataOrDefault<JObject>(); // Get the action for this WebHook coming from the action query parameter in the URI string action = context.Actions.FirstOrDefault(); return Task.FromResult(true); } } }
apache-2.0
C#
8f3dd9e0c465269ec455ea580442fe765ab9d296
Add trace information
Sphiecoh/aspnetwebhooks.bitbucket.demo,Sphiecoh/aspnetwebhooks.bitbucket.demo,Sphiecoh/aspnetwebhooks.bitbucket.demo
src/AspNet.Webhooks/WebHookHandlers/BitbucketWebHookHandler.cs
src/AspNet.Webhooks/WebHookHandlers/BitbucketWebHookHandler.cs
using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using AspNet.Webhooks.Demo.Data; using AspNet.Webhooks.Demo.Models; using Microsoft.AspNet.WebHooks; using Newtonsoft.Json.Linq; namespace AspNet.Webhooks.Demo.WebHookHandlers { public class BitbucketWebHookHandler : WebHookHandler { private readonly IssuesRepository _repository; public BitbucketWebHookHandler() { _repository = new IssuesRepository(); } public override Task ExecuteAsync(string receiver, WebHookHandlerContext context) { var entry = context.GetDataOrDefault<JObject>(); // Extract the action -- for Bitbucket we have only one. var action = context.Actions.First(); switch (action) { case "repo:push": // Extract information about the repository var repository = entry["repository"].ToObject<BitbucketRepository>(); // Information about the user causing the event var actor = entry["actor"].ToObject<BitbucketUser>(); // Information about the specific changes foreach (var change in entry["push"]["changes"]) { // The previous commit var oldTarget = change["old"]["target"].ToObject<BitbucketTarget>(); // The new commit var newTarget = change["new"]["target"].ToObject<BitbucketTarget>(); } break; case "issue:created": Trace.TraceInformation(entry.ToString()); var issue = entry.ToObject<BitbucketIssue>(); _repository.Create(issue).Wait(); break; default: Trace.WriteLine(entry.ToString()); break; } return Task.FromResult(true); } } }
using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using AspNet.Webhooks.Demo.Data; using AspNet.Webhooks.Demo.Models; using Microsoft.AspNet.WebHooks; using Newtonsoft.Json.Linq; namespace AspNet.Webhooks.Demo.WebHookHandlers { public class BitbucketWebHookHandler : WebHookHandler { private readonly IssuesRepository _repository; public BitbucketWebHookHandler() { _repository = new IssuesRepository(); } public override Task ExecuteAsync(string receiver, WebHookHandlerContext context) { var entry = context.GetDataOrDefault<JObject>(); // Extract the action -- for Bitbucket we have only one. var action = context.Actions.First(); switch (action) { case "repo:push": // Extract information about the repository var repository = entry["repository"].ToObject<BitbucketRepository>(); // Information about the user causing the event var actor = entry["actor"].ToObject<BitbucketUser>(); // Information about the specific changes foreach (var change in entry["push"]["changes"]) { // The previous commit var oldTarget = change["old"]["target"].ToObject<BitbucketTarget>(); // The new commit var newTarget = change["new"]["target"].ToObject<BitbucketTarget>(); } break; case "issue:created": var issue = entry.ToObject<BitbucketIssue>(); _repository.Create(issue).Wait(); break; default: Trace.WriteLine(entry.ToString()); break; } return Task.FromResult(true); } } }
mit
C#
d4ce8bbf35929796e48f4b6c17bf56f6483f69c0
Fix compilation error induced due to rebase
gep13/GitVersion,ermshiperete/GitVersion,ParticularLabs/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,asbjornu/GitVersion,GitTools/GitVersion,ParticularLabs/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion
src/GitVersionCore.Tests/Helpers/TestEffectiveConfiguration.cs
src/GitVersionCore.Tests/Helpers/TestEffectiveConfiguration.cs
using System.Collections.Generic; using System.Linq; using GitVersion; using GitVersion.Extensions; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; namespace GitVersionCore.Tests.Helpers { public class TestEffectiveConfiguration : EffectiveConfiguration { public TestEffectiveConfiguration( AssemblyVersioningScheme assemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch, AssemblyFileVersioningScheme assemblyFileVersioningScheme = AssemblyFileVersioningScheme.MajorMinorPatch, string assemblyVersioningFormat = null, string assemblyFileVersioningFormat = null, string assemblyInformationalFormat = null, VersioningMode versioningMode = VersioningMode.ContinuousDelivery, string gitTagPrefix = "v", string tag = "", string nextVersion = null, string branchPrefixToTrim = "", bool preventIncrementForMergedBranchVersion = false, string tagNumberPattern = null, string continuousDeploymentFallbackTag = "ci", bool trackMergeTarget = false, string majorMessage = null, string minorMessage = null, string patchMessage = null, string noBumpMessage = null, CommitMessageIncrementMode commitMessageMode = CommitMessageIncrementMode.Enabled, int legacySemVerPadding = 4, int buildMetaDataPadding = 4, int commitsSinceVersionSourcePadding = 4, IEnumerable<IVersionFilter> versionFilters = null, bool tracksReleaseBranches = false, bool isRelease = false, string commitDateFormat = "yyyy-MM-dd", bool updateBuildNumber = false) : base(assemblyVersioningScheme, assemblyFileVersioningScheme, assemblyInformationalFormat, assemblyVersioningFormat, assemblyFileVersioningFormat, versioningMode, gitTagPrefix, tag, nextVersion, IncrementStrategy.Patch, branchPrefixToTrim, preventIncrementForMergedBranchVersion, tagNumberPattern, continuousDeploymentFallbackTag, trackMergeTarget, majorMessage, minorMessage, patchMessage, noBumpMessage, commitMessageMode, legacySemVerPadding, buildMetaDataPadding, commitsSinceVersionSourcePadding, versionFilters ?? Enumerable.Empty<IVersionFilter>(), tracksReleaseBranches, isRelease, commitDateFormat, updateBuildNumber, 0, 0) { } } }
using System.Collections.Generic; using System.Linq; using GitVersion; using GitVersion.Extensions; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; namespace GitVersionCore.Tests.Helpers { public class TestEffectiveConfiguration : EffectiveConfiguration { public TestEffectiveConfiguration( AssemblyVersioningScheme assemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch, AssemblyFileVersioningScheme assemblyFileVersioningScheme = AssemblyFileVersioningScheme.MajorMinorPatch, string assemblyVersioningFormat = null, string assemblyFileVersioningFormat = null, string assemblyInformationalFormat = null, VersioningMode versioningMode = VersioningMode.ContinuousDelivery, string gitTagPrefix = "v", string tag = "", string nextVersion = null, string branchPrefixToTrim = "", bool preventIncrementForMergedBranchVersion = false, string tagNumberPattern = null, string continuousDeploymentFallbackTag = "ci", bool trackMergeTarget = false, string majorMessage = null, string minorMessage = null, string patchMessage = null, string noBumpMessage = null, CommitMessageIncrementMode commitMessageMode = CommitMessageIncrementMode.Enabled, int legacySemVerPadding = 4, int buildMetaDataPadding = 4, int commitsSinceVersionSourcePadding = 4, IEnumerable<IVersionFilter> versionFilters = null, bool tracksReleaseBranches = false, bool isRelease = false, string commitDateFormat = "yyyy-MM-dd", bool updateBuildNumber = false) : base(assemblyVersioningScheme, assemblyFileVersioningScheme, assemblyInformationalFormat, assemblyVersioningFormat, assemblyFileVersioningFormat, versioningMode, gitTagPrefix, tag, nextVersion, IncrementStrategy.Patch, branchPrefixToTrim, preventIncrementForMergedBranchVersion, tagNumberPattern, continuousDeploymentFallbackTag, trackMergeTarget, majorMessage, minorMessage, patchMessage, noBumpMessage, commitMessageMode, legacySemVerPadding, buildMetaDataPadding, commitsSinceVersionSourcePadding, versionFilters ?? Enumerable.Empty<IVersionFilter>(), tracksReleaseBranches, isRelease, commitDateFormat, updateBuildNumber, 0, 0, 0) { } } }
mit
C#
bc7e44713193ab66f8ed11d6a92b7daa925f7349
Revert "remove a suppression no longer needed"
acple/ParsecSharp
ParsecSharp/GlobalSuppressions.cs
ParsecSharp/GlobalSuppressions.cs
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")] [assembly: SuppressMessage("Style", "IDE0071WithoutSuggestion")]
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")]
mit
C#
43d969bfecfe599df575612066a9352167c8583b
Fix GetUser call
TrueCar/AutomaticSharp,TrueCar/AutomaticSharp
src/AutomaticSharp/UserClient.cs
src/AutomaticSharp/UserClient.cs
using System.Threading.Tasks; using AutomaticSharp.Models; using AutomaticSharp.Requests; namespace AutomaticSharp { public partial class Client { /// <summary> /// Provides the basic account information about a user. /// Dependent on scope:user:profile /// </summary> /// <returns><see cref="User"/></returns> public async Task<User> GetUserInfoAsync(string userId = "me") { const string path = "user/"; return await GetAsync<User>(path + userId + "/"); } /// <summary> /// Returns a <see cref="DeviceUserRelationship"/> Object /// </summary> /// <param name="deviceId"></param> /// <param name="userId"></param> /// <returns></returns> public async Task<DeviceUserRelationship> GetDeviceAsync(string deviceId, string userId = "me") { const string path = "user/"; return await GetAsync<DeviceUserRelationship>(path + userId + "/device/" + deviceId + "/"); } /// <summary> /// Returns an array of <see cref="DeviceUserRelationship"/> Objects /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task<AutomaticCollection<DeviceUserRelationship>> GetDevicesAsync(DevicesRequest request = null) { const string path = "user/"; if(request == null) return await GetAsync<AutomaticCollection<DeviceUserRelationship>>(path + "me/device/"); return await GetAsync<AutomaticCollection<DeviceUserRelationship>>(path + (request.UserId ?? "me") + "/device/", request.CreateParameters()); } public async Task<EmergencyContact> DeleteEmergencyContactAsync(string emergencyContactId, string userId = "me") { const string path = "user/"; return await DeleteAsync<EmergencyContact>(path + userId + "/emergency-contact/" + emergencyContactId + "/"); } } }
using System.Threading.Tasks; using AutomaticSharp.Models; using AutomaticSharp.Requests; namespace AutomaticSharp { public partial class Client { /// <summary> /// Provides the basic account information about a user. /// Dependent on scope:user:profile /// </summary> /// <returns><see cref="User"/></returns> public async Task<AutomaticCollection<User>> GetUserInfoAsync(string userId = "me") { const string path = "user/"; return await GetAsync<AutomaticCollection<User>>(path + userId + "/"); } /// <summary> /// Returns a <see cref="DeviceUserRelationship"/> Object /// </summary> /// <param name="deviceId"></param> /// <param name="userId"></param> /// <returns></returns> public async Task<DeviceUserRelationship> GetDeviceAsync(string deviceId, string userId = "me") { const string path = "user/"; return await GetAsync<DeviceUserRelationship>(path + userId + "/device/" + deviceId + "/"); } /// <summary> /// Returns an array of <see cref="DeviceUserRelationship"/> Objects /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task<AutomaticCollection<DeviceUserRelationship>> GetDevicesAsync(DevicesRequest request = null) { const string path = "user/"; if(request == null) return await GetAsync<AutomaticCollection<DeviceUserRelationship>>(path + "me/device/"); return await GetAsync<AutomaticCollection<DeviceUserRelationship>>(path + (request.UserId ?? "me") + "/device/", request.CreateParameters()); } public async Task<EmergencyContact> DeleteEmergencyContactAsync(string emergencyContactId, string userId = "me") { const string path = "user/"; return await DeleteAsync<EmergencyContact>(path + userId + "/emergency-contact/" + emergencyContactId + "/"); } } }
mit
C#
acd3307c550943f83592928fd79d1cc4411b1583
Add missing CakeDataService docs
cake-build/cake,cake-build/cake,gep13/cake,patriksvensson/cake,gep13/cake,devlead/cake,patriksvensson/cake,devlead/cake
src/Cake.Core/CakeDataService.cs
src/Cake.Core/CakeDataService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Cake.Core { /// <summary> /// Implementation of <see cref="ICakeDataService"/>. /// </summary> // ReSharper disable once ClassNeverInstantiated.Global public sealed class CakeDataService : ICakeDataService { private readonly Dictionary<Type, object> _data; /// <summary> /// Initializes a new instance of the <see cref="CakeDataService"/> class. /// </summary> public CakeDataService() { _data = new Dictionary<Type, object>(); } /// <inheritdoc/> public TData Get<TData>() where TData : class { if (_data.TryGetValue(typeof(TData), out var data)) { if (data is TData typedData) { return typedData; } var message = $"Context data exists but is of the wrong type ({data.GetType().FullName})."; throw new InvalidOperationException(message); } throw new InvalidOperationException("The context data has not been setup."); } /// <inheritdoc/> public void Add<TData>(TData value) where TData : class { if (_data.ContainsKey(typeof(TData))) { var message = $"Context data of type '{typeof(TData).FullName}' has already been registered."; throw new InvalidOperationException(message); } _data.Add(typeof(TData), value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Cake.Core { // ReSharper disable once ClassNeverInstantiated.Global public sealed class CakeDataService : ICakeDataService { private readonly Dictionary<Type, object> _data; public CakeDataService() { _data = new Dictionary<Type, object>(); } public TData Get<TData>() where TData : class { if (_data.TryGetValue(typeof(TData), out var data)) { if (data is TData typedData) { return typedData; } var message = $"Context data exists but is of the wrong type ({data.GetType().FullName})."; throw new InvalidOperationException(message); } throw new InvalidOperationException("The context data has not been setup."); } public void Add<TData>(TData value) where TData : class { if (_data.ContainsKey(typeof(TData))) { var message = $"Context data of type '{typeof(TData).FullName}' has already been registered."; throw new InvalidOperationException(message); } _data.Add(typeof(TData), value); } } }
mit
C#
94a7d20cfccea581812aeaf38df3a0cdc4e7407f
Make NP file exception class public
icedream/NPSharp
src/client/NP/NPFileException.cs
src/client/NP/NPFileException.cs
using System; namespace NPSharp.NP { public class NpFileException : Exception { internal NpFileException(int error) : base(error == 1 ? @"File not found on NP server" : @"Internal error on NP server") { } internal NpFileException() : base(@"Could not fetch file from NP server.") { } } }
using System; namespace NPSharp.NP { internal class NpFileException : Exception { internal NpFileException(int error) : base(error == 1 ? @"File not found on NP server" : @"Internal error on NP server") { } internal NpFileException() : base(@"Could not fetch file from NP server.") { } } }
mit
C#
07cc1822c8c8e9a46997f926e86a3d53b3277710
Make area name case insensitive, better error handling
CareerHub/.NET-CareerHub-API-Client,CareerHub/.NET-CareerHub-API-Client
Client/API/APIInfo.cs
Client/API/APIInfo.cs
using CareerHub.Client.API.Meta; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CareerHub.Client.API { public class APIInfo { public APIInfo() { this.SupportedComponents = new List<string>(); } public string BaseUrl { get; set; } public string Version { get; set; } public IEnumerable<string> SupportedComponents { get; set; } public static async Task<APIInfo> GetFromRemote(string baseUrl, ApiArea area) { var metaApi = new MetaApi(baseUrl); var result = await metaApi.GetAPIInfo(); if (!result.Success) { throw new ApplicationException(result.Error); } var remoteInfo = result.Content; string areaname = area.ToString(); var remoteArea = remoteInfo.Areas.SingleOrDefault(a => a.Name.Equals(areaname, StringComparison.OrdinalIgnoreCase)); if (remoteArea == null) { return null; } return new APIInfo { BaseUrl = baseUrl, Version = remoteArea.LatestVersion, SupportedComponents = remoteInfo.Components }; } } }
using CareerHub.Client.API.Meta; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CareerHub.Client.API { public class APIInfo { public APIInfo() { this.SupportedComponents = new List<string>(); } public string BaseUrl { get; set; } public string Version { get; set; } public IEnumerable<string> SupportedComponents { get; set; } public static async Task<APIInfo> GetFromRemote(string baseUrl, ApiArea area) { var metaApi = new MetaApi(baseUrl); var result = await metaApi.GetAPIInfo(); if (!result.Success) { throw new ApplicationException(result.Error); } var remoteInfo = result.Content; string areaname = area.ToString(); var remoteArea = remoteInfo.Areas.Single(a => a.Name == areaname); if (remoteArea == null) { return null; } return new APIInfo { BaseUrl = baseUrl, Version = remoteArea.LatestVersion, SupportedComponents = remoteInfo.Components }; } } }
mit
C#
80beb6b7b4b7cf12dec0ecd74dfa40e485039935
Add virtual property to album model
lukecahill/Bravo,lukecahill/Bravo,lukecahill/Bravo
Bravo/Models/Album.cs
Bravo/Models/Album.cs
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Bravo.Models { public class Album { [Required] public int AlbumId { get; set; } [Required, MaxLength(255), Display(Name = "Title")] public string AlbumName { get; set; } [Required] public int GenreId { get; set; } [Required] public int ArtistId { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } public ICollection<Song> Songs { get; set; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Bravo.Models { public class Album { [Required] public int AlbumId { get; set; } [Required, MaxLength(255), Display(Name = "Title")] public string AlbumName { get; set; } [Required] public int GenreId { get; set; } [Required] public int ArtistId { get; set; } public ICollection<Song> Songs { get; set; } } }
mit
C#
f047c7a8dea27884f515b7183a77c03be5fba59e
bump version
GeertvanHorrik/Fody,ColinDabritzViewpoint/Fody,distantcam/Fody,Fody/Fody
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("2.0.5")] [assembly: AssemblyFileVersion("2.0.5")]
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("2.0.4")] [assembly: AssemblyFileVersion("2.0.4")]
mit
C#
21a4f099d647b78509fbf79733865ce3d15338b3
bump version
Fody/Obsolete
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("1.5.3.0")] [assembly: AssemblyFileVersion("1.5.3.0")]
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("1.5.2.0")] [assembly: AssemblyFileVersion("1.5.2.0")]
mit
C#
6e8998810cf44ce26405a4fde96f062361527382
bump version
Fody/Fody,GeertvanHorrik/Fody
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("2.2.0")] [assembly: AssemblyFileVersion("2.2.0")]
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("2.1.3")] [assembly: AssemblyFileVersion("2.1.3")]
mit
C#
488bea103bfacd8812949db3ab58839cf920da93
Update Startup
stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity
C#Development/BashSoft/BashSoft/Startup.cs
C#Development/BashSoft/BashSoft/Startup.cs
namespace BashSoft { using BashSoft.IO; public class Startup { public static void Main(string[] args) { OutputWriter.PrintLogo(); InputReader.StartReadingCommands(); } } }
namespace BashSoft { using BashSoft.IO; public class Startup { public static void Main(string[] args) { OutputWriter.PrintLogo(); InputReader.StartReadingCommands(); } } }
mit
C#
0d1a3d64bb07ed81ae78afafa9c38ae8e29cbbde
Fix crash on box spawn if reset during p2
neowutran/TeraDamageMeter,radasuka/ShinraMeter,neowutran/ShinraMeter,Seyuna/ShinraMeter
DamageMeter.Core/Processing/S_SPAWN_NPC.cs
DamageMeter.Core/Processing/S_SPAWN_NPC.cs
using Data; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Tera.Game; namespace DamageMeter.Processing { public static class S_SPAWN_NPC { public static void Process(Tera.Game.Messages.SpawnNpcServerMessage message) { NetworkController.Instance.EntityTracker.Update(message); DamageTracker.Instance.UpdateEntities(message); var npc = NetworkController.Instance.EntityTracker.GetOrNull(message.Id) as NpcEntity; if (npc.Info.HuntingZoneId == 950 && npc.Info.TemplateId == 9501) { var bosses = Database.Database.Instance.AllEntity().Select(x => NetworkController.Instance.EntityTracker.GetOrNull(x)).OfType<NpcEntity>().ToList(); var vergosPhase2Part1 = bosses.FirstOrDefault(x => x.Info.HuntingZoneId == 950 && x.Info.TemplateId == 1000); var vergosPhase2Part2 = bosses.FirstOrDefault(x => x.Info.HuntingZoneId == 950 && x.Info.TemplateId == 2000); DataExporter.AutomatedExport(vergosPhase2Part1, NetworkController.Instance.AbnormalityStorage); DataExporter.AutomatedExport(vergosPhase2Part2, NetworkController.Instance.AbnormalityStorage); } if (npc.Info.HuntingZoneId == 950 && npc.Info.TemplateId == 9502) { var bosses = Database.Database.Instance.AllEntity().Select(x => NetworkController.Instance.EntityTracker.GetOrNull(x)).OfType<NpcEntity>(); var vergosPhase3 = bosses.FirstOrDefault(x => x.Info.HuntingZoneId == 950 && x.Info.TemplateId == 3000); DataExporter.AutomatedExport(vergosPhase3, NetworkController.Instance.AbnormalityStorage); } } } }
using Data; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Tera.Game; namespace DamageMeter.Processing { public static class S_SPAWN_NPC { public static void Process(Tera.Game.Messages.SpawnNpcServerMessage message) { NetworkController.Instance.EntityTracker.Update(message); DamageTracker.Instance.UpdateEntities(message); var npc = NetworkController.Instance.EntityTracker.GetOrNull(message.Id) as NpcEntity; if (npc.Info.HuntingZoneId == 950 && npc.Info.TemplateId == 9501) { var bosses = Database.Database.Instance.AllEntity().Select(x => NetworkController.Instance.EntityTracker.GetOrNull(x)).OfType<NpcEntity>(); var vergosPhase2Part1 = bosses.First(x => x.Info.HuntingZoneId == 950 && x.Info.TemplateId == 1000); var vergosPhase2Part2 = bosses.First(x => x.Info.HuntingZoneId == 950 && x.Info.TemplateId == 2000); DataExporter.AutomatedExport(vergosPhase2Part1, NetworkController.Instance.AbnormalityStorage); DataExporter.AutomatedExport(vergosPhase2Part2, NetworkController.Instance.AbnormalityStorage); } if (npc.Info.HuntingZoneId == 950 && npc.Info.TemplateId == 9502) { var bosses = Database.Database.Instance.AllEntity().Select(x => NetworkController.Instance.EntityTracker.GetOrNull(x)).OfType<NpcEntity>(); var vergosPhase3 = bosses.First(x => x.Info.HuntingZoneId == 950 && x.Info.TemplateId == 3000); DataExporter.AutomatedExport(vergosPhase3, NetworkController.Instance.AbnormalityStorage); } } } }
mit
C#
ad672f027d19d7da033614462e835cdeafd7188b
Adjust namespace
dirkrombauts/production-helper-for-ti3
ProductionHelperForTI3.Domain/SpaceDock.cs
ProductionHelperForTI3.Domain/SpaceDock.cs
using System; namespace ProductionHelperForTI3.Domain { public class SpaceDock { private readonly Planet planet; private readonly Technology enviroCompensator; public SpaceDock(Planet planet, Technology technology) { this.planet = planet; this.enviroCompensator = technology == Technologies.EnviroCompensator ? technology : null; } public int BuildLimit { get { return this.planet.ResourceValue + 2 + (this.enviroCompensator != null ? 1 : 0); } } } }
using System; using ProductionHelperForTI3.Domain; namespace ProductionHelperForTI3.Specification { public class SpaceDock { private readonly Planet planet; private readonly Technology enviroCompensator; public SpaceDock(Planet planet, Technology technology) { this.planet = planet; this.enviroCompensator = technology == Technologies.EnviroCompensator ? technology : null; } public int BuildLimit { get { return this.planet.ResourceValue + 2 + (this.enviroCompensator != null ? 1 : 0); } } } }
mit
C#
020f24a9391170bd5aed414f931056a5ee79b6bd
Update SplitProgress.cs
wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter
SimpleWavSplitter.Console/SplitProgress.cs
SimpleWavSplitter.Console/SplitProgress.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace SimpleWavSplitter { #region References using System; using WavFile; #endregion #region SplitProgress public class SplitProgress : IProgress { #region Constructor public SplitProgress() { } #endregion #region IProgress public void Update(double value) { string text = string.Format("\rProgress: {0:0.0}%", value); System.Console.Write(text); } #endregion } #endregion }
/* * SimpleWavSplitter.Console * Copyright © Wiesław Šoltés 2010-2012. All Rights Reserved */ namespace SimpleWavSplitter { #region References using System; using WavFile; #endregion #region SplitProgress public class SplitProgress : IProgress { #region Constructor public SplitProgress() { } #endregion #region IProgress public void Update(double value) { string text = string.Format("\rProgress: {0:0.0}%", value); System.Console.Write(text); } #endregion } #endregion }
mit
C#
ba60969e85d8a81a3e7071b794231129194e0533
Remove proxy method to SendLineToPrinterNow
mmoening/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl,jlewin/MatterControl,mmoening/MatterControl
SlicerConfiguration/Settings/GCodeMacro.cs
SlicerConfiguration/Settings/GCodeMacro.cs
/* Copyright (c) 2017, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Text.RegularExpressions; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.MatterControl.PrinterCommunication.Io; namespace MatterHackers.MatterControl.SlicerConfiguration { public class GCodeMacro { public string Name { get; set; } public string GCode { get; set; } public MacroUiLocation MacroUiLocation { get; set; } public DateTime LastModified { get; set; } public static string FixMacroName(string input) { int lengthLimit = 24; string result = Regex.Replace(input, @"\r\n?|\n", " "); if (result.Length > lengthLimit) { result = result.Substring(0, lengthLimit) + "..."; } return result; } public void Run(PrinterConnection printerConnection) { if (printerConnection.PrinterIsConnected) { printerConnection.MacroStart(); printerConnection.SendLineToPrinterNow(GCode); if (GCode.Contains(MacroProcessingStream.MacroPrefix)) { printerConnection.SendLineToPrinterNow("\n" + MacroProcessingStream.MacroPrefix + "close()"); } } } } }
/* Copyright (c) 2016, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System; using System.IO; using Newtonsoft.Json.Linq; using System.Text; using MatterHackers.MatterControl.PrinterCommunication; using MatterHackers.MatterControl.PrinterCommunication.Io; using System.Text.RegularExpressions; namespace MatterHackers.MatterControl.SlicerConfiguration { public class GCodeMacro { public string Name { get; set; } public string GCode { get; set; } public MacroUiLocation MacroUiLocation { get; set; } public DateTime LastModified { get; set; } public static string FixMacroName(string input) { int lengthLimit = 24; string result = Regex.Replace(input, @"\r\n?|\n", " "); if (result.Length > lengthLimit) { result = result.Substring(0, lengthLimit) + "..."; } return result; } public void Run(PrinterConnection printerConnection) { if (printerConnection.PrinterIsConnected) { printerConnection.MacroStart(); SendCommandToPrinter(printerConnection, GCode); if (GCode.Contains(MacroProcessingStream.MacroPrefix)) { SendCommandToPrinter(printerConnection, "\n" + MacroProcessingStream.MacroPrefix + "close()"); } } } protected void SendCommandToPrinter(PrinterConnection printerConnection, string command) { printerConnection.SendLineToPrinterNow(command); } } }
bsd-2-clause
C#
71cfac695c72a08d0c41eca11f50f9c15bf24bb8
Remove unused method.
DanTup/DaNES
DaNES.Emulation/Memory.cs
DaNES.Emulation/Memory.cs
using System; namespace DanTup.DaNES.Emulation { class Memory { byte[] memory; public Memory(int size) { memory = new byte[size]; } public byte Read(ushort address) => memory[address]; public byte Write(ushort address, byte value) => memory[address] = value; public void Write(ushort address, byte[] value) => Array.Copy(value, 0, memory, address, value.Length); } }
using System; namespace DanTup.DaNES.Emulation { class Memory { byte[] memory; public Memory(int size) { memory = new byte[size]; } public byte Read(ushort address) => memory[address]; public byte Write(ushort address, byte value) => memory[address] = value; public void Write(ushort address, byte[] value) => Array.Copy(value, 0, memory, address, value.Length); public byte[] Raw => memory; } }
mit
C#
8cf1e5accf740266e3dc04eded6ce4161f6a14db
Update Record.cs
wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/ViewModels/Data/Record.cs
src/Core2D/ViewModels/Data/Record.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.Immutable; using Core2D.Attributes; namespace Core2D.Data { /// <summary> /// Database record. /// </summary> public class Record : ObservableObject, IRecord { private ImmutableArray<IValue> _values; /// <summary> /// Initializes a new instance of the <see cref="Record"/> class. /// </summary> public Record() : base() { _values = ImmutableArray.Create<IValue>(); } /// <inheritdoc/> [Content] public ImmutableArray<IValue> Values { get => _values; set => Update(ref _values, value); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { var values = this._values.Copy(shared).ToImmutable(); return new Record() { Name = this.Name, Values = values }; } /// <summary> /// Check whether the <see cref="Values"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public virtual bool ShouldSerializeValues() => true; } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Core2D.Attributes; namespace Core2D.Data { /// <summary> /// Database record. /// </summary> public class Record : ObservableObject, IRecord { private ImmutableArray<IValue> _values; /// <summary> /// Initializes a new instance of the <see cref="Record"/> class. /// </summary> public Record() : base() { _values = ImmutableArray.Create<IValue>(); } /// <inheritdoc/> [Content] public ImmutableArray<IValue> Values { get => _values; set => Update(ref _values, value); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { var values = this._values.Copy(shared).ToImmutable(); return new Record() { Name = this.Name, Values = values }; } /// <summary> /// Check whether the <see cref="Values"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public virtual bool ShouldSerializeValues() => true; } }
mit
C#
5f0dca0b0e82ee10b18b5c455a2a0d4a63e2abf5
Remove warning about FileVersion
Seddryck/Lookum
GlobalAssemblyInfo.cs
GlobalAssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Lookum Team - Cédric L. Charlier")] [assembly: AssemblyProduct("Lookum")] [assembly: AssemblyCopyright("Copyright © 2014-2015 - Cédric L. Charlier")] [assembly: AssemblyDescription("Lookum is a framework dedicated to the support of etl features available from C# applications")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] //Reference the testing class to ensure access to internal members [assembly: InternalsVisibleTo("Lookum.Framework.Testing")] [assembly: AssemblyVersion("0.8.0.*")] [assembly: AssemblyFileVersion("0.8.0")] [assembly: AssemblyInformationalVersion("0.8.0-BETA")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Lookum Team - Cédric L. Charlier")] [assembly: AssemblyProduct("Lookum")] [assembly: AssemblyCopyright("Copyright © 2014-2015 - Cédric L. Charlier")] [assembly: AssemblyDescription("Lookum is a framework dedicated to the support of etl features available from C# applications")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] //Reference the testing class to ensure access to internal members [assembly: InternalsVisibleTo("Lookum.Framework.Testing")] [assembly: AssemblyVersion("0.8.0")] [assembly: AssemblyFileVersion("0.8.0.*")] [assembly: AssemblyInformationalVersion("0.8.0-BETA")]
apache-2.0
C#
69ad9d712fcca5d15c2f450cf76e4706625b830c
Remove unused inject directive
martincostello/website,martincostello/website,martincostello/website,martincostello/website
src/Website/Views/Tools/Index.cshtml
src/Website/Views/Tools/Index.cshtml
@section meta { <link rel="api-guid" href="@Url.RouteUrl(SiteRoutes.GenerateGuid)" /> <link rel="api-hash" href="@Url.RouteUrl(SiteRoutes.GenerateHash)" /> <link rel="api-machine-key" href="@Url.RouteUrl(SiteRoutes.GenerateMachineKey)" /> } @section scripts { <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.6.1/clipboard.min.js" integrity="sha256-El0fEiD3YOM7uIVZztyQzmbbPlgEj0oJVxRWziUh4UE=" crossorigin="anonymous" defer></script> <environment names="Development"> <script src="~/assets/js/site.tools.js" defer asp-append-version="true"></script> </environment> <environment names="Staging,Production"> <script src="~/assets/js/site.tools.min.js" defer asp-append-version="true"></script> </environment> } <h1>@ViewBag.Title</h1> <div class="panel panel-default"> <div class="panel-body">This page contains tools and links to common development tools.</div> </div> <noscript> <div class="alert alert-warning" role="alert">JavaScript must be enabled in your browser to use these tools.</div> </noscript> <hr /> <div> @await Html.PartialAsync("_GenerateGuid") </div> <hr /> <div> @await Html.PartialAsync("_GenerateHash") </div> <hr /> <div> @await Html.PartialAsync("_GenerateMachineKey") </div>
@inject SiteOptions Options @section meta { <link rel="api-guid" href="@Url.RouteUrl(SiteRoutes.GenerateGuid)" /> <link rel="api-hash" href="@Url.RouteUrl(SiteRoutes.GenerateHash)" /> <link rel="api-machine-key" href="@Url.RouteUrl(SiteRoutes.GenerateMachineKey)" /> } @section scripts { <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.6.1/clipboard.min.js" integrity="sha256-El0fEiD3YOM7uIVZztyQzmbbPlgEj0oJVxRWziUh4UE=" crossorigin="anonymous" defer></script> <environment names="Development"> <script src="~/assets/js/site.tools.js" defer asp-append-version="true"></script> </environment> <environment names="Staging,Production"> <script src="~/assets/js/site.tools.min.js" defer asp-append-version="true"></script> </environment> } <h1>@ViewBag.Title</h1> <div class="panel panel-default"> <div class="panel-body">This page contains tools and links to common development tools.</div> </div> <noscript> <div class="alert alert-warning" role="alert">JavaScript must be enabled in your browser to use these tools.</div> </noscript> <hr /> <div> @await Html.PartialAsync("_GenerateGuid") </div> <hr /> <div> @await Html.PartialAsync("_GenerateHash") </div> <hr /> <div> @await Html.PartialAsync("_GenerateMachineKey") </div>
apache-2.0
C#
383e95e9cca8da51409099a4f49bdae496ff07ca
save data to s3
Ailuridaes/solid-doodle,djmlee013/solid-doodle,Ailuridaes/solid-doodle,onema/solid-doodle,onema/solid-doodle,djmlee013/solid-doodle
LogParser/Function.cs
LogParser/Function.cs
using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Text.RegularExpressions; using Amazon.CloudWatchLogs; using Amazon.Lambda.Core; using Amazon.S3; using Amazon.S3.Model; using LogParser.Model; using Newtonsoft.Json; namespace LogParser { public class Function { //--- Constants --- private const string FILTER = @"^(\[[A-Z ]+\])"; //--- Fields --- private readonly string logsBucket = Environment.GetEnvironmentVariable("LOGS_BUCKET"); private readonly IAmazonCloudWatchLogs _cloudWatchClient; private readonly IAmazonS3 _s3Client; private static readonly Regex filter = new Regex(FILTER, RegexOptions.Compiled | RegexOptions.CultureInvariant); //--- Constructors --- public Function() { _cloudWatchClient = new AmazonCloudWatchLogsClient(); _s3Client = new AmazonS3Client(); } //--- Methods --- [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public void Handler(CloudWatchLogsEvent cloudWatchLogsEvent, ILambdaContext context) { // Level One Console.WriteLine($"THIS IS THE DATA: {cloudWatchLogsEvent.AwsLogs.Data}"); var data = DecompressLogData(cloudWatchLogsEvent.AwsLogs.Data); Console.WriteLine($"THIS IS THE DECODED, UNCOMPRESSED DATA: {data}"); var events = JsonConvert.DeserializeObject<DecompressedEvents>(data).LogEvents; var filteredEvents = events.Where(x => filter.IsMatch(x.Message)).ToList(); filteredEvents.ForEach(x => Console.WriteLine($"MESSAGE: {x.Message}")); _s3Client.PutObjectAsync( new PutObjectRequest(){ BucketName = logsBucket, Key = Guid.NewGuid().ToString(), ContentBody = string.Join("\n", filteredEvents.Select(x => x.Message).ToArray()) } ).Wait(); } public static string DecompressLogData(string value) { var gzip = Convert.FromBase64String(value); using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress)) return new StreamReader(stream).ReadToEnd(); } } }
using System; using System.IO; using System.IO.Compression; using System.Linq; using System.Text.RegularExpressions; using Amazon.CloudWatchLogs; using Amazon.Lambda.Core; using LogParser.Model; using Newtonsoft.Json; namespace LogParser { public class Function { //--- Fields --- private readonly IAmazonCloudWatchLogs _cloudWatchClient; private const string FILTER = @"^(\[[A-Z ]+\])"; private static readonly Regex filter = new Regex(FILTER, RegexOptions.Compiled | RegexOptions.CultureInvariant); //--- Constructors --- public Function() { _cloudWatchClient = new AmazonCloudWatchLogsClient(); } //--- Methods --- [LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] public void Handler(CloudWatchLogsEvent cloudWatchLogsEvent, ILambdaContext context) { // Level One Console.WriteLine($"THIS IS THE DATA: {cloudWatchLogsEvent.AwsLogs.Data}"); var data = DecompressLogData(cloudWatchLogsEvent.AwsLogs.Data); Console.WriteLine($"THIS IS THE DECODED, UNCOMPRESSED DATA: {data}"); var events = JsonConvert.DeserializeObject<DecompressedEvents>(data).LogEvents; var filteredEvents = events.Where(x => filter.IsMatch(x.Message)).ToList(); filteredEvents.ForEach(x => Console.WriteLine(x.Message)); } public static string DecompressLogData(string value) { var gzip = Convert.FromBase64String(value); using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress)) return new StreamReader(stream).ReadToEnd(); } } }
mit
C#