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 |
---|---|---|---|---|---|---|---|---|
a370a7b1f984148ac8edbd3681b545a512bbce60 | update version for nuget | robinrodricks/FluentFTP,robinrodricks/FluentFTP,worstenbrood/FluentFTP,hgupta9/FluentFTP,robinrodricks/FluentFTP | FluentFTP/AssemblyInfo.cs | FluentFTP/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("FluentFTP")]
[assembly: AssemblyDescription("FTP and FTPS client implementation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FluentFTP")]
[assembly: AssemblyCopyright("J.P. Trosclair")]
[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("16.0.16")]
// 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: GuidAttribute("A88FA910-1553-4000-AA56-6FC001AD7CF1")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("FluentFTP")]
[assembly: AssemblyDescription("FTP and FTPS client implementation")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FluentFTP")]
[assembly: AssemblyCopyright("J.P. Trosclair")]
[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("16.0.15")]
// 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: GuidAttribute("A88FA910-1553-4000-AA56-6FC001AD7CF1")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| mit | C# |
4bcce2d5c33862b947abf10df10c3ba0f998e6b9 | Add VerifyAccessToken to IAuthorizationClient. | mfilippov/vimeo-dot-net | src/VimeoDotNet/Authorization/IAuthorizationClient.cs | src/VimeoDotNet/Authorization/IAuthorizationClient.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using VimeoDotNet.Models;
namespace VimeoDotNet.Authorization
{
/// <summary>
/// IAuthorizationClient
/// Additional info https://developer.vimeo.com/api/authentication
/// </summary>
public interface IAuthorizationClient
{
/// <summary>
/// GetAccessToken
/// </summary>
/// <param name="authorizationCode">AuthorizationCode</param>
/// <param name="redirectUri">RedirectUri</param>
/// <returns>Access token response</returns>
/// [Obsolete("Use async API instead sync wrapper")]
AccessTokenResponse GetAccessToken(string authorizationCode, string redirectUri);
/// <summary>
/// GetAccessTokenAsync
/// </summary>
/// <param name="authorizationCode">AuthorizationCode</param>
/// <param name="redirectUri">RedirectUri</param>
/// <returns>Access token response</returns>
Task<AccessTokenResponse> GetAccessTokenAsync(string authorizationCode, string redirectUri);
/// <summary>
/// VerifyAccessToken
/// </summary>
/// <param name="accessToken">AccessToken</param>
/// <returns>true if access token works, false otherwise</returns>
/// [Obsolete("Use async API instead sync wrapper")]
bool VerifyAccessToken(string accessToken);
/// <summary>
/// VerifyAccessToken
/// </summary>
/// <param name="accessToken">AccessToken</param>
/// <returns>true if access token works, false otherwise</returns>
/// [Obsolete("Use async API instead sync wrapper")]
Task<bool> VerifyAccessTokenAsync(string accessToken);
/// <summary>
/// Return unauthenticated token
/// </summary>
/// <returns>Access token response</returns>
Task<AccessTokenResponse> GetUnauthenticatedTokenAsync();
/// <summary>
/// GetAuthorizationEndpoint
/// </summary>
/// <param name="redirectUri">RedirectUri</param>
/// <param name="scope">Scope</param>
/// <param name="state">State</param>
/// <returns>Authorization endpoint</returns>
string GetAuthorizationEndpoint(string redirectUri, IEnumerable<string> scope, string state);
}
} | using System.Collections.Generic;
using System.Threading.Tasks;
using VimeoDotNet.Models;
namespace VimeoDotNet.Authorization
{
/// <summary>
/// IAuthorizationClient
/// Additional info https://developer.vimeo.com/api/authentication
/// </summary>
public interface IAuthorizationClient
{
/// <summary>
/// GetAccessToken
/// </summary>
/// <param name="authorizationCode">AuthorizationCode</param>
/// <param name="redirectUri">RedirectUri</param>
/// <returns>Access token response</returns>
/// [Obsolete("Use async API instead sync wrapper")]
AccessTokenResponse GetAccessToken(string authorizationCode, string redirectUri);
/// <summary>
/// GetAccessTokenAsync
/// </summary>
/// <param name="authorizationCode">AuthorizationCode</param>
/// <param name="redirectUri">RedirectUri</param>
/// <returns>Access token response</returns>
Task<AccessTokenResponse> GetAccessTokenAsync(string authorizationCode, string redirectUri);
/// <summary>
/// Return unauthenticated token
/// </summary>
/// <returns>Access token response</returns>
Task<AccessTokenResponse> GetUnauthenticatedTokenAsync();
/// <summary>
/// GetAuthorizationEndpoint
/// </summary>
/// <param name="redirectUri">RedirectUri</param>
/// <param name="scope">Scope</param>
/// <param name="state">State</param>
/// <returns>Authorization endpoint</returns>
string GetAuthorizationEndpoint(string redirectUri, IEnumerable<string> scope, string state);
}
} | mit | C# |
62f1af61fef25d02e116dda01f7b1b42e0ec3601 | Fix wrong value for the Preview tag. | punker76/taglib-sharp,mono/taglib-sharp,hwahrmann/taglib-sharp,punker76/taglib-sharp,Clancey/taglib-sharp,archrival/taglib-sharp,CamargoR/taglib-sharp,Clancey/taglib-sharp,hwahrmann/taglib-sharp,CamargoR/taglib-sharp,Clancey/taglib-sharp,archrival/taglib-sharp | src/TagLib/IFD/Tags/Nikon3MakerNoteEntryTag.cs | src/TagLib/IFD/Tags/Nikon3MakerNoteEntryTag.cs | //
// Nikon3MakerNoteEntryTag.cs:
//
// Author:
// Ruben Vermeersch ([email protected])
//
// Copyright (C) 2010 Ruben Vermeersch
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
namespace TagLib.IFD.Tags
{
/// <summary>
/// Nikon format 3 makernote tags.
/// Based on http://www.exiv2.org/tags-nikon.html
/// </summary>
public enum Nikon3MakerNoteEntryTag : ushort
{
/// <summary>
/// Offset to an IFD containing a preview image. (Hex: 0x0011)
/// </summary>
Preview = 17,
}
}
| //
// Nikon3MakerNoteEntryTag.cs:
//
// Author:
// Ruben Vermeersch ([email protected])
//
// Copyright (C) 2010 Ruben Vermeersch
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
namespace TagLib.IFD.Tags
{
/// <summary>
/// Nikon format 3 makernote tags.
/// Based on http://www.exiv2.org/tags-nikon.html
/// </summary>
public enum Nikon3MakerNoteEntryTag : ushort
{
/// <summary>
/// Offset to an IFD containing a preview image. (Hex: 0x0011)
/// </summary>
Preview = 16,
}
}
| lgpl-2.1 | C# |
052f451882d4f73c0a60ae7678dabcf6730aa28f | update logic for readability | justcoding121/Algorithm-Sandbox,justcoding121/Advanced-Algorithms | Algorithm.Sandbox/DynamicProgramming/Minimizing/MinEggDrop.cs | Algorithm.Sandbox/DynamicProgramming/Minimizing/MinEggDrop.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithm.Sandbox.DynamicProgramming.Minimizing
{
/// <summary>
/// Problem statement below
/// http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
/// </summary>
public class MinEggDrop
{
public static int GetMinDrops(int floors, int eggs)
{
return GetMinDrops(floors, eggs,
new Dictionary<string, int>());
}
public static int GetMinDrops(int floors, int eggs,
Dictionary<string, int> cache)
{
//no more floor
//no need for a trial
if (floors == 0)
{
return 0;
}
//for one floor one trial
if (floors == 1)
{
return 1;
}
//we need floors number of trial when
//we only have one egg left
if (eggs == 1)
{
return floors;
}
var cacheKey = $"{floors}-{eggs}";
if(cache.ContainsKey(cacheKey))
{
return cache[cacheKey];
}
var minDrops = int.MaxValue;
//simulate drop from 1st to current floor
for (int i = 1; i <= floors; i++)
{
//broke the egg at ith floor
var broke = GetMinDrops(i - 1, eggs - 1, cache) + 1;
//did'nt break at ith floor
var didntBreak = GetMinDrops(floors - i, eggs, cache) + 1;
var min = Math.Max(didntBreak, broke);
minDrops = Math.Min(min, minDrops);
}
cache.Add(cacheKey, minDrops);
return minDrops;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithm.Sandbox.DynamicProgramming.Minimizing
{
/// <summary>
/// Problem statement below
/// http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
/// </summary>
public class MinEggDrop
{
public static int GetMinDrops(int floors, int eggs)
{
return GetMinDrops(floors, eggs,
new Dictionary<string, int>());
}
public static int GetMinDrops(int floors, int eggs,
Dictionary<string, int> cache)
{
//no more floor
//no need for a trial
if (floors == 0)
{
return 0;
}
//for one floor one trial
if (floors == 1)
{
return 1;
}
//we need floors number of trial when
//we only have one egg left
if (eggs == 1)
{
return floors;
}
var cacheKey = $"{floors}-{eggs}";
if(cache.ContainsKey(cacheKey))
{
return cache[cacheKey];
}
var drops = int.MaxValue;
//simulate drop from 1st to current floor
for (int i = 1; i <= floors; i++)
{
//broke the egg at ith floor
var broke = GetMinDrops(i - 1, eggs - 1, cache);
//did'nt break at ith floor
var didntBreak = GetMinDrops(floors - i, eggs, cache);
var min = Math.Max(didntBreak, broke);
drops = Math.Min(min, drops);
}
var result = drops + 1;
cache.Add(cacheKey, result);
return result;
}
}
}
| mit | C# |
66bc4037ad630f897b0ab6a420b16264d07d4c72 | Update JournalMarketSell.cs | EDDiscovery/EDDiscovery,klightspeed/EDDiscovery,EDDiscovery/EDDiscovery,andreaspada/EDDiscovery,EDDiscovery/EDDiscovery,klightspeed/EDDiscovery,andreaspada/EDDiscovery,klightspeed/EDDiscovery | EDDiscovery/EliteDangerous/JournalEvents/JournalMarketSell.cs | EDDiscovery/EliteDangerous/JournalEvents/JournalMarketSell.cs |
using Newtonsoft.Json.Linq;
using System.Linq;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
//When Written: when selling goods in the market
//Parameters:
//• Type: cargo type
//• Count: number of units
//• SellPrice: price per unit
//• TotalSale: total sale value
//• AvgPricePaid: average price paid
//• IllegalGoods: (not always present) whether goods are illegal here
//• StolenGoods: (not always present) whether goods were stolen
//• BlackMarket: (not always present) whether selling in a black market
public class JournalMarketSell : JournalEntry
{
public JournalMarketSell(JObject evt ) : base(evt, JournalTypeEnum.MarketSell)
{
Type = JSONHelper.GetStringDef(evt["Type"]);
Count = JSONHelper.GetInt(evt["Count"]);
SellPrice = JSONHelper.GetLong(evt["SellPrice"]);
TotalSale = JSONHelper.GetLong(evt["TotalSale"]);
AvgPricePaid = JSONHelper.GetLong(evt["AvgPricePaid"]);
IllegalGoods = JSONHelper.GetBool(evt["IllegalGoods"]);
StolenGoods = JSONHelper.GetBool(evt["StolenGoods"]);
BlackMarket = JSONHelper.GetBool(evt["BlackMarket"]);
}
public string Type { get; set; }
public int Count { get; set; }
public long SellPrice { get; set; }
public long TotalSale { get; set; }
public long AvgPricePaid { get; set; }
public bool IllegalGoods { get; set; }
public bool StolenGoods { get; set; }
public bool BlackMarket { get; set; }
public static System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.marketsell; } }
public void MaterialList(EDDiscovery2.DB.MaterialCommoditiesList mc, DB.SQLiteConnectionUser conn)
{
mc.Change(EDDiscovery2.DB.MaterialCommodities.CommodityCategory, Type, -Count, 0, conn);
}
public void Ledger(EDDiscovery2.DB.MaterialCommoditiesLedger mcl, DB.SQLiteConnectionUser conn)
{
EDDiscovery2.DB.MaterialCommodities mc = mcl.GetMaterialCommodity(EDDiscovery2.DB.MaterialCommodities.CommodityCategory, Type, conn);
mcl.AddEvent(Id, EventTimeUTC, EventTypeID, mc.name + " " + Count + " Avg " + AvgPricePaid, TotalSale, (double)(SellPrice - AvgPricePaid));
}
}
}
|
using Newtonsoft.Json.Linq;
using System.Linq;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
//When Written: when selling goods in the market
//Parameters:
//• Type: cargo type
//• Count: number of units
//• SellPrice: price per unit
//• TotalSale: total sale value
//• AvgPricePaid: average price paid
//• IllegalGoods: (not always present) whether goods are illegal here
//• StolenGoods: (not always present) whether goods were stolen
//• BlackMarket: (not always present) whether selling in a black market
public class JournalMarketSell : JournalEntry
{
public JournalMarketSell(JObject evt ) : base(evt, JournalTypeEnum.MarketSell)
{
Type = JSONHelper.GetStringDef(evt["Type"]);
Count = JSONHelper.GetInt(evt["Count"]);
SellPrice = JSONHelper.GetLong(evt["SellPrice"]);
TotalSale = JSONHelper.GetLong(evt["TotalSale"]);
AvgPricePaid = JSONHelper.GetLong(evt["AvgPricePaid"]);
IllegalGoods = JSONHelper.GetBool(evt["IllegalGoods"]);
StolenGoods = JSONHelper.GetBool(evt["StolenGoods"]);
BlackMarket = JSONHelper.GetBool(evt["BlackMarket"]);
}
public string Type { get; set; }
public int Count { get; set; }
public long SellPrice { get; set; }
public long TotalSale { get; set; }
public long AvgPricePaid { get; set; }
public bool IllegalGoods { get; set; }
public bool StolenGoods { get; set; }
public bool BlackMarket { get; set; }
public static System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.marketsell; } }
public void MaterialList(EDDiscovery2.DB.MaterialCommoditiesList mc, DB.SQLiteConnectionUser conn)
{
mc.Change(EDDiscovery2.DB.MaterialCommodities.CommodityCategory, Type, -Count, 0, conn);
}
public void Ledger(EDDiscovery2.DB.MaterialCommoditiesLedger mcl, DB.SQLiteConnectionUser conn)
{
EDDiscovery2.DB.MaterialCommodities mc = mcl.GetMaterialCommodity(EDDiscovery2.DB.MaterialCommodities.CommodityCategory, Type, conn);
mcl.AddEvent(Id, EventTimeUTC, EventTypeID, mc.name + " " + Count + " Avg " + AvgPricePaid, SellPrice, (double)(SellPrice - AvgPricePaid));
}
}
}
| apache-2.0 | C# |
fd60b211f46ee8c116fdb254edd22d0310ebb46c | Update SerilogTracingExtensions.cs | SimonCropp/NServiceBus.Serilog | src/NServiceBus.Serilog/SerilogTracingExtensions.cs | src/NServiceBus.Serilog/SerilogTracingExtensions.cs | using NServiceBus.Configuration.AdvancedExtensibility;
using NServiceBus.Serilog;
using Serilog;
namespace NServiceBus
{
/// <summary>
/// Extensions to enable and configure Serilog Tracing.
/// </summary>
public static class SerilogTracingExtensions
{
/// <summary>
/// Enable Serilog Tracing for this endpoint using <see cref="Log.Logger"/> as the logging target.
/// </summary>
public static SerilogTracingSettings EnableSerilogTracing(this EndpointConfiguration configuration)
{
return configuration.EnableSerilogTracing(Log.Logger);
}
/// <summary>
/// Enable Serilog Tracing for this endpoint.
/// </summary>
public static SerilogTracingSettings EnableSerilogTracing(this EndpointConfiguration configuration, ILogger logger)
{
Guard.AgainstNull(configuration, nameof(configuration));
Guard.AgainstNull(logger, nameof(logger));
configuration.Recoverability().AddUnrecoverableException<ConfigurationException>();
configuration.EnableFeature<TracingFeature>();
var settings = configuration.GetSettings();
var attachments = new SerilogTracingSettings(logger,configuration);
settings.Set(attachments);
return attachments;
}
/// <summary>
/// Get the current <see cref="ILogger"/> for this context.
/// </summary>
public static ILogger Logger(this IPipelineContext context)
{
Guard.AgainstNull(context, nameof(context));
var bag = context.Extensions;
if (bag.TryGet("SerilogHandlerLogger", out ILogger logger))
{
return logger;
}
if (bag.TryGet(out logger))
{
return logger;
}
throw new ConfigurationException($"Expected to find a {nameof(ILogger)} in the pipeline context. It is possible a call to {nameof(SerilogTracingExtensions)}.{nameof(EnableSerilogTracing)} is missing.");
}
}
} | using NServiceBus.Configuration.AdvancedExtensibility;
using NServiceBus.Serilog;
using Serilog;
namespace NServiceBus
{
/// <summary>
/// Extensions to enable and configure Serilog Tracing.
/// </summary>
public static class SerilogTracingExtensions
{
/// <summary>
/// Enable Serilog Tracing for this endpoint using <see cref="Log.Logger"/> as the logging target.
/// </summary>
public static SerilogTracingSettings EnableSerilogTracing(this EndpointConfiguration configuration)
{
return configuration.EnableSerilogTracing(Log.Logger);
}
/// <summary>
/// Enable Serilog Tracing for this endpoint.
/// </summary>
public static SerilogTracingSettings EnableSerilogTracing(this EndpointConfiguration configuration, ILogger logger)
{
Guard.AgainstNull(configuration, nameof(configuration));
Guard.AgainstNull(logger, nameof(logger));
configuration.Recoverability().AddUnrecoverableException<ConfigurationException>();
configuration.EnableFeature<TracingFeature>();
var settings = configuration.GetSettings();
var attachments = new SerilogTracingSettings(logger,configuration);
settings.Set(attachments);
return attachments;
}
/// <summary>
/// Get the current <see cref="ILogger"/> for this context.
/// </summary>
public static ILogger Logger(this IPipelineContext context)
{
Guard.AgainstNull(context, nameof(context));
var bag = context.Extensions;
if (bag.TryGet("SerilogHandlerLogger", out ILogger logger))
{
return logger;
}
if (bag.TryGet(out logger))
{
return logger;
}
throw new ConfigurationException($"Expected to find a {nameof(ILogger)} in the pipeline context. It is possible a call to {nameof(SerilogTracingExtensions)}.{nameof(EnableSerilogTracing)} is missing.");
}
}
} | mit | C# |
6113a39d627d9e1115675a0dd1b3a98d1c334347 | Change version number to 1.1 | mganss/IS24RestApi,enkol/IS24RestApi | IS24RestApi/Properties/AssemblyInfo.cs | IS24RestApi/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("IS24RestApi")]
[assembly: AssemblyDescription("Client for the Immobilienscout24 REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Ganss")]
[assembly: AssemblyProduct("IS24RestApi")]
[assembly: AssemblyCopyright("Copyright © 2013 IS24RestApi project contributors")]
[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("ce77545e-5fbe-4b4d-bf1f-1c5d4532070a")]
// 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.1.*")]
| 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("IS24RestApi")]
[assembly: AssemblyDescription("Client for the Immobilienscout24 REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Ganss")]
[assembly: AssemblyProduct("IS24RestApi")]
[assembly: AssemblyCopyright("Copyright © 2013 IS24RestApi project contributors")]
[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("ce77545e-5fbe-4b4d-bf1f-1c5d4532070a")]
// 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.*")]
| apache-2.0 | C# |
91f2a28f5a8cb5e525cbf9a7925735d391b67044 | 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 © Damnae 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.72.*")]
| 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 © Damnae 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.71.*")]
| mit | C# |
f4abb2b7f18cc19abdd1fc2c7d2bf0d74a87a968 | Update VueVersions | NeutroniumCore/Neutronium,sjoerd222888/MVVM.CEF.Glue,NeutroniumCore/Neutronium,sjoerd222888/MVVM.CEF.Glue,David-Desmaisons/Neutronium,David-Desmaisons/Neutronium,sjoerd222888/MVVM.CEF.Glue,David-Desmaisons/Neutronium,NeutroniumCore/Neutronium | JavascriptFramework/Vue/VueVersions.cs | JavascriptFramework/Vue/VueVersions.cs | using Neutronium.Core.Infra;
namespace Neutronium.JavascriptFramework.Vue
{
internal class VueVersions : IVueVersion
{
public string FrameworkName { get; }
public string Name { get; }
public string VueVersion { get; }
internal static VueVersions Vue1 { get; } = new VueVersions("vue.js 1.0.25", "VueInjector", "vue1");
internal static VueVersions Vue2 { get; } = new VueVersions("vue.js 2.1.10", "VueInjectorV2", "vue2");
public ResourceReader GetVueResource()
{
return new ResourceReader($"scripts.{VueVersion}", this);
}
private VueVersions(string frameworkName, string name, string version)
{
FrameworkName = frameworkName;
Name = name;
VueVersion = version;
}
}
}
| using Neutronium.Core.Infra;
namespace Neutronium.JavascriptFramework.Vue
{
internal class VueVersions : IVueVersion
{
public string FrameworkName { get; }
public string Name { get; }
public string VueVersion { get; }
internal static VueVersions Vue1 { get; } = new VueVersions("vue.js 1.0.25", "VueInjector", "vue1");
internal static VueVersions Vue2 { get; } = new VueVersions("vue.js 2.1.3", "VueInjectorV2", "vue2");
public ResourceReader GetVueResource()
{
return new ResourceReader($"scripts.{VueVersion}", this);
}
private VueVersions(string frameworkName, string name, string version)
{
FrameworkName = frameworkName;
Name = name;
VueVersion = version;
}
}
}
| mit | C# |
54f982056a66087baa12a4092eafc2a86e644c10 | Implement the compiler program | jamesqo/BasicCompiler | src/BasicCompiler/Program.cs | src/BasicCompiler/Program.cs | namespace BasicCompiler
{
using System;
using System.IO;
using BasicCompiler.Core;
public class Program
{
private static int Main(string[] args)
{
if (args.Length != 1)
{
Console.Error.WriteLine("Usage: BasicCompiler <file>");
return 1;
}
string text = File.ReadAllText(args[0]);
// Expected format of code:
// '(add (subtract 4 2) 2)'
var lexed = Lexer.Lex(text);
var parsed = Parser.Parse(lexed);
var transformed = new ExpressionStatementTransform().Apply(parsed);
var output = CodeGenerator.Stringify(transformed);
// Sample output:
// 'add(subtract(4, 2), 2)'
Console.WriteLine(output);
return 0;
}
}
}
| namespace BasicCompiler
{
using System;
using System.IO;
using BasicCompiler.Core;
public class Program
{
private static void Main(string[] args)
{
string text = File.ReadAllText(args[0]);
// Expected format of code:
// '(add (subtract 4 2) 2)'
var lexed = Lexer.Lex(text);
/*
var parsed = Parse(lexed);
var transformed = Transform(parsed);
var output = GenerateCode(transformed);
Console.WriteLine(output);
*/
}
}
}
| mit | C# |
c6541bb6576c5917fe0b6cc4600657855fc26b63 | remove claim model from AccountModels file | ramzzzay/PhoneBook,ramzzzay/PhoneBook | PhoneBook.Core/Models/AccountModels.cs | PhoneBook.Core/Models/AccountModels.cs | namespace PhoneBook.Core.Models
{
public class AccountRegistrationModel
{
public string Email { get; set; }
public string Password { get; set; }
}
} | namespace PhoneBook.Core.Models
{
public class AccountRegistrationModel
{
public string Email { get; set; }
public string Password { get; set; }
}
} | apache-2.0 | C# |
104445424cc51a8d485dbe7d337f03dbbad3d578 | Fix path issue for StreamOut | cloudfoundry/garden-windows,cloudfoundry-incubator/garden-windows,cloudfoundry/garden-windows,cloudfoundry-incubator/garden-windows,stefanschneider/garden-windows,stefanschneider/garden-windows,cloudfoundry/garden-windows,cloudfoundry-incubator/garden-windows,stefanschneider/garden-windows | Containerizer/Services/Implementations/StreamOutService.cs | Containerizer/Services/Implementations/StreamOutService.cs | using System.IO;
using Containerizer.Services.Interfaces;
namespace Containerizer.Services.Implementations
{
public class StreamOutService : IStreamOutService
{
private readonly IContainerPathService containerPathService;
private readonly ITarStreamService tarStreamService;
public StreamOutService(IContainerPathService containerPathService, ITarStreamService tarStreamService)
{
this.containerPathService = containerPathService;
this.tarStreamService = tarStreamService;
}
public Stream StreamOutFile(string id, string source)
{
string rootDir = containerPathService.GetContainerRoot(id);
string path = rootDir + source;
Stream stream = tarStreamService.WriteTarToStream(path);
return stream;
}
}
} | using System.IO;
using Containerizer.Services.Interfaces;
namespace Containerizer.Services.Implementations
{
public class StreamOutService : IStreamOutService
{
private readonly IContainerPathService containerPathService;
private readonly ITarStreamService tarStreamService;
public StreamOutService(IContainerPathService containerPathService, ITarStreamService tarStreamService)
{
this.containerPathService = containerPathService;
this.tarStreamService = tarStreamService;
}
public Stream StreamOutFile(string id, string source)
{
string rootDir = containerPathService.GetContainerRoot(id);
string path = Path.Combine(rootDir, source);
Stream stream = tarStreamService.WriteTarToStream(path);
return stream;
}
}
} | apache-2.0 | C# |
329073fd5682f03183da61f5592a65479e1c8a71 | update example | SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK | Examples/CSharp/DataTradeExamples/SendLimitOrderExample.cs | Examples/CSharp/DataTradeExamples/SendLimitOrderExample.cs | namespace DataTradeExamples
{
using System;
using SoftFX.Extended;
class SendLimitOrderExample : Example
{
public SendLimitOrderExample(string address, string username, string password)
: base(address, username, password)
{
Trade.ExecutionReport += Trade_ExecutionReport;
}
private void Trade_ExecutionReport(object sender, SoftFX.Extended.Events.ExecutionReportEventArgs e)
{
Console.WriteLine($"ExecutionReport: {e.Report.ExecutionType} {e.Report.OrderStatus}");
}
protected override void RunExample()
{
var record = this.Trade.Server.SendOrderEx("Operation1", "EURUSD", TradeCommand.Limit, TradeRecordSide.Buy, 100000, null, 1.0, null, null, null, null, null, null, null);
Console.WriteLine("Trade record: {0}", record);
Console.ReadKey();
}
}
}
| namespace DataTradeExamples
{
using System;
using SoftFX.Extended;
class SendLimitOrderExample : Example
{
public SendLimitOrderExample(string address, string username, string password)
: base(address, username, password)
{
Trade.ExecutionReport += Trade_ExecutionReport;
}
private void Trade_ExecutionReport(object sender, SoftFX.Extended.Events.ExecutionReportEventArgs e)
{
Console.WriteLine($"ExecutionReport: {e.Report.ExecutionType} {e.Report.OrderStatus}");
}
protected override void RunExample()
{
try
{
var record = this.Trade.Server.SendOrderEx("Operation1", "EURUSD", TradeCommand.Market, TradeRecordSide.Sell, 4000, null, 1.24068, null, null, null, null, "Open Market Bot 2018-03-07 14:13:09", "{\"Key\":\"T Open Market Script 1\",\"Tag\":null}", 0);
Console.WriteLine("Trade record: {0}", record);
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}
| mit | C# |
49b8594a051c7b6c4b49f90f69884d339bdce840 | Stabilize reversible renaming | yeaicc/ConfuserEx,Desolath/Confuserex,engdata/ConfuserEx,Desolath/ConfuserEx3,timnboys/ConfuserEx | Confuser.Renamer/ReversibleRenamer.cs | Confuser.Renamer/ReversibleRenamer.cs | using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Confuser.Renamer {
public class ReversibleRenamer {
RijndaelManaged cipher;
byte[] key;
public ReversibleRenamer(string password) {
cipher = new RijndaelManaged();
using (var sha = SHA256.Create())
cipher.Key = key = sha.ComputeHash(Encoding.UTF8.GetBytes(password));
}
static string Base64Encode(byte[] buf) {
return Convert.ToBase64String(buf).Trim('=').Replace('+', '$').Replace('/', '_');
}
static byte[] Base64Decode(string str) {
str = str.Replace('$', '+').Replace('_', '/').PadRight((str.Length + 3) & ~3, '=');
return Convert.FromBase64String(str);
}
byte[] GetIV(byte ivId) {
byte[] iv = new byte[cipher.BlockSize / 8];
for (int i = 0; i < iv.Length; i++)
iv[i] = (byte)(ivId ^ key[i]);
return iv;
}
byte GetIVId(string str) {
byte x = (byte)str[0];
for (int i = 1; i < str.Length; i++)
x = (byte)(x * 3 + (byte)str[i]);
return x;
}
public string Encrypt(string name) {
byte ivId = GetIVId(name);
cipher.IV = GetIV(ivId);
var buf = Encoding.UTF8.GetBytes(name);
using (var ms = new MemoryStream()) {
ms.WriteByte(ivId);
using (var stream = new CryptoStream(ms, cipher.CreateEncryptor(), CryptoStreamMode.Write))
stream.Write(buf, 0, buf.Length);
buf = ms.ToArray();
return Base64Encode(buf);
}
}
public string Decrypt(string name) {
using (var ms = new MemoryStream(Base64Decode(name))) {
byte ivId = (byte)ms.ReadByte();
cipher.IV = GetIV(ivId);
var result = new MemoryStream();
using (var stream = new CryptoStream(ms, cipher.CreateDecryptor(), CryptoStreamMode.Read))
stream.CopyTo(result);
return Encoding.UTF8.GetString(result.ToArray());
}
}
}
} | using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Confuser.Renamer {
public class ReversibleRenamer {
RijndaelManaged cipher;
byte[] key;
byte ivId;
public ReversibleRenamer(string password) {
cipher = new RijndaelManaged();
using (var sha = SHA256.Create())
cipher.Key = key = sha.ComputeHash(Encoding.UTF8.GetBytes(password));
ivId = key[0];
}
static string Base64Encode(byte[] buf) {
return Convert.ToBase64String(buf).Trim('=').Replace('+', '$').Replace('/', '_');
}
static byte[] Base64Decode(string str) {
str = str.Replace('$', '+').Replace('_', '/').PadRight((str.Length + 3) & ~3, '=');
return Convert.FromBase64String(str);
}
byte[] GetIV(byte ivId) {
byte[] iv = new byte[cipher.BlockSize / 8];
for (int i = 0; i < iv.Length; i++)
iv[i] = (byte)(ivId ^ key[i]);
return iv;
}
byte[] NextIV(out byte ivId) {
var iv = GetIV(this.ivId);
ivId = this.ivId++;
return iv;
}
public string Encrypt(string name) {
byte ivId;
cipher.IV = NextIV(out ivId);
var buf = Encoding.UTF8.GetBytes(name);
using (var ms = new MemoryStream()) {
ms.WriteByte(ivId);
using (var stream = new CryptoStream(ms, cipher.CreateEncryptor(), CryptoStreamMode.Write))
stream.Write(buf, 0, buf.Length);
buf = ms.ToArray();
return Base64Encode(buf);
}
}
public string Decrypt(string name) {
using (var ms = new MemoryStream(Base64Decode(name))) {
byte ivId = (byte)ms.ReadByte();
cipher.IV = GetIV(ivId);
var result = new MemoryStream();
using (var stream = new CryptoStream(ms, cipher.CreateDecryptor(), CryptoStreamMode.Read))
stream.CopyTo(result);
return Encoding.UTF8.GetString(result.ToArray());
}
}
}
} | mit | C# |
82023aebd7ce0a03250d00d5b31e2a7ba8e2a598 | Fix #43 (possibly) | Seist/Skylight | Room/Events/Arguments/ChatEventArgs.cs | Room/Events/Arguments/ChatEventArgs.cs | namespace Skylight
{
using System;
/// <summary>
/// The class that handles all chat-based messages from the server
/// including ones sent to the user through system.
/// </summary>
public class ChatEventArgs : EventArgs
{
/// <summary>
/// The player who sent the message.
/// </summary>
public readonly Player speaker;
/// <summary>
/// Initializes a new instance of the <see cref="ChatEventArgs"/> class.
/// The main method where the chat messages are sent. This method sets the properties in
/// this class to the speaker and origin of the message, where it is handed off to a delegate
/// later.
/// </summary>
/// <param name="speaker">
/// The player who said the message.
/// </param>
/// <param name="origin">
/// The room where the message originated.
/// </param>
public ChatEventArgs(Player speaker, Room origin)
{
this.Origin = origin;
if (this.Origin != null)
{
this.Origin.ChatLog = origin.ChatLog;
}
this.speaker = speaker;
}
/// <summary>
/// The origin (room) where the message came from.
/// </summary>
public Room Origin { get; set; }
}
} | namespace Skylight
{
using System;
/// <summary>
/// The class that handles all chat-based messages from the server
/// including ones sent to the user through system.
/// </summary>
public class ChatEventArgs : EventArgs
{
/// <summary>
/// The player who sent the message.
/// </summary>
private readonly Player speaker;
/// <summary>
/// Initializes a new instance of the <see cref="ChatEventArgs"/> class.
/// The main method where the chat messages are sent. This method sets the properties in
/// this class to the speaker and origin of the message, where it is handed off to a delegate
/// later.
/// </summary>
/// <param name="speaker">
/// The player who said the message.
/// </param>
/// <param name="origin">
/// The room where the message originated.
/// </param>
public ChatEventArgs(Player speaker, Room origin)
{
this.Origin = origin;
if (this.Origin != null)
{
this.Origin.ChatLog = origin.ChatLog;
}
this.speaker = speaker;
}
/// <summary>
/// The origin (room) where the message came from.
/// </summary>
public Room Origin { get; private set; }
}
} | mit | C# |
dca38640d514ea732b9ed6d2c589948f23d874f6 | Fix unhandled exception for null streams | SceneGate/Yarhl | libgame/FileFormat/BinaryFormat.cs | libgame/FileFormat/BinaryFormat.cs | //
// BinaryFormat.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <[email protected]>
//
// Copyright (c) 2016 Benito Palacios Sánchez
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace Libgame.FileFormat
{
using IO;
using Mono.Addins;
/// <summary>
/// Binary format.
/// </summary>
[Extension]
public class BinaryFormat : Format
{
/// <summary>
/// Initializes a new instance of the <see cref="BinaryFormat"/> class.
/// </summary>
/// <param name="stream">Binary stream.</param>
public BinaryFormat(DataStream stream)
{
Stream = new DataStream(stream, 0, stream?.Length ?? 0);
}
/// <summary>
/// Initializes a new instance of the <see cref="BinaryFormat"/> class.
/// </summary>
/// <param name="filePath">The file path.</param>
public BinaryFormat(string filePath)
{
Stream = new DataStream(filePath, FileOpenMode.ReadWrite);
}
/// <summary>
/// Gets the format name.
/// </summary>
/// <value>The format name.</value>
public override string Name {
get { return "libgame.binary"; }
}
/// <summary>
/// Gets the stream.
/// </summary>
/// <value>The stream.</value>
public DataStream Stream {
get;
private set;
}
/// <summary>
/// Releases all resource used by the <see cref="BinaryFormat"/>
/// object.
/// </summary>
/// <param name="freeManagedResourcesAlso">If set to <c>true</c> free
/// managed resources also.</param>
protected override void Dispose(bool freeManagedResourcesAlso)
{
base.Dispose(freeManagedResourcesAlso);
if (freeManagedResourcesAlso)
Stream.Dispose();
}
}
}
| //
// BinaryFormat.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <[email protected]>
//
// Copyright (c) 2016 Benito Palacios Sánchez
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace Libgame.FileFormat
{
using IO;
using Mono.Addins;
/// <summary>
/// Binary format.
/// </summary>
[Extension]
public class BinaryFormat : Format
{
/// <summary>
/// Initializes a new instance of the <see cref="BinaryFormat"/> class.
/// </summary>
/// <param name="stream">Binary stream.</param>
public BinaryFormat(DataStream stream)
{
Stream = new DataStream(stream, 0, stream.Length);
}
/// <summary>
/// Initializes a new instance of the <see cref="BinaryFormat"/> class.
/// </summary>
/// <param name="filePath">The file path.</param>
public BinaryFormat(string filePath)
{
Stream = new DataStream(filePath, FileOpenMode.ReadWrite);
}
/// <summary>
/// Gets the format name.
/// </summary>
/// <value>The format name.</value>
public override string Name {
get { return "libgame.binary"; }
}
/// <summary>
/// Gets the stream.
/// </summary>
/// <value>The stream.</value>
public DataStream Stream {
get;
private set;
}
/// <summary>
/// Releases all resource used by the <see cref="BinaryFormat"/>
/// object.
/// </summary>
/// <param name="freeManagedResourcesAlso">If set to <c>true</c> free
/// managed resources also.</param>
protected override void Dispose(bool freeManagedResourcesAlso)
{
base.Dispose(freeManagedResourcesAlso);
if (freeManagedResourcesAlso)
Stream.Dispose();
}
}
}
| mit | C# |
8a9b811ea1ead9c7550937f8a7f7701237852ef5 | Add Precipitation Type to MinuteDataPoint. | jcheng31/ForecastPCL,jcheng31/DarkSkyApi | ForecastPCL/Models/MinuteDataPoint.cs | ForecastPCL/Models/MinuteDataPoint.cs | namespace ForecastIOPortable.Models
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// The weather conditions for a particular minute.
/// </summary>
[DataContract]
public class MinuteDataPoint
{
/// <summary>
/// Unix time at which this data point applies.
/// </summary>
[DataMember]
private int time;
/// <summary>
/// Gets or sets the time of this data point.
/// </summary>
public DateTimeOffset Time
{
get
{
return this.time.ToDateTimeOffset();
}
set
{
this.time = value.ToUnixTime();
}
}
/// <summary>
/// Gets or sets the average expected precipitation assuming any precipitation occurs.
/// </summary>
[DataMember(Name = "precipIntensity")]
public float PrecipitationIntensity { get; set; }
/// <summary>
/// Gets or sets the probability of precipitation (from 0 to 1).
/// </summary>
[DataMember(Name = "precipProbability")]
public float PrecipitationProbability { get; set; }
/// <summary>
/// Gets or sets the type of precipitation.
/// </summary>
[DataMember(Name = "precipType")]
public string PrecipitationType { get; set; }
}
}
| namespace ForecastIOPortable.Models
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// The weather conditions for a particular minute.
/// </summary>
[DataContract]
public class MinuteDataPoint
{
/// <summary>
/// Unix time at which this data point applies.
/// </summary>
[DataMember]
private int time;
/// <summary>
/// Gets or sets the time of this data point.
/// </summary>
public DateTimeOffset Time
{
get
{
return this.time.ToDateTimeOffset();
}
set
{
this.time = value.ToUnixTime();
}
}
/// <summary>
/// Gets or sets the average expected precipitation assuming any precipitation occurs.
/// </summary>
[DataMember(Name = "precipIntensity")]
public float PrecipitationIntensity { get; set; }
/// <summary>
/// Gets or sets the probability of precipitation (from 0 to 1).
/// </summary>
[DataMember(Name = "precipProbability")]
public float PrecipitationProbability { get; set; }
}
}
| mit | C# |
ac59c59cde4903f10b9573ba0d6973808cae92d3 | Fix bug in Delimited (delimiter was never used) | weblinq/WebLinq,atifaziz/WebLinq,atifaziz/WebLinq,weblinq/WebLinq | src/Core/Text/TextQuery.cs | src/Core/Text/TextQuery.cs | #region Copyright (c) 2016 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace WebLinq.Text
{
using System;
using System.Net.Http;
using System.Reactive.Linq;
using System.Text;
using Mannex.Collections.Generic;
public static class TextQuery
{
public static IObservable<string> Delimited<T>(this IObservable<T> query, string delimiter) =>
query.Select((e, i) => i.AsKeyTo(e))
.Aggregate(
new StringBuilder(),
(sb, e) => sb.Append(e.Key > 0 ? delimiter : null).Append(e.Value),
sb => sb.ToString());
public static IObservable<HttpFetch<string>> Text(this IHttpObservable query) =>
query.WithReader(f => f.Content.ReadAsStringAsync());
public static IObservable<HttpFetch<string>> Text(this IHttpObservable query, Encoding encoding) =>
query.WithReader(async f => encoding.GetString(await f.Content.ReadAsByteArrayAsync()));
public static IObservable<HttpFetch<string>> Text(this IObservable<HttpFetch<HttpContent>> query) =>
from fetch in query
from text in fetch.Content.ReadAsStringAsync()
select fetch.WithContent(text);
public static IObservable<HttpFetch<string>> Text(this IObservable<HttpFetch<HttpContent>> query, Encoding encoding) =>
from fetch in query
from bytes in fetch.Content.ReadAsByteArrayAsync()
select fetch.WithContent(encoding.GetString(bytes));
}
}
| #region Copyright (c) 2016 Atif Aziz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace WebLinq.Text
{
using System;
using System.Net.Http;
using System.Reactive.Linq;
using System.Text;
public static class TextQuery
{
public static IObservable<string> Delimited<T>(this IObservable<T> query, string delimiter) =>
query.Aggregate(new StringBuilder(), (sb, e) => sb.Append(e), sb => sb.ToString());
public static IObservable<HttpFetch<string>> Text(this IHttpObservable query) =>
query.WithReader(f => f.Content.ReadAsStringAsync());
public static IObservable<HttpFetch<string>> Text(this IHttpObservable query, Encoding encoding) =>
query.WithReader(async f => encoding.GetString(await f.Content.ReadAsByteArrayAsync()));
public static IObservable<HttpFetch<string>> Text(this IObservable<HttpFetch<HttpContent>> query) =>
from fetch in query
from text in fetch.Content.ReadAsStringAsync()
select fetch.WithContent(text);
public static IObservable<HttpFetch<string>> Text(this IObservable<HttpFetch<HttpContent>> query, Encoding encoding) =>
from fetch in query
from bytes in fetch.Content.ReadAsByteArrayAsync()
select fetch.WithContent(encoding.GetString(bytes));
}
}
| apache-2.0 | C# |
d115bf246b89ad2f6ab546c2724bd73810f1add4 | Add the base of RazorPagesOptions into ResponsiveServices | wangkanai/Detection | src/DependencyInjection/BuilderExtensions/Responsive.cs | src/DependencyInjection/BuilderExtensions/Responsive.cs | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Wangkanai.Detection.Hosting;
using Wangkanai.Detection.Services;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ResponsiveBuilderExtensions
{
public static IDetectionBuilder AddResponsiveService(this IDetectionBuilder builder)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
builder.Services.TryAddTransient<IResponsiveService, ResponsiveService>();
builder.Services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new ResponsiveViewLocationExpander(ResponsiveViewLocationFormat.Suffix));
options.ViewLocationExpanders.Add(new ResponsiveViewLocationExpander(ResponsiveViewLocationFormat.Subfolder));
});
builder.Services.Configure<RazorPagesOptions>(options => { });
return builder;
}
}
} | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Wangkanai.Detection.Hosting;
using Wangkanai.Detection.Services;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ResponsiveBuilderExtensions
{
public static IDetectionBuilder AddResponsiveService(this IDetectionBuilder builder)
{
if (builder == null)
throw new ArgumentNullException(nameof(builder));
builder.Services.TryAddTransient<IResponsiveService, ResponsiveService>();
builder.Services.Configure<RazorViewEngineOptions>(options =>
{
options.ViewLocationExpanders.Add(new ResponsiveViewLocationExpander(ResponsiveViewLocationFormat.Suffix));
options.ViewLocationExpanders.Add(new ResponsiveViewLocationExpander(ResponsiveViewLocationFormat.Subfolder));
});
return builder;
}
}
} | apache-2.0 | C# |
69238e8ea688144939499a178a8583e1205d065e | Allow pre-creation sync pins | TheBerkin/Rant | Rant/Engine/Constructs/SyncManager.cs | Rant/Engine/Constructs/SyncManager.cs | using System.Collections.Generic;
namespace Rant.Engine.Constructs
{
internal class SyncManager
{
private readonly Dictionary<string, Synchronizer> _syncTable =
new Dictionary<string, Synchronizer>();
private readonly HashSet<string> _pinQueue = new HashSet<string>();
private readonly Sandbox _sb;
public SyncManager(Sandbox sb)
{
_sb = sb;
}
public void Create(string name, SyncType type, bool apply)
{
Synchronizer sync;
if (!_syncTable.TryGetValue(name, out sync))
sync = _syncTable[name] =
new Synchronizer(type, _sb.RNG.NextRaw())
{
Pinned = _pinQueue.Remove(name)
};
if (apply) _sb.CurrentBlockAttribs.Sync = sync;
}
public void Apply(string name)
{
Synchronizer sync;
if (_syncTable.TryGetValue(name, out sync))
_sb.CurrentBlockAttribs.Sync = sync;
}
public void SetPinned(string name, bool isPinned)
{
Synchronizer sync;
if (_syncTable.TryGetValue(name, out sync))
{
sync.Pinned = isPinned;
}
else if (isPinned)
{
_pinQueue.Add(name);
}
else
{
_pinQueue.Remove(name);
}
}
public void Step(string name)
{
Synchronizer sync;
if (_syncTable.TryGetValue(name, out sync))
sync.Step(true);
}
public void Reset(string name)
{
Synchronizer sync;
if (_syncTable.TryGetValue(name, out sync))
sync.Reset();
}
}
} | using System.Collections.Generic;
namespace Rant.Engine.Constructs
{
internal class SyncManager
{
private readonly Dictionary<string, Synchronizer> _syncTable =
new Dictionary<string, Synchronizer>();
private readonly Sandbox _sb;
public SyncManager(Sandbox sb)
{
_sb = sb;
}
public void Create(string name, SyncType type, bool apply)
{
Synchronizer sync;
if (!_syncTable.TryGetValue(name, out sync))
sync = _syncTable[name] = new Synchronizer(type, _sb.RNG.NextRaw());
if (apply) _sb.CurrentBlockAttribs.Sync = sync;
}
public void Apply(string name)
{
Synchronizer sync;
if (_syncTable.TryGetValue(name, out sync))
_sb.CurrentBlockAttribs.Sync = sync;
}
public void SetPinned(string name, bool isPinned)
{
Synchronizer sync;
if (_syncTable.TryGetValue(name, out sync))
sync.Pinned = isPinned;
}
public void Step(string name)
{
Synchronizer sync;
if (_syncTable.TryGetValue(name, out sync))
sync.Step(true);
}
public void Reset(string name)
{
Synchronizer sync;
if (_syncTable.TryGetValue(name, out sync))
sync.Reset();
}
}
} | mit | C# |
5bb38b39c9aba2240b9fab056c672f7fcccd384c | Undo breaking change | umbraco/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS | src/Umbraco.Web.BackOffice/Install/InstallController.cs | src/Umbraco.Web.BackOffice/Install/InstallController.cs | using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.WebAssets;
using Umbraco.Cms.Infrastructure.Install;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Filters;
using Umbraco.Extensions;
namespace Umbraco.Cms.Web.BackOffice.Install;
/// <summary>
/// The Installation controller
/// </summary>
[InstallAuthorize]
[Area(Constants.Web.Mvc.InstallArea)]
public class InstallController : Controller
{
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly GlobalSettings _globalSettings;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly InstallHelper _installHelper;
private readonly LinkGenerator _linkGenerator;
private readonly ILogger<InstallController> _logger;
private readonly IRuntimeState _runtime;
private readonly IRuntimeMinifier _runtimeMinifier;
private readonly IUmbracoVersion _umbracoVersion;
public InstallController(
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
InstallHelper installHelper,
IRuntimeState runtime,
IOptions<GlobalSettings> globalSettings,
IRuntimeMinifier runtimeMinifier,
IHostingEnvironment hostingEnvironment,
IUmbracoVersion umbracoVersion,
ILogger<InstallController> logger,
LinkGenerator linkGenerator)
{
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_installHelper = installHelper;
_runtime = runtime;
_globalSettings = globalSettings.Value;
_runtimeMinifier = runtimeMinifier;
_hostingEnvironment = hostingEnvironment;
_umbracoVersion = umbracoVersion;
_logger = logger;
_linkGenerator = linkGenerator;
}
[HttpGet]
[StatusCodeResult(HttpStatusCode.ServiceUnavailable)]
public async Task<ActionResult> Index()
{
// Get the install base URL
ViewData.SetInstallApiBaseUrl(_linkGenerator.GetInstallerApiUrl());
// Get the base umbraco folder
var baseFolder = _hostingEnvironment.ToAbsolute(_globalSettings.UmbracoPath);
ViewData.SetUmbracoBaseFolder(baseFolder);
ViewData.SetUmbracoVersion(_umbracoVersion.SemanticVersion);
await _installHelper.SetInstallStatusAsync(false, string.Empty);
return View(Path.Combine(Constants.SystemDirectories.Umbraco.TrimStart("~"), Constants.Web.Mvc.InstallArea, nameof(Index) + ".cshtml"));
}
[HttpGet]
[IgnoreFromNotFoundSelectorPolicy]
public ActionResult Redirect() => NotFound();
}
| using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.WebAssets;
using Umbraco.Cms.Infrastructure.Install;
using Umbraco.Cms.Web.Common.Filters;
using Umbraco.Extensions;
namespace Umbraco.Cms.Web.BackOffice.Install;
/// <summary>
/// The Installation controller
/// </summary>
[InstallAuthorize]
[Area(Constants.Web.Mvc.InstallArea)]
public class InstallController : Controller
{
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly GlobalSettings _globalSettings;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly InstallHelper _installHelper;
private readonly LinkGenerator _linkGenerator;
private readonly ILogger<InstallController> _logger;
private readonly IRuntimeState _runtime;
private readonly IRuntimeMinifier _runtimeMinifier;
private readonly IUmbracoVersion _umbracoVersion;
public InstallController(
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
InstallHelper installHelper,
IRuntimeState runtime,
IOptions<GlobalSettings> globalSettings,
IRuntimeMinifier runtimeMinifier,
IHostingEnvironment hostingEnvironment,
IUmbracoVersion umbracoVersion,
ILogger<InstallController> logger,
LinkGenerator linkGenerator)
{
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_installHelper = installHelper;
_runtime = runtime;
_globalSettings = globalSettings.Value;
_runtimeMinifier = runtimeMinifier;
_hostingEnvironment = hostingEnvironment;
_umbracoVersion = umbracoVersion;
_logger = logger;
_linkGenerator = linkGenerator;
}
[HttpGet]
[StatusCodeResult(HttpStatusCode.ServiceUnavailable)]
public async Task<ActionResult> Index()
{
// Get the install base URL
ViewData.SetInstallApiBaseUrl(_linkGenerator.GetInstallerApiUrl());
// Get the base umbraco folder
var baseFolder = _hostingEnvironment.ToAbsolute(_globalSettings.UmbracoPath);
ViewData.SetUmbracoBaseFolder(baseFolder);
ViewData.SetUmbracoVersion(_umbracoVersion.SemanticVersion);
await _installHelper.SetInstallStatusAsync(false, string.Empty);
return View(Path.Combine(Constants.SystemDirectories.Umbraco.TrimStart("~"), Constants.Web.Mvc.InstallArea, nameof(Index) + ".cshtml"));
}
}
| mit | C# |
6db71860e19ec76c565f7651d70e1b1132b64751 | Fix failing test. | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/UnitTests/GitHub.Api/SimpleApiClientFactoryTests.cs | src/UnitTests/GitHub.Api/SimpleApiClientFactoryTests.cs | using System;
using System.Threading.Tasks;
using GitHub.Api;
using GitHub.Primitives;
using GitHub.Services;
using GitHub.VisualStudio;
using NSubstitute;
using Xunit;
public class SimpleApiClientFactoryTests
{
public class TheCreateMethod
{
[Fact]
public async Task CreatesNewInstanceOfSimpleApiClient()
{
const string url = "https://github.com/github/CreatesNewInstanceOfSimpleApiClient";
var program = new Program();
var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>();
var wikiProbe = Substitute.For<IWikiProbe>();
var factory = new SimpleApiClientFactory(
program,
new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe),
new Lazy<IWikiProbe>(() => wikiProbe));
var client = await factory.Create(url);
Assert.Equal(url, client.OriginalUrl);
Assert.Equal(HostAddress.GitHubDotComHostAddress, client.HostAddress);
Assert.Same(client, await factory.Create(url)); // Tests caching.
}
}
public class TheClearFromCacheMethod
{
[Fact]
public async Task RemovesClientFromCache()
{
const string url = "https://github.com/github/RemovesClientFromCache";
var program = new Program();
var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>();
var wikiProbe = Substitute.For<IWikiProbe>();
var factory = new SimpleApiClientFactory(
program,
new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe),
new Lazy<IWikiProbe>(() => wikiProbe));
var client = await factory.Create(url);
factory.ClearFromCache(client);
Assert.NotSame(client, factory.Create(url));
}
}
}
| using System;
using System.Threading.Tasks;
using GitHub.Api;
using GitHub.Primitives;
using GitHub.Services;
using GitHub.VisualStudio;
using NSubstitute;
using Xunit;
public class SimpleApiClientFactoryTests
{
public class TheCreateMethod
{
[Fact]
public async Task CreatesNewInstanceOfSimpleApiClient()
{
const string url = "https://github.com/github/CreatesNewInstanceOfSimpleApiClient";
var program = new Program();
var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>();
var wikiProbe = Substitute.For<IWikiProbe>();
var factory = new SimpleApiClientFactory(
program,
new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe),
new Lazy<IWikiProbe>(() => wikiProbe));
var client = await factory.Create(url);
Assert.Equal(url, client.OriginalUrl);
Assert.Equal(HostAddress.GitHubDotComHostAddress, client.HostAddress);
Assert.Same(client, factory.Create(url)); // Tests caching.
}
}
public class TheClearFromCacheMethod
{
[Fact]
public async Task RemovesClientFromCache()
{
const string url = "https://github.com/github/RemovesClientFromCache";
var program = new Program();
var enterpriseProbe = Substitute.For<IEnterpriseProbeTask>();
var wikiProbe = Substitute.For<IWikiProbe>();
var factory = new SimpleApiClientFactory(
program,
new Lazy<IEnterpriseProbeTask>(() => enterpriseProbe),
new Lazy<IWikiProbe>(() => wikiProbe));
var client = await factory.Create(url);
factory.ClearFromCache(client);
Assert.NotSame(client, factory.Create(url));
}
}
}
| mit | C# |
669254af1354a6b670e59799fe6c557f254d0c93 | Fix gradle for win | xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents | Android/Kotlin/build.cake | Android/Kotlin/build.cake |
var TARGET = Argument("t", Argument("target", "Default"));
Task("binderate")
.Does(() =>
{
var configFile = MakeAbsolute(new FilePath("./config.json")).FullPath;
var basePath = MakeAbsolute(new DirectoryPath("./")).FullPath;
var exit = StartProcess("xamarin-android-binderator",
$"--config=\"{configFile}\" --basepath=\"{basePath}\"");
if (exit != 0) throw new Exception($"xamarin-android-binderator exited with code {exit}.");
});
Task("native")
.Does(() =>
{
var fn = IsRunningOnWindows() ? "gradlew.bat" : "gradlew";
var gradlew = MakeAbsolute((FilePath)("./native/" + fn));
var exit = StartProcess(gradlew, new ProcessSettings {
Arguments = "assemble",
WorkingDirectory = "./native/KotlinSample/"
});
if (exit != 0) throw new Exception($"Gradle exited with exit code {exit}.");
});
Task("externals")
.IsDependentOn("binderate")
.IsDependentOn("native");
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
var settings = new MSBuildSettings()
.SetConfiguration("Release")
.SetVerbosity(Verbosity.Minimal)
.WithRestore()
.WithProperty("DesignTimeBuild", "false")
.WithProperty("PackageOutputPath", MakeAbsolute((DirectoryPath)"./output/").FullPath)
.WithTarget("Pack");
MSBuild("./generated/Xamarin.Kotlin.sln", settings);
});
Task("nuget")
.IsDependentOn("libs");
Task("samples")
.IsDependentOn("libs")
.Does(() =>
{
var settings = new MSBuildSettings()
.SetConfiguration("Release")
.SetVerbosity(Verbosity.Minimal)
.WithRestore()
.WithProperty("DesignTimeBuild", "false");
MSBuild("./samples/KotlinSample.sln", settings);
});
Task("clean")
.Does(() =>
{
CleanDirectories("./generated/*/bin");
CleanDirectories("./generated/*/obj");
CleanDirectories("./externals/");
CleanDirectories("./generated/");
CleanDirectories("./native/.gradle");
CleanDirectories("./native/**/build");
});
Task("Default")
.IsDependentOn("externals")
.IsDependentOn("libs")
.IsDependentOn("nuget")
.IsDependentOn("samples");
RunTarget(TARGET);
|
var TARGET = Argument("t", Argument("target", "Default"));
Task("binderate")
.Does(() =>
{
var configFile = MakeAbsolute(new FilePath("./config.json")).FullPath;
var basePath = MakeAbsolute(new DirectoryPath("./")).FullPath;
var exit = StartProcess("xamarin-android-binderator",
$"--config=\"{configFile}\" --basepath=\"{basePath}\"");
if (exit != 0) throw new Exception($"xamarin-android-binderator exited with code {exit}.");
});
Task("native")
.Does(() =>
{
var gradlew = MakeAbsolute((FilePath)"./native/KotlinSample/gradlew");
var exit = StartProcess(gradlew, new ProcessSettings {
Arguments = "assemble",
WorkingDirectory = "./native/KotlinSample/"
});
if (exit != 0) throw new Exception($"Gradle exited with exit code {exit}.");
});
Task("externals")
.IsDependentOn("binderate")
.IsDependentOn("native");
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
var settings = new MSBuildSettings()
.SetConfiguration("Release")
.SetVerbosity(Verbosity.Minimal)
.WithRestore()
.WithProperty("DesignTimeBuild", "false")
.WithProperty("PackageOutputPath", MakeAbsolute((DirectoryPath)"./output/").FullPath)
.WithTarget("Pack");
MSBuild("./generated/Xamarin.Kotlin.sln", settings);
});
Task("nuget")
.IsDependentOn("libs");
Task("samples")
.IsDependentOn("libs")
.Does(() =>
{
var settings = new MSBuildSettings()
.SetConfiguration("Release")
.SetVerbosity(Verbosity.Minimal)
.WithRestore()
.WithProperty("DesignTimeBuild", "false");
MSBuild("./samples/KotlinSample.sln", settings);
});
Task("clean")
.Does(() =>
{
CleanDirectories("./generated/*/bin");
CleanDirectories("./generated/*/obj");
CleanDirectories("./externals/");
CleanDirectories("./generated/");
CleanDirectories("./native/.gradle");
CleanDirectories("./native/**/build");
});
Task("Default")
.IsDependentOn("externals")
.IsDependentOn("libs")
.IsDependentOn("nuget")
.IsDependentOn("samples");
RunTarget(TARGET);
| mit | C# |
9c9b8579eeb12ef31a6f5dfb326526b38409e092 | Check for JustShutUpIKnowWhatImDoing | GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity | Assets/Teak/Editor/TeakPostProcessScene.cs | Assets/Teak/Editor/TeakPostProcessScene.cs | #region License
/* Teak -- Copyright (C) 2016 GoCarrot Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region References
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
#endregion
public class TeakPostProcessScene
{
[PostProcessScene]
public static void OnPostprocessScene()
{
if(!mRanThisBuild)
{
mRanThisBuild = true;
if (!TeakSettings.JustShutUpIKnowWhatImDoing)
{
if(string.IsNullOrEmpty(TeakSettings.AppId))
{
Debug.LogError("Teak App Id needs to be assigned in the Edit/Teak menu.");
}
if(string.IsNullOrEmpty(TeakSettings.APIKey))
{
Debug.LogError("Teak API Key needs to be assigned in the Edit/Teak menu.");
}
Directory.CreateDirectory(Path.Combine(Application.dataPath, "Plugins/Android/res/values"));
XDocument doc = new XDocument(
new XElement("resources",
new XElement("string", TeakSettings.AppId, new XAttribute("name", "io_teak_app_id")),
new XElement("string", TeakSettings.APIKey, new XAttribute("name", "io_teak_api_key")),
String.IsNullOrEmpty(TeakSettings.GCMSenderId) ? null : new XElement("string", TeakSettings.GCMSenderId, new XAttribute("name", "io_teak_gcm_sender_id"))
)
);
doc.Save(Path.Combine(Application.dataPath, "Plugins/Android/res/values/teak.xml"));
}
}
}
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuildProject)
{
mRanThisBuild = false;
}
private static bool mRanThisBuild = false;
}
| #region License
/* Teak -- Copyright (C) 2016 GoCarrot Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region References
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
#endregion
public class TeakPostProcessScene
{
[PostProcessScene]
public static void OnPostprocessScene()
{
if(!mRanThisBuild)
{
mRanThisBuild = true;
if(string.IsNullOrEmpty(TeakSettings.AppId))
{
Debug.LogError("Teak App Id needs to be assigned in the Edit/Teak menu.");
}
if(string.IsNullOrEmpty(TeakSettings.APIKey))
{
Debug.LogError("Teak API Key needs to be assigned in the Edit/Teak menu.");
}
if (!TeakSettings.JustShutUpIKnowWhatImDoing)
{
Directory.CreateDirectory(Path.Combine(Application.dataPath, "Plugins/Android/res/values"));
XDocument doc = new XDocument(
new XElement("resources",
new XElement("string", TeakSettings.AppId, new XAttribute("name", "io_teak_app_id")),
new XElement("string", TeakSettings.APIKey, new XAttribute("name", "io_teak_api_key")),
String.IsNullOrEmpty(TeakSettings.GCMSenderId) ? null : new XElement("string", TeakSettings.GCMSenderId, new XAttribute("name", "io_teak_gcm_sender_id"))
)
);
doc.Save(Path.Combine(Application.dataPath, "Plugins/Android/res/values/teak.xml"));
}
}
}
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuildProject)
{
mRanThisBuild = false;
}
private static bool mRanThisBuild = false;
}
| apache-2.0 | C# |
467d05abca30e50f591c642f450b3a4bb4ec0f2d | update tree | pixel-stuff/ld_dare_32 | Unity/ludum-dare-32-PixelStuff/Assets/Scripts/Tree/tree.cs | Unity/ludum-dare-32-PixelStuff/Assets/Scripts/Tree/tree.cs | using UnityEngine;
using System.Collections;
public class tree : MonoBehaviour {
enum TreeState{
UP,
CHOPED,
FALLEN,
PICKED
};
public GameObject rightChop;
public GameObject leftChop;
public GameObject trunk;
public GameObject stump;
public float SecondeAnimation;
// Use this for initialization
private TreeState state;
private Transform fallenTransform;
private float remaningSeconde;
private float RotationZIteration;
void Start () {
state = TreeState.UP;
}
// Update is called once per frame
void Update () {
updatePosition ();
//test
if (this.gameObject.transform.position.x < 0) {
chopLeft();
chopRight();
}
//!test
if ( state == TreeState.UP && isChoped()) {
state = TreeState.CHOPED;
calculFallPosition();
remaningSeconde = SecondeAnimation;
}
if (state == TreeState.CHOPED && remaningSeconde > 0) {
remaningSeconde -= Time.deltaTime;
fall ();
}
if (remaningSeconde < 0) {
trunk.GetComponent<BoxCollider2D>().enabled = false;
state = TreeState.FALLEN;
}
}
void updatePosition(){
if (this.gameObject.transform.position.x > 0) {
this.gameObject.transform.position = new Vector3 (this.gameObject.transform.position.x - 0.1f, this.gameObject.transform.position.y, 0);
}
}
bool isChoped(){
return rightChop.GetComponent<ChopOnTree> ().isCompletlyChop() && leftChop.GetComponent<ChopOnTree> ().isCompletlyChop();
//return true;
}
void chopLeft(){
leftChop.GetComponent<ChopOnTree> ().triggerChop ();
}
void chopRight(){
rightChop.GetComponent<ChopOnTree> ().triggerChop ();
}
void calculFallPosition(){
RotationZIteration = (-90f) / SecondeAnimation;
}
void fall(){
//trunk.transform.position = new Vector3 (trunk.transform.position.x + PositionXIteration * Time.deltaTime, trunk.transform.position.y + PositionYIteration * Time.deltaTime, 0);
trunk.transform.RotateAround (stump.transform.position, new Vector3 (0, 0, 1), RotationZIteration * Time.deltaTime);
}
public bool isFallen(){
return state == TreeState.FALLEN;
}
}
| using UnityEngine;
using System.Collections;
public class tree : MonoBehaviour {
enum TreeState{
UP,
CHOPED,
FALLEN,
PICKED
};
public GameObject rightChop;
public GameObject leftChop;
public GameObject trunk;
public GameObject stump;
public float SecondeAnimation;
// Use this for initialization
private TreeState state;
private Transform fallenTransform;
private float remaningSeconde;
private float RotationZIteration;
void Start () {
state = TreeState.UP;
}
// Update is called once per frame
void Update () {
updatePosition ();
//test
if (this.gameObject.transform.position.x < 0) {
chopLeft();
chopRight();
}
//!test
if ( state == TreeState.UP && isChoped()) {
state = TreeState.CHOPED;
calculFallPosition();
remaningSeconde = SecondeAnimation;
}
if (state == TreeState.CHOPED && remaningSeconde > 0) {
remaningSeconde -= Time.deltaTime;
fall ();
}
if (remaningSeconde < 0) {
this.GetComponent<BoxCollider2D>().enabled = false;
state = TreeState.FALLEN;
}
}
void updatePosition(){
if (this.gameObject.transform.position.x > 0) {
this.gameObject.transform.position = new Vector3 (this.gameObject.transform.position.x - 0.1f, this.gameObject.transform.position.y, 0);
}
}
bool isChoped(){
return rightChop.GetComponent<ChopOnTree> ().isCompletlyChop() && leftChop.GetComponent<ChopOnTree> ().isCompletlyChop();
//return true;
}
void chopLeft(){
leftChop.GetComponent<ChopOnTree> ().triggerChop ();
}
void chopRight(){
rightChop.GetComponent<ChopOnTree> ().triggerChop ();
}
void calculFallPosition(){
RotationZIteration = (-90f) / SecondeAnimation;
}
void fall(){
//trunk.transform.position = new Vector3 (trunk.transform.position.x + PositionXIteration * Time.deltaTime, trunk.transform.position.y + PositionYIteration * Time.deltaTime, 0);
trunk.transform.RotateAround (stump.transform.position, new Vector3 (0, 0, 1), RotationZIteration * Time.deltaTime);
}
public bool isFallen(){
return state == TreeState.FALLEN;
}
}
| mit | C# |
97f5c3751b8808a72b681ae0a44ef1241bf1adda | Clarify Batch created and updated DateTime can be NULL | goshippo/shippo-csharp-client | Shippo/Batch.cs | Shippo/Batch.cs | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Shippo {
[JsonObject (MemberSerialization.OptIn)]
public class Batch : ShippoId {
[JsonProperty (PropertyName = "object_status")]
public string ObjectStatus { get; set; }
[JsonProperty (PropertyName = "object_created")]
public DateTime? ObjectCreated { get; set; }
[JsonProperty (PropertyName = "object_updated")]
public DateTime? ObjectUpdated { get; set; }
[JsonProperty (PropertyName = "object_owner")]
public string ObjectOwner { get; set; }
[JsonProperty (PropertyName = "default_carrier_account")]
public string DefaultCarrierAccount { get; set; }
[JsonProperty (PropertyName = "default_servicelevel_token")]
public string DefaultServicelevelToken { get; set; }
[JsonProperty (PropertyName = "label_filetype")]
public string LabelFiletype { get; set; }
[JsonProperty (PropertyName = "metadata")]
public string Metadata { get; set; }
[JsonProperty (PropertyName = "batch_shipments")]
public BatchShipments BatchShipments { get; set; }
[JsonProperty (PropertyName = "label_url")]
public List<String> LabelUrl { get; set; }
[JsonProperty (PropertyName = "object_results")]
public ObjectResults ObjectResults { get; set; }
}
}
| using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Shippo {
[JsonObject (MemberSerialization.OptIn)]
public class Batch : ShippoId {
[JsonProperty (PropertyName = "object_status")]
public string ObjectStatus { get; set; }
[JsonProperty (PropertyName = "object_created")]
public DateTime ObjectCreated { get; set; }
[JsonProperty (PropertyName = "object_updated")]
public DateTime ObjectUpdated { get; set; }
[JsonProperty (PropertyName = "object_owner")]
public string ObjectOwner { get; set; }
[JsonProperty (PropertyName = "default_carrier_account")]
public string DefaultCarrierAccount { get; set; }
[JsonProperty (PropertyName = "default_servicelevel_token")]
public string DefaultServicelevelToken { get; set; }
[JsonProperty (PropertyName = "label_filetype")]
public string LabelFiletype { get; set; }
[JsonProperty (PropertyName = "metadata")]
public string Metadata { get; set; }
[JsonProperty (PropertyName = "batch_shipments")]
public BatchShipments BatchShipments { get; set; }
[JsonProperty (PropertyName = "label_url")]
public List<String> LabelUrl { get; set; }
[JsonProperty (PropertyName = "object_results")]
public ObjectResults ObjectResults { get; set; }
}
}
| apache-2.0 | C# |
c149cc969e820a11a29c663458f46fdc4ca9005c | remove mysqlconnector from test | MaceWindu/linq2db,linq2db/linq2db,linq2db/linq2db,LinqToDB4iSeries/linq2db,LinqToDB4iSeries/linq2db,MaceWindu/linq2db | Tests/Linq/UserTests/Issue1486Tests.cs | Tests/Linq/UserTests/Issue1486Tests.cs | using LinqToDB;
using LinqToDB.Data;
using LinqToDB.DataProvider;
using NUnit.Framework;
using System.Data;
using System.Linq;
using Tests.Model;
namespace Tests.UserTests
{
[TestFixture]
public class Issue1486Tests : TestBase
{
public class IssueDataConnection : DataConnection
{
public IssueDataConnection(string configuration)
: base(GetDataProvider(configuration), GetConnection(configuration), true)
{
}
private new static IDataProvider GetDataProvider(string configuration)
{
return DataConnection.GetDataProvider(configuration);
}
private static IDbConnection GetConnection(string configuration)
{
string connStr = GetConnectionString(configuration);
return DataConnection.GetDataProvider(configuration).CreateConnection(connStr);
}
}
public class FactoryDataConnection : DataConnection
{
public FactoryDataConnection(string configuration)
: base(GetDataProvider(configuration), () => GetConnection(configuration))
{
}
private new static IDataProvider GetDataProvider(string configuration)
{
return DataConnection.GetDataProvider(configuration);
}
private static IDbConnection GetConnection(string configuration)
{
string connStr = GetConnectionString(configuration);
return DataConnection.GetDataProvider(configuration).CreateConnection(connStr);
}
}
// excluded providers don't support cloning and remove credentials from connection string
[Test]
public void TestConnectionStringCopy(
[DataSources(
false,
ProviderName.OracleManaged,
ProviderName.OracleNative,
ProviderName.SapHana)]
string context,
[Values]
bool providerSpecific)
{
using (new AllowMultipleQuery())
using (new AvoidSpecificDataProviderAPI(providerSpecific))
using (var db = new IssueDataConnection(context))
{
db.GetTable<Child>().LoadWith(p => p.Parent.Children).First();
}
}
[ActiveIssue("AvoidSpecificDataProviderAPI support missing", Configurations = new[] { ProviderName.OracleManaged, ProviderName.OracleNative })]
[Test]
public void TestFactory([DataSources(false)] string context, [Values] bool providerSpecific)
{
using (new AllowMultipleQuery())
using (new AvoidSpecificDataProviderAPI(providerSpecific))
using (var db = new FactoryDataConnection(context))
{
db.GetTable<Child>().LoadWith(p => p.Parent.Children).First();
}
}
}
}
| using LinqToDB;
using LinqToDB.Data;
using LinqToDB.DataProvider;
using NUnit.Framework;
using System.Data;
using System.Linq;
using Tests.Model;
namespace Tests.UserTests
{
[TestFixture]
public class Issue1486Tests : TestBase
{
public class IssueDataConnection : DataConnection
{
public IssueDataConnection(string configuration)
: base(GetDataProvider(configuration), GetConnection(configuration), true)
{
}
private new static IDataProvider GetDataProvider(string configuration)
{
return DataConnection.GetDataProvider(configuration);
}
private static IDbConnection GetConnection(string configuration)
{
string connStr = GetConnectionString(configuration);
return DataConnection.GetDataProvider(configuration).CreateConnection(connStr);
}
}
public class FactoryDataConnection : DataConnection
{
public FactoryDataConnection(string configuration)
: base(GetDataProvider(configuration), () => GetConnection(configuration))
{
}
private new static IDataProvider GetDataProvider(string configuration)
{
return DataConnection.GetDataProvider(configuration);
}
private static IDbConnection GetConnection(string configuration)
{
string connStr = GetConnectionString(configuration);
return DataConnection.GetDataProvider(configuration).CreateConnection(connStr);
}
}
// excluded providers don't support cloning and remove credentials from connection string
[Test]
public void TestConnectionStringCopy(
[DataSources(
false,
ProviderName.MySqlConnector,
ProviderName.OracleManaged,
ProviderName.OracleNative,
ProviderName.SapHana)]
string context,
[Values]
bool providerSpecific)
{
using (new AllowMultipleQuery())
using (new AvoidSpecificDataProviderAPI(providerSpecific))
using (var db = new IssueDataConnection(context))
{
db.GetTable<Child>().LoadWith(p => p.Parent.Children).First();
}
}
[ActiveIssue("AvoidSpecificDataProviderAPI support missing", Configurations = new[] { ProviderName.OracleManaged, ProviderName.OracleNative })]
[Test]
public void TestFactory([DataSources(false)] string context, [Values] bool providerSpecific)
{
using (new AllowMultipleQuery())
using (new AvoidSpecificDataProviderAPI(providerSpecific))
using (var db = new FactoryDataConnection(context))
{
db.GetTable<Child>().LoadWith(p => p.Parent.Children).First();
}
}
}
}
| mit | C# |
31c69422ce9bee636d9728c29c94e2eeef10af9d | Fix Line type | setchi/NoteEditor,setchi/NotesEditor | Assets/Scripts/Line.cs | Assets/Scripts/Line.cs | using UnityEngine;
public class Line
{
public Color color;
public Vector3 start;
public Vector3 end;
public Line(Vector3 start, Vector3 end, Color color)
{
this.color = color;
this.start = start;
this.end = end;
}
}
| using UnityEngine;
public struct Line
{
public Color color;
public Vector3 start;
public Vector3 end;
public Line(Vector3 start, Vector3 end, Color color)
{
this.color = color;
this.start = start;
this.end = end;
}
}
| mit | C# |
1cbf3100c35707320d4c29526c7ee4fca29fd41a | Update Evgeny Zborovsky ShortBioTagLine, WebSite and FeedUris. (#553) | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/EvgenyZborovsky.cs | src/Firehose.Web/Authors/EvgenyZborovsky.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class EvgenyZborovsky : IAmAMicrosoftMVP
{
public string FirstName => "Evgeny";
public string LastName => "Zborovsky";
public string StateOrRegion => "Estonia";
public string EmailAddress => "[email protected]";
public string ShortBioOrTagLine => "blogs, speaks, helps others and is an enthusiastic Xamarin developer.";
public Uri WebSite => new Uri("https://evgenyzborovsky.com/");
public IEnumerable<Uri> FeedUris
{
get
{
yield return new Uri("https://evgenyzborovsky.com/tag/xamarin-forms/feed/");
yield return new Uri("https://evgenyzborovsky.com/tag/xamarin/feed/");
}
}
public string TwitterHandle => "ezborovsky";
public string GravatarHash => "b8a0ab8445fafb38afdf26cb976df32f";
public string GitHubHandle => "yuv4ik";
public GeoPosition Position => new GeoPosition(58.3750372, 26.6625567);
public string FeedLanguageCode => "en";
}
}
| using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class EvgenyZborovsky : IAmAMicrosoftMVP
{
public string FirstName => "Evgeny";
public string LastName => "Zborovsky";
public string StateOrRegion => "Estonia";
public string EmailAddress => "[email protected]";
public string ShortBioOrTagLine => "blogs, speaks, helps others and is enthusiastic Xamarin developer.";
public Uri WebSite => new Uri("https://smellyc0de.wordpress.com/");
public IEnumerable<Uri> FeedUris
{
get
{
yield return new Uri("https://smellyc0de.wordpress.com/tag/xamarin-forms/feed/");
yield return new Uri("https://smellyc0de.wordpress.com/tag/xamarin/feed/");
}
}
public string TwitterHandle => "ezborovsky";
public string GravatarHash => "b8a0ab8445fafb38afdf26cb976df32f";
public string GitHubHandle => "yuv4ik";
public GeoPosition Position => new GeoPosition(58.3750372, 26.6625567);
public string FeedLanguageCode => "en";
}
}
| mit | C# |
a793cd693402c373ad131779ac28e3921847e191 | Add c# doc bits. | chtoucas/Narvalo.NET,chtoucas/Narvalo.NET | src/Narvalo.Cerbere/ControlFlowException.cs | src/Narvalo.Cerbere/ControlFlowException.cs | // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo
{
using System;
using Narvalo.Properties;
public class ControlFlowException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="ControlFlowException"/> class.
/// </summary>
public ControlFlowException() : base(Strings_Core.ControlFlowException_DefaultMessage) { }
/// <summary>
/// Initializes a new instance of the <see cref="ControlFlowException"/> class with
/// a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public ControlFlowException(string message) : base(message) { }
public ControlFlowException(string message, Exception innerException)
: base(message, innerException)
{ }
}
}
| // Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.
namespace Narvalo
{
using System;
using Narvalo.Properties;
public class ControlFlowException : Exception
{
public ControlFlowException() : base(Strings_Cerbere.ControlFlowException_DefaultMessage) { }
/// <summary>
/// Initializes a new instance of the <see cref="ControlFlowException"/> class with
/// a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public ControlFlowException(string message) : base(message) { }
public ControlFlowException(string message, Exception innerException)
: base(message, innerException)
{ }
}
}
| bsd-2-clause | C# |
02c13f7342bb70560671a2b53abf763489d15bbf | Fix parameter comparison | JakeGinnivan/ApiApprover | src/PublicApiGenerator/MethodNameBuilder.cs | src/PublicApiGenerator/MethodNameBuilder.cs | using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
namespace PublicApiGenerator
{
public static class MethodNameBuilder
{
public static string AugmentMethodNameWithMethodModifierMarkerTemplate(MethodDefinition methodDefinition,
MemberAttributes attributes)
{
var name = CSharpOperatorKeyword.Get(methodDefinition.Name);
if (methodDefinition.DeclaringType.IsInterface)
{
return name;
}
var isNew = methodDefinition.IsNew(typeDef => typeDef?.Methods, e =>
e.Name.Equals(methodDefinition.Name, StringComparison.Ordinal) &&
e.Parameters.Count == methodDefinition.Parameters.Count &&
e.Parameters.SequenceEqual(methodDefinition.Parameters, new ParameterTypeComparer()));
return ModifierMarkerNameBuilder.Build(methodDefinition, attributes, isNew, name,
CodeNormalizer.MethodModifierMarkerTemplate);
}
class ParameterTypeComparer : IEqualityComparer<ParameterDefinition>
{
public bool Equals(ParameterDefinition x, ParameterDefinition y)
{
return x?.ParameterType == y?.ParameterType;
}
public int GetHashCode(ParameterDefinition obj)
{
return obj.GetHashCode();
}
}
}
}
| using System;
using System.CodeDom;
using Mono.Cecil;
namespace PublicApiGenerator
{
public static class MethodNameBuilder
{
public static string AugmentMethodNameWithMethodModifierMarkerTemplate(MethodDefinition methodDefinition,
MemberAttributes attributes)
{
var name = CSharpOperatorKeyword.Get(methodDefinition.Name);
if (methodDefinition.DeclaringType.IsInterface)
{
return name;
}
var isNew = methodDefinition.IsNew(typeDef => typeDef?.Methods, e =>
e.Name.Equals(methodDefinition.Name, StringComparison.Ordinal) &&
e.Parameters.Count == methodDefinition.Parameters.Count);
return ModifierMarkerNameBuilder.Build(methodDefinition, attributes, isNew, name,
CodeNormalizer.MethodModifierMarkerTemplate);
}
}
}
| mit | C# |
e41aabd614c9b90e7529e920cf62e4bf33dc9ff5 | Add loadable gettypes | glenndierckx/RequestHandlers,Smartasses/RequestHandlers | src/RequestHandlers/RequestHandlerFinder.cs | src/RequestHandlers/RequestHandlerFinder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace RequestHandlers
{
public static class RequestHandlerFinder
{
public static RequestHandlerDefinition[] InAssembly(params Assembly[] assemblies)
{
return assemblies.SelectMany(x => x.GetLoadableTypes())
.Select(x => new
{
Type = x,
TypeInfo = x.GetTypeInfo()
})
.Where(x => x.TypeInfo.IsClass && !x.TypeInfo.IsAbstract && !x.TypeInfo.IsInterface && !x.TypeInfo.IsGenericTypeDefinition)
.SelectMany(x => GetRequestHandlerInterfaces(x.Type),
(type, definition) =>
new RequestHandlerDefinition
{
RequestHandlerType = type.Type,
RequestType = definition.Item1,
ResponseType = definition.Item2
}).ToArray();
}
private static IEnumerable<Tuple<Type, Type>> GetRequestHandlerInterfaces(Type type)
{
var requestHandlers = type.GetTypeInfo().GetInterfaces().Where(x => !x.GetTypeInfo().IsGenericTypeDefinition && x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequestHandler<,>));
foreach (var requestHandler in requestHandlers)
{
var typeArguments = requestHandler.GetTypeInfo().GetGenericArguments();
yield return Tuple.Create(typeArguments[0], typeArguments[1]);
}
}
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace RequestHandlers
{
public static class RequestHandlerFinder
{
public static RequestHandlerDefinition[] InAssembly(params Assembly[] assemblies)
{
return assemblies.SelectMany(x => x.GetTypes())
.Select(x => new
{
Type = x,
TypeInfo = x.GetTypeInfo()
})
.Where(x => x.TypeInfo.IsClass && !x.TypeInfo.IsAbstract && !x.TypeInfo.IsInterface && !x.TypeInfo.IsGenericTypeDefinition)
.SelectMany(x => GetRequestHandlerInterfaces(x.Type),
(type, definition) =>
new RequestHandlerDefinition
{
RequestHandlerType = type.Type,
RequestType = definition.Item1,
ResponseType = definition.Item2
}).ToArray();
}
private static IEnumerable<Tuple<Type, Type>> GetRequestHandlerInterfaces(Type type)
{
var requestHandlers = type.GetTypeInfo().GetInterfaces().Where(x => !x.GetTypeInfo().IsGenericTypeDefinition && x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequestHandler<,>));
foreach (var requestHandler in requestHandlers)
{
var typeArguments = requestHandler.GetTypeInfo().GetGenericArguments();
yield return Tuple.Create(typeArguments[0], typeArguments[1]);
}
}
}
} | mit | C# |
10c1bcb5e2c0667ab175acd32ad2cddf40325609 | Fix issue #34: ZeroLog cannot instantiate an appender from an external assembly | Abc-Arbitrage/ZeroLog | src/ZeroLog/Appenders/AppenderFactory.cs | src/ZeroLog/Appenders/AppenderFactory.cs | using System;
using System.Linq;
using Jil;
using ZeroLog.Config;
namespace ZeroLog.Appenders
{
public class AppenderFactory
{
public static IAppender CreateAppender(AppenderDefinition definition)
{
var appenderType = GetAppenderType(definition);
var appender = (IAppender)Activator.CreateInstance(appenderType);
appender.Name = definition.Name;
var appenderParameterType = GetAppenderParameterType(appenderType);
if (appenderParameterType != null)
{
var appenderParameters = GetAppenderParameters(definition, appenderParameterType);
var configureMethod = appenderType.GetMethod(nameof(IAppender<object>.Configure), new[] { appenderParameterType });
configureMethod?.Invoke(appender, new[] { appenderParameters });
}
return appender;
}
private static Type GetAppenderType(AppenderDefinition definition)
{
Type appenderType;
// Check if we have an assembly-qualified name of a type
if (definition.AppenderTypeName.IndexOf(',') >= 0)
{
appenderType = Type.GetType(definition.AppenderTypeName, true, false);
}
else
{
appenderType = AppDomain.CurrentDomain.GetAssemblies()
.Select(x => x.GetType(definition.AppenderTypeName))
.FirstOrDefault(x => x != null);
}
return appenderType;
}
private static object GetAppenderParameters(AppenderDefinition definition, Type appenderParameterType)
{
var appenderParameterJson = JSON.SerializeDynamic(definition.AppenderJsonConfig);
var appenderParameters = (object)JSON.Deserialize(appenderParameterJson, appenderParameterType);
return appenderParameters;
}
private static Type GetAppenderParameterType(Type appenderType)
{
var type = appenderType;
var implementedInterfaceTypes = type.GetInterfaces();
foreach (var interfaceType in implementedInterfaceTypes)
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IAppender<>))
return interfaceType.GetGenericArguments()[0];
}
return null;
}
}
}
| using System;
using System.Linq;
using Jil;
using ZeroLog.Config;
namespace ZeroLog.Appenders
{
public class AppenderFactory
{
public static IAppender CreateAppender(AppenderDefinition definition)
{
var appenderType = GetAppenderType(definition);
var appender = (IAppender)Activator.CreateInstance(appenderType);
appender.Name = definition.Name;
var appenderParameterType = GetAppenderParameterType(appenderType);
if (appenderParameterType != null)
{
var appenderParameters = GetAppenderParameters(definition, appenderParameterType);
var configureMethod = appenderType.GetMethod(nameof(IAppender<object>.Configure), new[] { appenderParameterType });
configureMethod?.Invoke(appender, new[] { appenderParameters });
}
return appender;
}
private static Type GetAppenderType(AppenderDefinition definition)
{
var appenderType = AppDomain.CurrentDomain.GetAssemblies()
.Select(x => x.GetType(definition.AppenderTypeName))
.FirstOrDefault(x => x != null);
return appenderType;
}
private static object GetAppenderParameters(AppenderDefinition definition, Type appenderParameterType)
{
var appenderParameterJson = JSON.SerializeDynamic(definition.AppenderJsonConfig);
var appenderParameters = (object)JSON.Deserialize(appenderParameterJson, appenderParameterType);
return appenderParameters;
}
private static Type GetAppenderParameterType(Type appenderType)
{
var type = appenderType;
var implementedInterfaceTypes = type.GetInterfaces();
foreach (var interfaceType in implementedInterfaceTypes)
{
if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IAppender<>))
return interfaceType.GetGenericArguments()[0];
}
return null;
}
}
}
| mit | C# |
1049caef0083de7ce9b5f7823e417fbad0bd8805 | Add additional parameters | Distant/MetroTileEditor | Editor/BlockEditWindow.cs | Editor/BlockEditWindow.cs | using UnityEngine;
using UnityEditor;
namespace MetroTileEditor.Editors
{
[InitializeOnLoad]
public class BlockEditWindow : EditorWindow
{
public static BlockData currentData;
[MenuItem("Window/BlockEditor")]
static void Init()
{
EditorWindow window = GetWindow<BlockEditWindow>();
GUIContent content = new GUIContent();
content.text = "Block Editor";
window.titleContent = content;
window.autoRepaintOnSceneChange = true;
window.Show();
}
void OnInspectorUpdate()
{
Repaint();
}
void OnEnable()
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
SceneView.onSceneGUIDelegate += OnSceneGUI;
}
void OnDisable()
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
}
void OnGUI()
{
if (currentData != null)
{
GUILayout.Label(currentData.blockType);
currentData.breakable = EditorGUILayout.Toggle("Breakable", currentData.breakable);
currentData.isTriggerOnly = EditorGUILayout.Toggle("Is Trigger (no collision)", currentData.isTriggerOnly);
currentData.excludeFromMesh = EditorGUILayout.Toggle("Exclude from mesh", currentData.excludeFromMesh);
}
}
void OnSceneGUI(SceneView sceneView)
{
}
}
}
| using UnityEngine;
using UnityEditor;
namespace MetroTileEditor.Editors
{
[InitializeOnLoad]
public class BlockEditWindow : EditorWindow
{
public static BlockData currentData;
[MenuItem("Window/BlockEditor")]
static void Init()
{
EditorWindow window = GetWindow<BlockEditWindow>();
GUIContent content = new GUIContent();
content.text = "Block Editor";
window.titleContent = content;
window.autoRepaintOnSceneChange = true;
window.Show();
}
void OnInspectorUpdate()
{
Repaint();
}
void OnEnable()
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
SceneView.onSceneGUIDelegate += OnSceneGUI;
}
void OnDisable()
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
}
void OnGUI()
{
if (currentData != null)
{
GUILayout.Label(currentData.blockType);
currentData.breakable = EditorGUILayout.Toggle("Breakable", currentData.breakable);
}
}
void OnSceneGUI(SceneView sceneView)
{
}
}
}
| mit | C# |
e0ca905efa5ef1f4a48e8d0b17a599a4715827aa | Fix error with multithreaded UniversalDetector reseting | MSayfullin/EncodingConverter | EncodingConverter/Logic/EncodingManager.cs | EncodingConverter/Logic/EncodingManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dokas.FluentStrings;
using Mozilla.CharDet;
namespace dokas.EncodingConverter.Logic
{
internal sealed class EncodingManager
{
private readonly FileManager _fileManager;
private static readonly IEnumerable<Encoding> _encodings;
static EncodingManager()
{
_encodings = Encoding.GetEncodings().Select(e => e.GetEncoding()).ToArray();
}
public static IEnumerable<Encoding> Encodings
{
get { return _encodings; }
}
public EncodingManager(FileManager fileManager)
{
_fileManager = fileManager;
}
public async Task<Encoding> Resolve(string filePath)
{
UniversalDetector detector = null;
await Task.Factory.StartNew(() =>
{
var bytes = _fileManager.Load(filePath);
detector = new UniversalDetector();
detector.HandleData(bytes);
});
return !detector.DetectedCharsetName.IsEmpty() ? Encoding.GetEncoding(detector.DetectedCharsetName) : null;
}
public void Convert(string filePath, Encoding from, Encoding to)
{
if (from == null)
{
throw new ArgumentOutOfRangeException("from");
}
if (to == null)
{
throw new ArgumentOutOfRangeException("to");
}
var bytes = _fileManager.Load(filePath);
var convertedBytes = Encoding.Convert(from, to, bytes);
_fileManager.Save(filePath, convertedBytes);
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using dokas.FluentStrings;
using Mozilla.CharDet;
namespace dokas.EncodingConverter.Logic
{
internal sealed class EncodingManager
{
private readonly FileManager _fileManager;
private static readonly IEnumerable<Encoding> _encodings;
private static readonly UniversalDetector _detector;
static EncodingManager()
{
_encodings = Encoding.GetEncodings().Select(e => e.GetEncoding()).ToArray();
_detector = new UniversalDetector();
}
public static IEnumerable<Encoding> Encodings
{
get { return _encodings; }
}
public EncodingManager(FileManager fileManager)
{
_fileManager = fileManager;
}
public async Task<Encoding> Resolve(string filePath)
{
_detector.Reset();
await Task.Factory.StartNew(() =>
{
var bytes = _fileManager.Load(filePath);
_detector.HandleData(bytes);
});
return !_detector.DetectedCharsetName.IsEmpty() ? Encoding.GetEncoding(_detector.DetectedCharsetName) : null;
}
public void Convert(string filePath, Encoding from, Encoding to)
{
var bytes = _fileManager.Load(filePath);
var convertedBytes = Encoding.Convert(from, to, bytes);
_fileManager.Save(filePath, convertedBytes);
}
}
}
| mit | C# |
84f09fea6891612d73a67c9b135e868b668d2597 | update stats | annaked/ExpressEntryCalculator,annaked/ExpressEntryCalculator,annaked/ExpressEntryCalculator | ExpressEntryCalculator.Api/GetLastStats.cs | ExpressEntryCalculator.Api/GetLastStats.cs | using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using ExpressEntryCalculator.Api.Models;
namespace ExpressEntryCalculator.Api
{
public static class GetLastStats
{
[FunctionName("stats")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var lastStats = new ExpressEntryStats
{
InvitationsIssued = 3232,
LowestScore = 467,
RoundDate = new DateTime(2020, 3, 23)
};
return new OkObjectResult(lastStats);
}
}
}
| using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using ExpressEntryCalculator.Api.Models;
namespace ExpressEntryCalculator.Api
{
public static class GetLastStats
{
[FunctionName("stats")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var lastStats = new ExpressEntryStats
{
InvitationsIssued = 3600,
LowestScore = 471,
RoundDate = new DateTime(2019, 11, 27)
};
return new OkObjectResult(lastStats);
}
}
}
| mit | C# |
c007dcf71c233b61dbc6db0252f1f54724e9a3e3 | Set Razor to be the only view engine | simoto/FabricStore,simoto/FabricStore,simoto/FabricStore | FabricStore/FabricStore.Web/Global.asax.cs | FabricStore/FabricStore.Web/Global.asax.cs | using FabricStore.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FabricStore.Data.Migrations;
using FabricStore.Web.Infrastructure.Mapping;
using System.Reflection;
namespace FabricStore.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext, MigrationConfiguration>());
var automapperConfig = new AutoMapperConfig(Assembly.GetExecutingAssembly());
automapperConfig.Execute();
}
}
}
| using FabricStore.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FabricStore.Data.Migrations;
using FabricStore.Web.Infrastructure.Mapping;
using System.Reflection;
namespace FabricStore.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext, MigrationConfiguration>());
var automapperConfig = new AutoMapperConfig(Assembly.GetExecutingAssembly());
automapperConfig.Execute();
}
}
}
| mit | C# |
f2a95c24afa4ed918fc01a78c196ce2809bbc789 | Add binaryTree.Clear(); to binary tree test. | Appius/Algorithms-and-Data-Structures | Data-Structures/BinaryTree/Program.cs | Data-Structures/BinaryTree/Program.cs | #region
using System;
using BinaryTree.Models;
#endregion
namespace BinaryTree
{
internal class Program
{
private static void Main()
{
var binaryTree = new BinaryTree<int> {5, 3, 9, 1, -5, 0, 2};
Console.WriteLine("{0}, count of items: {1}", binaryTree, binaryTree.Count);
const int val = 1;
Console.WriteLine("Removing value - {0}...", val);
binaryTree.Remove(val);
Console.WriteLine("{0}, count of items: {1}", binaryTree, binaryTree.Count);
Console.ReadKey();
binaryTree.Clear();
}
}
} | #region
using System;
using BinaryTree.Models;
#endregion
namespace BinaryTree
{
internal class Program
{
private static void Main()
{
var binaryTree = new BinaryTree<int> {5, 3, 9, 1, -5, 0, 2};
Console.WriteLine("{0}, count of items: {1}", binaryTree, binaryTree.Count);
const int val = 1;
Console.WriteLine("Removing value - {0}...", val);
binaryTree.Remove(val);
Console.WriteLine("{0}, count of items: {1}", binaryTree, binaryTree.Count);
Console.ReadKey();
}
}
} | apache-2.0 | C# |
e16741d6eb5dba68c0eb4d53171bcd72250eee3d | Change assembly copyright text | danielchalmers/SteamAccountSwitcher | SteamAccountSwitcher/Properties/AssemblyInfo.cs | SteamAccountSwitcher/Properties/AssemblyInfo.cs | #region
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
#endregion
// 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("Steam Account Switcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniel Chalmers Software")]
[assembly: AssemblyProduct("Steam Account Switcher")]
[assembly: AssemblyCopyright("© Daniel Chalmers 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("22E1FAEA-639E-400B-9DCB-F2D04EC126E1")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.*")]
[assembly: AssemblyFileVersion("2.1.0.0")] | #region
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
#endregion
// 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("Steam Account Switcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniel Chalmers Software")]
[assembly: AssemblyProduct("Steam Account Switcher")]
[assembly: AssemblyCopyright("\u00A9 2016 Daniel Chalmers")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("22E1FAEA-639E-400B-9DCB-F2D04EC126E1")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.*")]
[assembly: AssemblyFileVersion("2.1.0.0")] | mit | C# |
e87b4ebdefdd3384a83eaf70e2dade9ca3a422d2 | Fix environment variable name | masaedw/LineSharp | EchoBot/Controllers/LineController.cs | EchoBot/Controllers/LineController.cs | using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using LineSharp;
using LIneSharp.Messages;
namespace EchoBot.Controllers
{
[RoutePrefix("api/{controller}")]
public class LineController : ApiController
{
private LineClient Client;
public LineController()
{
var channelId = Environment.GetEnvironmentVariable("LINE_CHANNEL_ID");
var channelSecret = Environment.GetEnvironmentVariable("LINE_CHANNEL_SECRET");
var accessToken = Environment.GetEnvironmentVariable("LINE_CHANNEL_ACCESS_TOKEN");
Client = new LineClient(channelId, channelSecret, accessToken);
}
[HttpPost]
public async Task<HttpResponseMessage> Webhook()
{
var content = await Request.Content.ReadAsStringAsync();
var signature = Request.Headers.GetValues("X-Line-Signature").FirstOrDefault();
if (signature == null || !Client.ValidateSignature(content, signature))
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "not found");
}
var events = Client.ParseEvent(content);
foreach (var ev in events)
{
switch (ev.Type)
{
case "message":
var mev = (MessageEvent)ev;
switch (mev.Message.Type)
{
case "text":
var message = (TextMessage)mev.Message;
await Client.ReplyTextAsync(mev.ReplyToken, message.Text);
break;
}
break;
}
}
return Request.CreateResponse(HttpStatusCode.OK, "OK");
}
}
}
| using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using LineSharp;
using LIneSharp.Messages;
namespace EchoBot.Controllers
{
[RoutePrefix("api/{controller}")]
public class LineController : ApiController
{
private LineClient Client;
public LineController()
{
var channelId = Environment.GetEnvironmentVariable("LINE_CHANNEL_ID");
var channelSecret = Environment.GetEnvironmentVariable("LINE_CHANNEL_ID");
var accessToken = Environment.GetEnvironmentVariable("LINE_CHANNEL_ID");
Client = new LineClient(channelId, channelSecret, accessToken);
}
[HttpPost]
public async Task<HttpResponseMessage> Webhook()
{
var content = await Request.Content.ReadAsStringAsync();
var signature = Request.Headers.GetValues("X-Line-Signature").FirstOrDefault();
if (signature == null || !Client.ValidateSignature(content, signature))
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "not found");
}
var events = Client.ParseEvent(content);
foreach (var ev in events)
{
switch (ev.Type)
{
case "message":
var mev = (MessageEvent)ev;
switch (mev.Message.Type)
{
case "text":
var message = (TextMessage)mev.Message;
await Client.ReplyTextAsync(mev.ReplyToken, message.Text);
break;
}
break;
}
}
return Request.CreateResponse(HttpStatusCode.OK, "OK");
}
}
}
| mit | C# |
4564967108790490ab2179daf88838431bbf7f77 | Add Neon runtime information to NeonException | ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang,ghewgill/neon-lang | exec/csnex/Exceptions.cs | exec/csnex/Exceptions.cs | using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace csnex
{
[Serializable()]
public class NeonException: ApplicationException
{
public NeonException() {
}
public NeonException(string name, string info) : base(name) {
Name = name;
Info = info;
}
public NeonException(string message) : base(message) {
}
public NeonException(string message, params object[] args) : base(string.Format(message, args)) {
}
public NeonException(string message, System.Exception innerException) : base(message, innerException) {
}
// Satisfy Warning CA2240 to implement a GetObjectData() to our custom exception type.
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null) {
throw new ArgumentNullException("info");
}
info.AddValue("NeonException", Name);
info.AddValue("NeonInfo", Info);
base.GetObjectData(info, context);
}
public string Name;
public string Info;
}
[Serializable]
public class InvalidOpcodeException: NeonException
{
public InvalidOpcodeException() {
}
public InvalidOpcodeException(string message) : base(message) {
}
}
[Serializable]
public class BytecodeException: NeonException
{
public BytecodeException() {
}
public BytecodeException(string message) : base(message) {
}
}
[Serializable]
public class NotImplementedException: NeonException
{
public NotImplementedException() {
}
public NotImplementedException(string message) : base(message) {
}
}
[Serializable]
public class NeonRuntimeException: NeonException
{
public NeonRuntimeException()
{
}
public NeonRuntimeException(string name, string info) : base(name, info)
{
}
}
}
| using System;
namespace csnex
{
[Serializable()]
public class NeonException: ApplicationException
{
public NeonException() {
}
public NeonException(string message) : base(message) {
}
public NeonException(string message, params object[] args) : base(string.Format(message, args)) {
}
public NeonException(string message, System.Exception innerException) : base(message, innerException) {
}
}
[Serializable]
public class InvalidOpcodeException: NeonException
{
public InvalidOpcodeException() {
}
public InvalidOpcodeException(string message) : base(message) {
}
}
[Serializable]
public class BytecodeException: NeonException
{
public BytecodeException() {
}
public BytecodeException(string message) : base(message) {
}
}
[Serializable]
public class NotImplementedException: NeonException
{
public NotImplementedException() {
}
public NotImplementedException(string message) : base(message) {
}
}
}
| mit | C# |
5defc7ae67d9c6b68a6f0dc7bae5af5217df4cdc | Remove Enum.ToList from ListExtensions | RedWall/Futilities | Futilities/Futilities.ListExtensions/ListExtensions.cs | Futilities/Futilities.ListExtensions/ListExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Futilities.ListExtensions
{
public static class ListExtensions
{
public static void Kill<T>(this List<T> list)
{
list.Clear();
list.TrimExcess();
}
public static T GetValueOrDefault<T>(this List<T> list, int? index)
{
if (index.HasValue && index.Value >= 0 && list.Count() > index.Value)
return list[index.Value];
return default(T);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Futilities.ListExtensions
{
public static class ListExtensions
{
public static List<T> EnumToList<T>() => Enum.GetValues(typeof(T)).Cast<T>().ToList();
public static void Kill<T>(this List<T> list)
{
list.Clear();
list.TrimExcess();
}
public static T GetValueOrDefault<T>(this List<T> list, int? index)
{
if (index.HasValue && index.Value >= 0 && list.Count() > index.Value)
return list[index.Value];
return default(T);
}
}
}
| mit | C# |
31b1cd40b607d27c5c21199d801adcbfef23e1ce | Fix test | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | InfinniPlatform.MessageQueue.Tests/RabbitMqTestBase.cs | InfinniPlatform.MessageQueue.Tests/RabbitMqTestBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using InfinniPlatform.Helpers;
using InfinniPlatform.MessageQueue.RabbitMq.Connection;
using InfinniPlatform.MessageQueue.RabbitMq.Hosting;
using InfinniPlatform.MessageQueue.RabbitMq.Serialization;
using InfinniPlatform.Sdk.Logging;
using InfinniPlatform.Sdk.Queues.Consumers;
using Moq;
using NUnit.Framework;
namespace InfinniPlatform.MessageQueue.Tests
{
public class RabbitMqTestBase
{
internal static RabbitMqManager RabbitMqManager { get; set; }
[OneTimeSetUp]
public void SetUp()
{
RabbitMqManager = new RabbitMqManager(RabbitMqConnectionSettings.Default, TestConstants.ApplicationName);
RabbitMqManager.DeleteQueues(RabbitMqManager.GetQueues());
WindowsServices.StartService(TestConstants.ServiceName, TestConstants.WaitTimeout);
}
[OneTimeTearDown]
public void TearDown()
{
RabbitMqManager.DeleteQueues(RabbitMqManager.GetQueues());
}
public static void RegisterConsumers(IEnumerable<ITaskConsumer> taskConsumers, IEnumerable<IBroadcastConsumer> broadcastConsumers)
{
var logMock = new Mock<ILog>();
logMock.Setup(log => log.Debug(It.IsAny<object>(), It.IsAny<Dictionary<string, object>>(), It.IsAny<Exception>()))
.Callback((object message, Dictionary<string, object> context, Exception exception) => { Console.WriteLine(message); });
logMock.Setup(log => log.Info(It.IsAny<object>(), It.IsAny<Dictionary<string, object>>(), It.IsAny<Exception>()))
.Callback((object message, Dictionary<string, object> context, Exception exception) => { Console.WriteLine(message); });
logMock.Setup(log => log.Error(It.IsAny<object>(), It.IsAny<Dictionary<string, object>>(), It.IsAny<Exception>()))
.Callback((object message, Dictionary<string, object> context, Exception exception) => { Console.WriteLine(message); });
var perfLogMock = new Mock<IPerformanceLog>();
var messageConsumersManager = new MessageConsumersStartupInitializer(taskConsumers ?? Enumerable.Empty<ITaskConsumer>(), broadcastConsumers ?? Enumerable.Empty<IBroadcastConsumer>(), RabbitMqManager, new MessageSerializer(), logMock.Object, perfLogMock.Object);
messageConsumersManager.OnAfterStart();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using InfinniPlatform.Helpers;
using InfinniPlatform.MessageQueue.RabbitMq.Connection;
using InfinniPlatform.MessageQueue.RabbitMq.Hosting;
using InfinniPlatform.MessageQueue.RabbitMq.Serialization;
using InfinniPlatform.Sdk.Logging;
using InfinniPlatform.Sdk.Queues.Consumers;
using Moq;
using NUnit.Framework;
namespace InfinniPlatform.MessageQueue.Tests
{
public class RabbitMqTestBase
{
internal static RabbitMqManager RabbitMqManager { get; set; }
[OneTimeSetUp]
public void SetUp()
{
RabbitMqManager = new RabbitMqManager(RabbitMqConnectionSettings.Default, TestConstants.ApplicationName);
RabbitMqManager.DeleteQueues(RabbitMqManager.GetQueues());
WindowsServices.StartService(TestConstants.ServiceName, TestConstants.WaitTimeout);
}
[OneTimeTearDown]
public void TearDown()
{
RabbitMqManager.DeleteQueues(RabbitMqManager.GetQueues());
}
public static void RegisterConsumers(IEnumerable<ITaskConsumer> taskConsumers, IEnumerable<IBroadcastConsumer> broadcastConsumers)
{
var logMock = new Mock<ILog>();
logMock.Setup(log => log.Debug(It.IsAny<object>(), It.IsAny<Dictionary<string, object>>(), It.IsAny<Exception>()))
.Callback((object message, Dictionary<string, object> context, Exception exception) => { Console.WriteLine(message); });
logMock.Setup(log => log.Info(It.IsAny<object>(), It.IsAny<Dictionary<string, object>>(), It.IsAny<Exception>()))
.Callback((object message, Dictionary<string, object> context, Exception exception) => { Console.WriteLine(message); });
logMock.Setup(log => log.Error(It.IsAny<object>(), It.IsAny<Dictionary<string, object>>(), It.IsAny<Exception>()))
.Callback((object message, Dictionary<string, object> context, Exception exception) => { Console.WriteLine(message); });
var perfLogMock = new Mock<IPerformanceLog>();
perfLogMock.Setup(log => log.Log(It.IsAny<string>(), It.IsAny<DateTime>(), It.IsAny<string>()))
.Callback((string method, DateTime start, string outcome) => { Console.WriteLine(method); });
var messageConsumersManager = new MessageConsumersStartupInitializer(taskConsumers ?? Enumerable.Empty<ITaskConsumer>(), broadcastConsumers ?? Enumerable.Empty<IBroadcastConsumer>(), RabbitMqManager, new MessageSerializer(), logMock.Object, perfLogMock.Object);
messageConsumersManager.OnAfterStart();
}
}
} | agpl-3.0 | C# |
eb1f8a7981d7c7b5d0cfa4469c0750b07386eb05 | Make rename explicit | JohanLarsson/Gu.Wpf.Geometry | Gu.Wpf.Geometry.UiTests/Images/TestImage.cs | Gu.Wpf.Geometry.UiTests/Images/TestImage.cs | namespace Gu.Wpf.Geometry.UiTests
{
using System;
using System.Drawing;
using System.IO;
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public static class TestImage
{
internal static readonly string Current = GetCurrent();
[Explicit]
[Script]
public static void Rename()
{
var folder = @"C:\Git\_GuOrg\Gu.Wpf.Adorners\Gu.Wpf.Adorners.UiTests";
var oldName = "Red_border_default_visibility_width_100.png";
var newName = "Red_border_default_visibility_width_100.png";
foreach (var file in Directory.EnumerateFiles(folder, oldName, SearchOption.AllDirectories))
{
File.Move(file, file.Replace(oldName, newName, StringComparison.Ordinal));
}
foreach (var file in Directory.EnumerateFiles(folder, "*.cs", SearchOption.AllDirectories))
{
File.WriteAllText(file, File.ReadAllText(file).Replace(oldName, newName, StringComparison.Ordinal));
}
}
#pragma warning disable IDE0060, CA1801 // Remove unused parameter
internal static void OnFail(Bitmap? expected, Bitmap actual, string resource)
#pragma warning restore IDE0060, CA1801 // Remove unused parameter
{
var fullFileName = Path.Combine(Path.GetTempPath(), resource);
_ = Directory.CreateDirectory(Path.GetDirectoryName(fullFileName)!);
actual.Save(fullFileName);
TestContext.AddTestAttachment(fullFileName);
}
private static string GetCurrent()
{
if (WindowsVersion.IsWindows7())
{
return "Win7";
}
if (WindowsVersion.IsWindows10())
{
return "Win10";
}
if (WindowsVersion.CurrentContains("Windows Server 2019") ||
WindowsVersion.CurrentContains("Windows Server 2022"))
{
return "WinServer2019";
}
return WindowsVersion.CurrentVersionProductName;
}
}
}
| namespace Gu.Wpf.Geometry.UiTests
{
using System;
using System.Drawing;
using System.IO;
using Gu.Wpf.UiAutomation;
using NUnit.Framework;
public static class TestImage
{
internal static readonly string Current = GetCurrent();
[Script]
public static void Rename()
{
var folder = @"C:\Git\_GuOrg\Gu.Wpf.Adorners\Gu.Wpf.Adorners.UiTests";
var oldName = "Red_border_default_visibility_width_100.png";
var newName = "Red_border_default_visibility_width_100.png";
foreach (var file in Directory.EnumerateFiles(folder, oldName, SearchOption.AllDirectories))
{
File.Move(file, file.Replace(oldName, newName, StringComparison.Ordinal));
}
foreach (var file in Directory.EnumerateFiles(folder, "*.cs", SearchOption.AllDirectories))
{
File.WriteAllText(file, File.ReadAllText(file).Replace(oldName, newName, StringComparison.Ordinal));
}
}
#pragma warning disable IDE0060, CA1801 // Remove unused parameter
internal static void OnFail(Bitmap? expected, Bitmap actual, string resource)
#pragma warning restore IDE0060, CA1801 // Remove unused parameter
{
var fullFileName = Path.Combine(Path.GetTempPath(), resource);
_ = Directory.CreateDirectory(Path.GetDirectoryName(fullFileName)!);
actual.Save(fullFileName);
TestContext.AddTestAttachment(fullFileName);
}
private static string GetCurrent()
{
if (WindowsVersion.IsWindows7())
{
return "Win7";
}
if (WindowsVersion.IsWindows10())
{
return "Win10";
}
if (WindowsVersion.CurrentContains("Windows Server 2019") ||
WindowsVersion.CurrentContains("Windows Server 2022"))
{
return "WinServer2019";
}
return WindowsVersion.CurrentVersionProductName;
}
}
}
| mit | C# |
079cdbae7abd14fbfe16276f47904f06dbaa1f97 | Update 05-Scan-Test.cs | awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples | .dotnet/example_code/DynamoDB/TryDax/05-Scan-Test.cs | .dotnet/example_code/DynamoDB/TryDax/05-Scan-Test.cs | // snippet-sourcedescription:[ ]
// snippet-service:[dynamodb]
// snippet-keyword:[dotNET]
// snippet-keyword:[Amazon DynamoDB]
// snippet-keyword:[Code Sample]
// snippet-keyword:[ ]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[ ]
// snippet-sourceauthor:[AWS]
// snippet-start:[dynamodb.dotNET.trydax.05-Scan-Test]
/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file 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 Amazon.Runtime;
using Amazon.DAX;
using Amazon.DynamoDBv2.Model;
namespace ClientTest
{
class Program
{
static void Main(string[] args)
{
string endpointUri = args[0];
Console.WriteLine("Using DAX client - endpointUri=" + endpointUri);
var clientConfig = new DaxClientConfig(endpointUri)
{
AwsCredentials = FallbackCredentialsFactory.GetCredentials(
};
var client = new ClusterDaxClient(clientConfig);
var tableName = "TryDaxTable";
var iterations = 5;
var startTime = DateTime.Now;
for (var i = 0; i < iterations; i++)
{
var request = new ScanRequest()
{
TableName = tableName
};
var response = client.ScanAsync(request).Result;
Console.WriteLine(i + ": Scan succeeded");
}
var endTime = DateTime.Now;
TimeSpan timeSpan = endTime - startTime;
Console.WriteLine("Total time: " + timeSpan.TotalMilliseconds + " milliseconds");
Console.WriteLine("Hit <enter> to continue...");
Console.ReadLine();
}
}
}
// snippet-end:[dynamodb.dotNET.trydax.05-Scan-Test]
| // snippet-sourcedescription:[ ]
// snippet-service:[dynamodb]
// snippet-keyword:[dotNET]
// snippet-keyword:[Amazon DynamoDB]
// snippet-keyword:[Code Sample]
// snippet-keyword:[ ]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[ ]
// snippet-sourceauthor:[AWS]
// snippet-start:[dynamodb.dotNET.trydax.05-Scan-Test]
/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file 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 Amazon.Runtime;
using Amazon.DAX;
using Amazon.DynamoDBv2.Model;
using System.Collections.Generic;
using System;
using Amazon.DynamoDBv2;
using Amazon;
namespace ClientTest
{
class Program
{
static void Main(string[] args)
{
String hostName = args[0].Split(':')[0];
int port = Int32.Parse(args[0].Split(':')[1]);
Console.WriteLine("Using DAX client - hostname=" + hostName + ", port=" + port);
var clientConfig = new DaxClientConfig(hostName, port)
{
AwsCredentials = FallbackCredentialsFactory.GetCredentials(
};
var client = new ClusterDaxClient(clientConfig);
var tableName = "TryDaxTable";
var iterations = 5;
var startTime = DateTime.Now;
for (var i = 0; i < iterations; i++)
{
var request = new ScanRequest()
{
TableName = tableName
};
var response = client.ScanAsync(request).Result;
Console.WriteLine(i + ": Scan succeeded");
}
var endTime = DateTime.Now;
TimeSpan timeSpan = endTime - startTime;
Console.WriteLine("Total time: " + (int)timeSpan.TotalMilliseconds + " milliseconds");
Console.WriteLine("Hit <enter> to continue...");
Console.ReadLine();
}
}
}
// snippet-end:[dynamodb.dotNET.trydax.05-Scan-Test] | apache-2.0 | C# |
a43da2c8a70ec4272c5c0fbb49dd0403925b0f26 | Update deep link to LinuxAppDown | EricSten-MSFT/kudu,projectkudu/kudu,projectkudu/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,projectkudu/kudu,projectkudu/kudu,projectkudu/kudu | Kudu.Services.Web/Detectors/Default.cshtml | Kudu.Services.Web/Detectors/Default.cshtml | @{
var ownerName = Environment.GetEnvironmentVariable("WEBSITE_OWNER_NAME") ?? "";
var subscriptionId = ownerName;
var resourceGroup = Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP") ?? "";
var siteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "";
var hostName = Environment.GetEnvironmentVariable("HTTP_HOST") ?? "";
var slotName = "";
var path = "";
if (Request.QueryString["type"] != null && Request.QueryString["name"] != null)
{
path = string.Format("{0}%2F{1}", Request.QueryString["type"].ToString(), Request.QueryString["name"].ToString());
}
var index = ownerName.IndexOf('+');
if (index >= 0)
{
subscriptionId = ownerName.Substring(0, index);
}
string detectorPath;
if (!string.IsNullOrWhiteSpace(path))
{
detectorPath = path;
}
else
{
if (Kudu.Core.Helpers.OSDetector.IsOnWindows())
{
detectorPath = "analysis%2FappDownAnalysis";
}
else
{
detectorPath = "analysis%2FLinuxAppDown";
}
}
var hostNameIndex = hostName.IndexOf('.');
if (hostNameIndex >= 0)
{
hostName = hostName.Substring(0, hostNameIndex);
}
var runtimeSuffxIndex = siteName.IndexOf("__");
if (runtimeSuffxIndex >= 0)
{
siteName = siteName.Substring(0, runtimeSuffxIndex);
}
// Get the slot name
if (!hostName.Equals(siteName, StringComparison.CurrentCultureIgnoreCase))
{
var slotNameIndex = siteName.Length;
if (hostName.Length > slotNameIndex && hostName[slotNameIndex] == '-')
{
// Fix up hostName by removing "-SLOTNAME"
slotName = hostName.Substring(slotNameIndex + 1);
hostName = hostName.Substring(0, slotNameIndex);
}
}
var isSlot = !String.IsNullOrWhiteSpace(slotName) && !slotName.Equals("production", StringComparison.CurrentCultureIgnoreCase);
var detectorDeepLink = "https://portal.azure.com/?websitesextension_ext=asd.featurePath%3D"
+ detectorPath
+ "#resource/subscriptions/" + subscriptionId
+ "/resourceGroups/" + resourceGroup
+ "/providers/Microsoft.Web/sites/"
+ hostName
+ (isSlot ? "/slots/" + slotName : "")
+ "/troubleshoot";
Response.Redirect(detectorDeepLink);
}
| @{
var ownerName = Environment.GetEnvironmentVariable("WEBSITE_OWNER_NAME") ?? "";
var subscriptionId = ownerName;
var resourceGroup = Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP") ?? "";
var siteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "";
var hostName = Environment.GetEnvironmentVariable("HTTP_HOST") ?? "";
var slotName = "";
var path = "";
if (Request.QueryString["type"] != null && Request.QueryString["name"] != null)
{
path = string.Format("{0}%2F{1}", Request.QueryString["type"].ToString(), Request.QueryString["name"].ToString());
}
var index = ownerName.IndexOf('+');
if (index >= 0)
{
subscriptionId = ownerName.Substring(0, index);
}
string detectorPath;
if (!string.IsNullOrWhiteSpace(path))
{
detectorPath = path;
}
else
{
if (Kudu.Core.Helpers.OSDetector.IsOnWindows())
{
detectorPath = "analysis%2FappDownAnalysis";
}
else
{
detectorPath = "detectors%2FLinuxAppDown";
}
}
var hostNameIndex = hostName.IndexOf('.');
if (hostNameIndex >= 0)
{
hostName = hostName.Substring(0, hostNameIndex);
}
var runtimeSuffxIndex = siteName.IndexOf("__");
if (runtimeSuffxIndex >= 0)
{
siteName = siteName.Substring(0, runtimeSuffxIndex);
}
// Get the slot name
if (!hostName.Equals(siteName, StringComparison.CurrentCultureIgnoreCase))
{
var slotNameIndex = siteName.Length;
if (hostName.Length > slotNameIndex && hostName[slotNameIndex] == '-')
{
// Fix up hostName by removing "-SLOTNAME"
slotName = hostName.Substring(slotNameIndex + 1);
hostName = hostName.Substring(0, slotNameIndex);
}
}
var isSlot = !String.IsNullOrWhiteSpace(slotName) && !slotName.Equals("production", StringComparison.CurrentCultureIgnoreCase);
var detectorDeepLink = "https://portal.azure.com/?websitesextension_ext=asd.featurePath%3D"
+ detectorPath
+ "#resource/subscriptions/" + subscriptionId
+ "/resourceGroups/" + resourceGroup
+ "/providers/Microsoft.Web/sites/"
+ hostName
+ (isSlot ? "/slots/" + slotName : "")
+ "/troubleshoot";
Response.Redirect(detectorDeepLink);
}
| apache-2.0 | C# |
f535729687013cd0297e181853328179cff27f18 | Make field readonly | MHeasell/Mappy,MHeasell/Mappy | Mappy/Operations/CopyAreaOperation.cs | Mappy/Operations/CopyAreaOperation.cs | namespace Mappy.Operations
{
using Mappy.Collections;
public class CopyAreaOperation<T> : IReplayableOperation
{
private readonly IGrid<T> source;
private readonly IGrid<T> destination;
private readonly int sourceX;
private readonly int sourceY;
private readonly int destX;
private readonly int destY;
private readonly int width;
private readonly int height;
private readonly IGrid<T> oldContents;
public CopyAreaOperation(IGrid<T> source, IGrid<T> destination, int sourceX, int sourceY, int destX, int destY, int width, int height)
{
this.source = source;
this.destination = destination;
this.sourceX = sourceX;
this.sourceY = sourceY;
this.destX = destX;
this.destY = destY;
this.width = width;
this.height = height;
this.oldContents = new Grid<T>(width, height);
GridMethods.Copy(destination, this.oldContents, destX, destY, 0, 0, width, height);
}
public void Execute()
{
GridMethods.Copy(this.source, this.destination, this.sourceX, this.sourceY, this.destX, this.destY, this.width, this.height);
}
public void Undo()
{
GridMethods.Copy(this.oldContents, this.destination, this.destX, this.destY);
}
}
}
| namespace Mappy.Operations
{
using Mappy.Collections;
public class CopyAreaOperation<T> : IReplayableOperation
{
private readonly IGrid<T> source;
private readonly IGrid<T> destination;
private readonly int sourceX;
private readonly int sourceY;
private readonly int destX;
private readonly int destY;
private readonly int width;
private readonly int height;
private IGrid<T> oldContents;
public CopyAreaOperation(IGrid<T> source, IGrid<T> destination, int sourceX, int sourceY, int destX, int destY, int width, int height)
{
this.source = source;
this.destination = destination;
this.sourceX = sourceX;
this.sourceY = sourceY;
this.destX = destX;
this.destY = destY;
this.width = width;
this.height = height;
this.oldContents = new Grid<T>(width, height);
GridMethods.Copy(destination, this.oldContents, destX, destY, 0, 0, width, height);
}
public void Execute()
{
GridMethods.Copy(this.source, this.destination, this.sourceX, this.sourceY, this.destX, this.destY, this.width, this.height);
}
public void Undo()
{
GridMethods.Copy(this.oldContents, this.destination, this.destX, this.destY);
}
}
}
| mit | C# |
7a82c437e9dbfd61897ad37043a214f38e0943ea | Fix use of private addin registry | mhutch/MonoDevelop.AddinMaker,mhutch/MonoDevelop.AddinMaker | MonoDevelop.Addins.Tasks/AddinTask.cs | MonoDevelop.Addins.Tasks/AddinTask.cs | using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Addins;
namespace MonoDevelop.Addins.Tasks
{
public abstract class AddinTask : Task
{
[Required]
public string ConfigDir { get; set; }
[Required]
public string AddinsDir { get; set; }
[Required]
public string DatabaseDir { get; set; }
[Required]
public string BinDir { get; set; }
protected bool InitializeAddinRegistry ()
{
if (string.IsNullOrEmpty (ConfigDir))
Log.LogError ("ConfigDir must be specified");
if (string.IsNullOrEmpty (AddinsDir))
Log.LogError ("AddinsDir must be specified");
if (string.IsNullOrEmpty (DatabaseDir))
Log.LogError ("DatabaseDir must be specified");
if (string.IsNullOrEmpty (BinDir))
Log.LogError ("BinDir must be specified");
ConfigDir = Path.GetFullPath (ConfigDir);
BinDir = Path.GetFullPath (BinDir);
AddinsDir = Path.GetFullPath (AddinsDir);
DatabaseDir = Path.GetFullPath (DatabaseDir);
Registry = new AddinRegistry (
ConfigDir,
BinDir,
AddinsDir,
DatabaseDir
);
Log.LogMessage (MessageImportance.Normal, "Updating addin database at {0}", DatabaseDir);
Registry.Update (new LogProgressStatus (Log, 2));
return !Log.HasLoggedErrors;
}
protected AddinRegistry Registry { get; private set; }
}
}
| using System;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.Addins;
namespace MonoDevelop.Addins.Tasks
{
public abstract class AddinTask : Task
{
[Required]
public string ConfigDir { get; set; }
[Required]
public string AddinsDir { get; set; }
[Required]
public string DatabaseDir { get; set; }
[Required]
public string BinDir { get; set; }
protected bool InitializeAddinRegistry ()
{
if (string.IsNullOrEmpty (ConfigDir))
Log.LogError ("ConfigDir must be specified");
if (string.IsNullOrEmpty (AddinsDir))
Log.LogError ("AddinsDir must be specified");
if (string.IsNullOrEmpty (DatabaseDir))
Log.LogError ("DatabaseDir must be specified");
if (string.IsNullOrEmpty (BinDir))
Log.LogError ("BinDir must be specified");
Registry = new AddinRegistry (
ConfigDir,
BinDir,
AddinsDir,
DatabaseDir
);
Log.LogMessage (MessageImportance.Normal, "Updating addin database at {0}", DatabaseDir);
Registry.Update (new LogProgressStatus (Log, 2));
return !Log.HasLoggedErrors;
}
protected AddinRegistry Registry { get; private set; }
}
}
| mit | C# |
f48602849539e887eca5f1945330f29deccc859c | Use object instead of dynamic to improve performance by 200x | SnowflakePowered/michi | Michi/Functions/RemoteFunctionParameters.cs | Michi/Functions/RemoteFunctionParameters.cs | using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Michi.Functions
{
/// <summary>
/// Represents a keyed collection of function parameters.
/// Once added, parameters can not be accessed individually, but can be iterated upon.
/// </summary>
public class RemoteFunctionParameters : IEnumerable<KeyValuePair<string, object>>
{
private readonly IDictionary<string, dynamic> parameterDictionary;
public RemoteFunctionParameters()
{
this.parameterDictionary = new ConcurrentDictionary<string, object>();
}
internal T Param<T>(string key)
{
if (!this.parameterDictionary.ContainsKey(key)) return default(T);
object value = this.parameterDictionary[key];
return (value is T) ? (T)value : default(T);
}
public void Add(string key, object value)
{
this.parameterDictionary.Add(key, value);
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return this.parameterDictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Michi.Functions
{
/// <summary>
/// Represents a keyed collection of function parameters.
/// Once added, parameters can not be accessed individually, but can be iterated upon.
/// </summary>
public class RemoteFunctionParameters : IEnumerable<KeyValuePair<string, object>>
{
private readonly IDictionary<string, dynamic> parameterDictionary;
public RemoteFunctionParameters()
{
this.parameterDictionary = new ConcurrentDictionary<string, object>();
}
internal T Param<T>(string key)
{
if (!this.parameterDictionary.ContainsKey(key)) return default(T);
object value = this.parameterDictionary[key];
return (value is T) ? (T)value : default(T);
}
public void Add(string key, dynamic value)
{
this.parameterDictionary.Add(key, value);
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
return this.parameterDictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| mit | C# |
d5d34e4afb7a211a915471222d4b1ecf0d55a9a9 | move the privacy policy to the middle | AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us | src/www/Views/Shared/_LayoutBase.cshtml | src/www/Views/Shared/_LayoutBase.cshtml | @{ Layout = "_LayoutMinimal"; }
@section custom_head {
@await RenderSectionAsync("custom_head", required: false)
<partial name="_Favicons" />
<meta name="theme-color" content="#272b30">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine:bold&display=swap" />
<partial name="_css_site" />
@await RenderSectionAsync("stylesheets", required: false)
@await RenderSectionAsync("scripts_head", required: false)
}
@RenderBody()
<footer class="container-fluid">
<div class="row social">
<div class="col text-center">
<a class="hover-bright" target="_blank" rel="noopener" href="https://play.google.com/store/apps/developer?id=mmorano"><svg-icon icon="Android"></svg-icon></a>
<a class="hover-bright" target="_blank" rel="noopener" href="https://twitter.com/AerisG222"><svg-icon icon="Twitter"></svg-icon></a>
<a class="hover-bright" target="_blank" rel="noopener" href="https://www.linkedin.com/pub/mike-morano/0/b51/805"><svg-icon icon="LinkedIn"></svg-icon></a>
<a class="hover-bright" target="_blank" rel="noopener" href="https://github.com/AerisG222"><svg-icon icon="Github"></svg-icon></a>
<a class="hover-bright" target="_blank" rel="noopener" href="https://steamcommunity.com/profiles/76561197974977949/"><svg-icon icon="Steam"></svg-icon></a>
</div>
</div>
<div class="row privacy">
<div class="col text-center">
<a href="/privacy" style="text-decoration: none;">privacy policy</a>
</div>
</div>
<div class="row copyright">
<div class="col text-center">
<span>copyright © @(DateTime.Now.Year) mike morano | all rights reserved</span>
</div>
</div>
</footer>
<mini-profiler />
<partial name="_js_Bootstrap" />
@await RenderSectionAsync("scripts_footer", required: false)
<partial name="_js_GoogleAnalytics" />
| @{ Layout = "_LayoutMinimal"; }
@section custom_head {
@await RenderSectionAsync("custom_head", required: false)
<partial name="_Favicons" />
<meta name="theme-color" content="#272b30">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine:bold&display=swap" />
<partial name="_css_site" />
@await RenderSectionAsync("stylesheets", required: false)
@await RenderSectionAsync("scripts_head", required: false)
}
@RenderBody()
<footer class="container-fluid">
<div class="row social">
<div class="col text-center">
<a class="hover-bright" target="_blank" rel="noopener" href="https://play.google.com/store/apps/developer?id=mmorano"><svg-icon icon="Android"></svg-icon></a>
<a class="hover-bright" target="_blank" rel="noopener" href="https://twitter.com/AerisG222"><svg-icon icon="Twitter"></svg-icon></a>
<a class="hover-bright" target="_blank" rel="noopener" href="https://www.linkedin.com/pub/mike-morano/0/b51/805"><svg-icon icon="LinkedIn"></svg-icon></a>
<a class="hover-bright" target="_blank" rel="noopener" href="https://github.com/AerisG222"><svg-icon icon="Github"></svg-icon></a>
<a class="hover-bright" target="_blank" rel="noopener" href="https://steamcommunity.com/profiles/76561197974977949/"><svg-icon icon="Steam"></svg-icon></a>
</div>
</div>
<div class="row copyright">
<div class="col-4 offset-4 text-center">
<span>copyright © @(DateTime.Now.Year) mike morano | all rights reserved</span>
</div>
<div class="col-4 text-end">
<a href="/privacy" style="text-decoration: none;">privacy policy</a>
</div>
</div>
</footer>
<mini-profiler />
<partial name="_js_Bootstrap" />
@await RenderSectionAsync("scripts_footer", required: false)
<partial name="_js_GoogleAnalytics" />
| mit | C# |
a0880bfb11af268827252757f37aaa518ce6f875 | Support fields and highlights in responses | synhershko/HebrewSearch | NElasticsearch/NElasticsearch/Models/Hit.cs | NElasticsearch/NElasticsearch/Models/Hit.cs | using System.Collections.Generic;
using System.Diagnostics;
namespace NElasticsearch.Models
{
/// <summary>
/// Individual hit response from ElasticSearch.
/// </summary>
[DebuggerDisplay("{_type} in {_index} id {_id}")]
public class Hit<T>
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public double? _score { get; set; }
public T _source { get; set; }
public Dictionary<string, IEnumerable<object>> fields = new Dictionary<string, IEnumerable<object>>();
public Dictionary<string, IEnumerable<string>> highlight;
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace NElasticsearch.Models
{
/// <summary>
/// Individual hit response from ElasticSearch.
/// </summary>
[DebuggerDisplay("{_type} in {_index} id {_id}")]
public class Hit<T>
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public double? _score { get; set; }
public T _source { get; set; }
//public Dictionary<String, JToken> fields = new Dictionary<string, JToken>();
}
}
| agpl-3.0 | C# |
355664cb02f07d17cf31e8ff6f2bef8187bbcff3 | reformat view page to prevent excessively wrapping the title | TheRealJZ/slackernews,TheRealJZ/slackernews | SlackerNews/Website/Views/Home/Index.cshtml | SlackerNews/Website/Views/Home/Index.cshtml | @model List<Common.article>
@{
ViewBag.Title = "Slacker News - when reading hacker news is just too much";
}
<h2>Highest scoring stories submitted in the past 24 hours</h2>
@if (Model != null && Model.Any())
{
<div style="overflow-x: auto">
<table class="table table-striped table-condensed">
<thead>
<tr>
<th style="width:40px" class="text-right"><span class="glyphicon glyphicon-chevron-up"></span></th>
<th style="min-width:200px">Title</th>
<th>Created</th>
<th>Tags</th>
<th>Summary</th>
<th>Top Comment</th>
</tr>
</thead>
@foreach (var a in Model)
{
<tr>
<td><a href="https://news.ycombinator.com/[email protected]_article_id">@a.score</a></td>
<td><a href="@a.url">@a.title</a></td>
<td>@a.GetFormattedTimeSinceCreated()</td>
<td>@a.tags</td>
<td>@a.semantic_summary</td>
<td>@a.top_comment_text</td>
</tr>
}
</table>
</div>
}
| @model List<Common.article>
@{
ViewBag.Title = "Slacker News - when reading hacker news is just too much";
}
<h2>Highest scoring stories submitted in the past 24 hours</h2>
@if (Model != null && Model.Any())
{
<div style="overflow-x: auto">
<table class="table table-striped">
<thead>
<tr>
<th>Score</th>
<th>Title</th>
<th>Created</th>
<th>Tags</th>
<th>Summary</th>
<th>Top Comment</th>
</tr>
</thead>
@foreach (var a in Model)
{
<tr>
<td><a href="https://news.ycombinator.com/[email protected]_article_id">@a.score</a></td>
<td><a href="@a.url">@a.title</a></td>
<td>@a.GetFormattedTimeSinceCreated()</td>
<td>@a.tags</td>
<td>@a.semantic_summary</td>
<td>@a.top_comment_text</td>
</tr>
}
</table>
</div>
} | mit | C# |
e0fe94ed448a845553d9607bcfb36f0d5c161fff | Add documentation for device implementation. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Authentication/TraktDevice.cs | Source/Lib/TraktApiSharp/Authentication/TraktDevice.cs | namespace TraktApiSharp.Authentication
{
using Newtonsoft.Json;
using System;
/// <summary>
/// Represents a Trakt device response.
/// <para>
/// See also <seealso cref="TraktDeviceAuth.GenerateDeviceAsync()" />,
/// <seealso cref="TraktDeviceAuth.GenerateDeviceAsync(string)" />.<para />
/// See <a href="http://docs.trakt.apiary.io/#reference/authentication-devices/device-code/generate-new-device-codes">"Trakt API Doc - Devices: Device Code"</a> for more information.
/// </para>
/// </summary>
public class TraktDevice
{
/// <summary>
/// Initializes a new instance of the <see cref="TraktDevice" /> class.
/// <para>The instantiated device instance is invalid.</para>
/// </summary>
public TraktDevice()
{
Created = DateTime.UtcNow;
}
/// <summary>Gets or sets the actual device code.</summary>
[JsonProperty(PropertyName = "device_code")]
public string DeviceCode { get; set; }
/// <summary>Gets or sets the user code.</summary>
[JsonProperty(PropertyName = "user_code")]
public string UserCode { get; set; }
/// <summary>Gets or sets the verification URL.</summary>
[JsonProperty(PropertyName = "verification_url")]
public string VerificationUrl { get; set; }
/// <summary>Gets or sets the seconds, after which this device will expire.</summary>
[JsonProperty(PropertyName = "expires_in")]
public int ExpiresInSeconds { get; set; }
/// <summary>Gets or sets the interval, at which the access token should be polled.</summary>
[JsonProperty(PropertyName = "interval")]
public int IntervalInSeconds { get; set; }
/// <summary>
/// Returns, whether this device is valid.
/// <para>
/// A Trakt device is valid, as long as the actual <see cref="DeviceCode" />
/// is neither null nor empty and as long as this device is not expired.<para />
/// See also <seealso cref="ExpiresInSeconds" />.<para />
/// See also <seealso cref="IsExpiredUnused" />.<para />
/// </para>
/// </summary>
[JsonIgnore]
public bool IsValid => !string.IsNullOrEmpty(DeviceCode) && !IsExpiredUnused;
/// <summary>Gets the UTC DateTime, when this device was created.</summary>
[JsonIgnore]
public DateTime Created { get; private set; }
/// <summary>Gets, whether this device is expired without actually using it for polling for an access token.</summary>
[JsonIgnore]
public bool IsExpiredUnused => Created.AddSeconds(ExpiresInSeconds) <= DateTime.UtcNow;
}
}
| namespace TraktApiSharp.Authentication
{
using Newtonsoft.Json;
using System;
public class TraktDevice
{
public TraktDevice()
{
Created = DateTime.UtcNow;
}
[JsonProperty(PropertyName = "device_code")]
public string DeviceCode { get; set; }
[JsonProperty(PropertyName = "user_code")]
public string UserCode { get; set; }
[JsonProperty(PropertyName = "verification_url")]
public string VerificationUrl { get; set; }
[JsonProperty(PropertyName = "expires_in")]
public int ExpiresInSeconds { get; set; }
[JsonProperty(PropertyName = "interval")]
public int IntervalInSeconds { get; set; }
[JsonIgnore]
public bool IsValid => !string.IsNullOrEmpty(DeviceCode) && !IsExpiredUnused;
[JsonIgnore]
public DateTime Created { get; private set; }
[JsonIgnore]
public bool IsExpiredUnused => Created.AddSeconds(ExpiresInSeconds) <= DateTime.UtcNow;
}
}
| mit | C# |
1591c4b0318205f542a7e914341f5d4bd0c51b7d | Bump version to 0.5.2 | whampson/bft-spec,whampson/cascara | Src/WHampson.Bft/Properties/AssemblyInfo.cs | Src/WHampson.Bft/Properties/AssemblyInfo.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.BFT")]
[assembly: AssemblyDescription("Binary File Template parser.")]
[assembly: AssemblyProduct("WHampson.BFT")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.5.2")]
[assembly: AssemblyVersion("0.5.2")]
[assembly: AssemblyInformationalVersion("0.5.2")]
| #region License
/* Copyright (c) 2017 Wes Hampson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("WHampson.BFT")]
[assembly: AssemblyDescription("Binary File Template parser.")]
[assembly: AssemblyProduct("WHampson.BFT")]
[assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")]
[assembly: AssemblyFileVersion("0.5.1")]
[assembly: AssemblyVersion("0.5.1")]
[assembly: AssemblyInformationalVersion("0.5.1")]
| mit | C# |
68b6b47515c17441992497343554ffed5499d559 | rename contest demo namespace. | amiralles/contest,amiralles/contest | src/Contest.Demo/Demo.cs | src/Contest.Demo/Demo.cs | namespace Demo { //It doesn't match naming conventions but looks clear in the console ;)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _ = System.Action<Contest.Core.Runner>;
// ReSharper disable UnusedMember.Local
class Contest_101 {
_ this_is_a_passing_test = assert =>
assert.Equal(4, 2 + 2);
_ this_is_a_failing_test = assert =>
assert.Equal(5, 2 + 2);
_ this_is_a__should_throw__passing_test = test =>
test.ShouldThrow<NullReferenceException>(() => {
object target = null;
var dummy = target.ToString();
});
_ this_is_a__should_throw__failing_test = test =>
test.ShouldThrow<NullReferenceException>(() => {
//It doesn't throws; So it fails.
});
}
class Contest_201 {
_ before_each = test => {
User.Create("pipe");
User.Create("vilmis");
User.Create("amiralles");
};
_ after_each = test =>
User.Reset();
_ find_existing_user_returns_user = assert =>
assert.IsNotNull(User.Find("pipe"));
_ find_non_existing_user_returns_null = assert =>
assert.IsNull(User.Find("not exists"));
_ create_user_adds_new_user = assert => {
User.Create("foo");
assert.Equal(4, User.Count());
};
}
class Contest_301 {
// setup
_ before_echo = test =>
test.Bag["msg"] = "Hello World!";
//cleanup
_ after_echo = test =>
test.Bag["msg"] = null;
//actual test
_ echo = test =>
test.Equal("Hello World!", Utils.Echo(test.Bag["msg"]));
}
class Utils {
public static Func<object, object> Echo = msg => msg;
}
public class User {
static readonly List<string> _users = new List<string>();
public static Action Reset = () => _users.Clear();
public static Action<string> Create = name => _users.Add(name);
public static Func<int> Count = () => _users.Count;
public static Func<string, object> Find = name =>
_users.FirstOrDefault(u => u == name);
}
}
| namespace Contest.Demo {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _ = System.Action<Contest.Core.Runner>;
// ReSharper disable UnusedMember.Local
class Contest_101 {
_ this_is_a_passing_test = assert =>
assert.Equal(4, 2 + 2);
_ this_is_a_failing_test = assert =>
assert.Equal(5, 2 + 2);
_ this_is_a__should_throw__passing_test = test =>
test.ShouldThrow<NullReferenceException>(() => {
object target = null;
var dummy = target.ToString();
});
_ this_is_a__should_throw__failing_test = test =>
test.ShouldThrow<NullReferenceException>(() => {
//It doesn't throws; So it fails.
});
}
class Contest_201 {
_ before_each = test => {
User.Create("pipe");
User.Create("vilmis");
User.Create("amiralles");
};
_ after_each = test =>
User.Reset();
_ find_existing_user_returns_user = assert =>
assert.IsNotNull(User.Find("pipe"));
_ find_non_existing_user_returns_null = assert =>
assert.IsNull(User.Find("not exists"));
_ create_user_adds_new_user = assert => {
User.Create("foo");
assert.Equal(4, User.Count());
};
}
class Contest_301 {
// setup
_ before_echo = test =>
test.Bag["msg"] = "Hello World!";
//cleanup
_ after_echo = test =>
test.Bag["msg"] = null;
//actual test
_ echo = test =>
test.Equal("Hello World!", Utils.Echo(test.Bag["msg"]));
}
class Utils {
public static Func<object, object> Echo = msg => msg;
}
public class User {
static readonly List<string> _users = new List<string>();
public static Action Reset = () => _users.Clear();
public static Action<string> Create = name => _users.Add(name);
public static Func<int> Count = () => _users.Count;
public static Func<string, object> Find = name =>
_users.FirstOrDefault(u => u == name);
}
}
| mit | C# |
f3116f92c4c58b3fb0eb324aacea4b80382816f4 | Update SharedSlotType.cs | stoiveyp/Alexa.NET.Management | Alexa.NET.Management/SlotType/SharedSlotType.cs | Alexa.NET.Management/SlotType/SharedSlotType.cs | using Newtonsoft.Json;
namespace Alexa.NET.Management.SlotType
{
public class SharedSlotType
{
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description",NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
}
}
| using Newtonsoft.Json;
namespace Alexa.NET.Management.SlotType
{
public class SharedSlotType
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description",NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
}
}
| mit | C# |
35744f703b28a50d88ac9f8e0cbec4bddda212f5 | test fix for PostreSQL | enginekit/linq2db,AK107/linq2db,lvaleriu/linq2db,jogibear9988/linq2db,MaceWindu/linq2db,LinqToDB4iSeries/linq2db,MaceWindu/linq2db,linq2db/linq2db,LinqToDB4iSeries/linq2db,AK107/linq2db,sdanyliv/linq2db,lvaleriu/linq2db,jogibear9988/linq2db,inickvel/linq2db,linq2db/linq2db,genusP/linq2db,sdanyliv/linq2db,ronnyek/linq2db,genusP/linq2db | Tests/Linq/UserTests/Issue513Tests.cs | Tests/Linq/UserTests/Issue513Tests.cs | using LinqToDB;
using LinqToDB.Data;
using LinqToDB.Mapping;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tests.UserTests
{
[TestFixture]
public class Issue513Tests : TestBase
{
System.Threading.Semaphore _semaphore = new System.Threading.Semaphore(0, 10);
[Table ("Child")]
[Column("ParentID", "Parent.ParentID")]
public class Child513
{
[Association(ThisKey = "Parent.ParentID", OtherKey = "ParentID")]
public Parent513 Parent;
}
[Table("Parent")]
public class Parent513
{
[Column]
public int ParentID;
}
[DataContextSource(false)]
public void Test(string context)
{
var tasks = new Task[10];
for (var i = 0; i < 10; i++)
tasks[i] = new Task(() => TestInternal(context));
for (var i = 0; i < 10; i++)
tasks[i].Start();
System.Threading.Thread.Sleep(1000);
_semaphore.Release(10);
Task.WaitAll(tasks);
}
public void TestInternal(string context)
{
using (var db = GetDataContext(context))
{
_semaphore.WaitOne();
var r = db.GetTable<Child513>().Select(_ => _.Parent).Distinct();
Assert.IsNotEmpty(r);
}
}
}
}
| using LinqToDB;
using LinqToDB.Data;
using LinqToDB.Mapping;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tests.UserTests
{
[TestFixture]
public class Issue513Tests : TestBase
{
System.Threading.Semaphore _semaphore = new System.Threading.Semaphore(0, 10);
[Table ("Child")]
[Column("ParentId", "Parent.ParentId")]
public class Child513
{
[Association(ThisKey = "Parent.ParentId", OtherKey = "ParentId")]
public Parent513 Parent;
}
[Table("Parent")]
public class Parent513
{
[Column]
public int ParentId;
}
[DataContextSource(false)]
public void Test(string context)
{
var tasks = new Task[10];
for (var i = 0; i < 10; i++)
tasks[i] = new Task(() => TestInternal(context));
for (var i = 0; i < 10; i++)
tasks[i].Start();
System.Threading.Thread.Sleep(1000);
_semaphore.Release(10);
Task.WaitAll(tasks);
}
public void TestInternal(string context)
{
using (var db = GetDataContext(context))
{
_semaphore.WaitOne();
var r = db.GetTable<Child513>().Select(_ => _.Parent).Distinct();
Assert.IsNotEmpty(r);
}
}
}
}
| mit | C# |
ca06f2517dd6d9db42f9fb1db7831a32b1bdffdb | Remove unneccessary using | steven-r/Oberon0Compiler | oberon0/Definitions/BaseSelectorElement.cs | oberon0/Definitions/BaseSelectorElement.cs | #region copyright
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseSelectorElement.cs" company="Stephen Reindl">
// Copyright (c) Stephen Reindl. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
// </copyright>
// <summary>
// Part of oberon0 - Oberon0Compiler/BaseSelectorElement.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#endregion
namespace Oberon0.Compiler.Definitions
{
using Antlr4.Runtime;
using Oberon0.Compiler.Types;
public abstract class BaseSelectorElement
{
#pragma warning disable CS3001 // Argument type is not CLS-compliant
protected BaseSelectorElement(IToken tokenStart)
#pragma warning restore CS3001 // Argument type is not CLS-compliant
{
this.Token = tokenStart;
}
#pragma warning disable CS3003 // Type is not CLS-compliant
/// <summary>
/// Gets the token or available.
/// </summary>
public IToken Token { get; }
#pragma warning restore CS3003 // Type is not CLS-compliant
/// <summary>
/// Gets or sets the type definition.
/// </summary>
public TypeDefinition TypeDefinition { get; set; }
/// <summary>
/// Gets or sets the basic type definition. The base type definition represents the root type.
/// </summary>
public TypeDefinition BasicTypeDefinition { get; set; }
}
} | #region copyright
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseSelectorElement.cs" company="Stephen Reindl">
// Copyright (c) Stephen Reindl. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
// </copyright>
// <summary>
// Part of oberon0 - Oberon0Compiler/BaseSelectorElement.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#endregion
namespace Oberon0.Compiler.Definitions
{
using System;
using Antlr4.Runtime;
using Oberon0.Compiler.Types;
public abstract class BaseSelectorElement
{
#pragma warning disable CS3001 // Argument type is not CLS-compliant
protected BaseSelectorElement(IToken tokenStart)
#pragma warning restore CS3001 // Argument type is not CLS-compliant
{
this.Token = tokenStart;
}
#pragma warning disable CS3003 // Type is not CLS-compliant
/// <summary>
/// Gets the token or available.
/// </summary>
public IToken Token { get; }
#pragma warning restore CS3003 // Type is not CLS-compliant
/// <summary>
/// Gets or sets the type definition.
/// </summary>
public TypeDefinition TypeDefinition { get; set; }
/// <summary>
/// Gets or sets the basic type definition. The base type definition represents the root type.
/// </summary>
public TypeDefinition BasicTypeDefinition { get; set; }
}
} | mit | C# |
3b1e68c82b924f7a8d654161df73e8b5c85614a5 | Update Ques.cs | Xeeynamo/KingdomHearts | OpenKh.Kh2/Jiminy/Ques.cs | OpenKh.Kh2/Jiminy/Ques.cs | using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xe.BinaryMapper;
namespace OpenKh.Kh2.Jiminy
{
public class Ques
{
public const int MagicCode = 0x55514D4A;
public enum QuestStatus : ushort
{
Disabled = 0,
Draw = 1,
Cleared = 2,
FullyCleared = 3
}
[Data] public ushort World { get; set; }
[Data] public ushort CategoryText { get; set; }
[Data] public ushort Title { get; set; }
[Data] public QuestStatus Status { get; set; } //z_un_002a99c8
[Data] public ushort StoryFlag { get; set; }
[Data] public ushort GameId { get; set; }
[Data] public ushort Score { get; set; }
[Data] public ushort ClearCondition { get; set; }
public List<Ques> Read(Stream stream) => BaseJiminy<Ques>.Read(stream).Items;
public void Write(Stream stream, int version, IEnumerable<Ques> items) => BaseJiminy<Ques>.Write(stream, MagicCode, version, items.ToList());
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xe.BinaryMapper;
namespace OpenKh.Kh2.Jiminy
{
public class Ques
{
public const int MagicCode = 0x55514D4A;
[Data] public ushort World { get; set; }
[Data] public ushort CategoryText { get; set; }
[Data] public ushort Title { get; set; }
[Data] public ushort Stat { get; set; } //z_un_002a99c8
[Data] public ushort StoryFlag { get; set; }
[Data] public ushort GameId { get; set; }
[Data] public ushort Score { get; set; }
[Data] public ushort ClearCondition { get; set; }
public List<Ques> Read(Stream stream) => BaseJiminy<Ques>.Read(stream).Items;
public void Write(Stream stream, int version, IEnumerable<Ques> items) => BaseJiminy<Ques>.Write(stream, MagicCode, version, items.ToList());
}
}
| mit | C# |
3d600ab1bd3ba7af4be13a4f1c8844d447015a23 | change w.r.t Aspose.Slides for .NET 18.7 | aspose-slides/Aspose.Slides-for-.NET,asposeslides/Aspose_Slides_NET | Examples/CSharp/Charts/SettingFontProperties.cs | Examples/CSharp/Charts/SettingFontProperties.cs | using Aspose.Slides;
using Aspose.Slides.Charts;
using Aspose.Slides.Examples.CSharp;
using Aspose.Slides.Export;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp.Charts
{
class SettingFontProperties
{
public static void Run()
{
//ExStart:SettingFontProperties
string dataDir = RunExamples.GetDataDir_Charts();
using (Presentation pres = new Presentation(dataDir+"test.pptx"))
{
IChart chart = pres.Slides[0].Shapes.AddChart(ChartType.ClusteredColumn, 50, 50, 600, 400);
chart.HasDataTable = true;
chart.ChartDataTable.TextFormat.PortionFormat.FontBold = NullableBool.True;
chart.ChartDataTable.TextFormat.PortionFormat.FontHeight = 20;
pres.Save(dataDir+"output.pptx", SaveFormat.Pptx);
}
}
//ExEnd:SettingFontProperties
}
} | using Aspose.Slides;
using Aspose.Slides.Charts;
using Aspose.Slides.Examples.CSharp;
using Aspose.Slides.Export;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp.Charts
{
class SettingFontProperties
{
public static void Run()
{
string dataDir = RunExamples.GetDataDir_Charts();
using (Presentation pres = new Presentation(dataDir+"test.pptx"))
{
IChart chart = pres.Slides[0].Shapes.AddChart(ChartType.ClusteredColumn, 50, 50, 600, 400);
chart.HasDataTable = true;
chart.ChartDataTable.TextFormat.PortionFormat.FontBold = NullableBool.True;
chart.ChartDataTable.TextFormat.PortionFormat.FontHeight = 20;
pres.Save(dataDir+"output.pptx", SaveFormat.Pptx);
}
}
}
} | mit | C# |
6caf4e38790298f24837a0764fe5bfa778118674 | Add xmldoc to `SkinnableInfo` | NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu | osu.Game/Screens/Play/HUD/SkinnableInfo.cs | osu.Game/Screens/Play/HUD/SkinnableInfo.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Extensions;
using osu.Game.IO.Serialization;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Screens.Play.HUD
{
/// <summary>
/// Serialised information governing custom changes to an <see cref="ISkinSerialisable"/>.
/// </summary>
[Serializable]
public class SkinnableInfo : IJsonSerializable
{
public Type Type { get; set; }
public Vector2 Position { get; set; }
public float Rotation { get; set; }
public Vector2 Scale { get; set; }
public Anchor Anchor { get; set; }
public Anchor Origin { get; set; }
public List<SkinnableInfo> Children { get; } = new List<SkinnableInfo>();
[JsonConstructor]
public SkinnableInfo()
{
}
/// <summary>
/// Construct a new instance populating all attributes from the provided drawable.
/// </summary>
/// <param name="component">The drawable which attributes should be sourced from.</param>
public SkinnableInfo(Drawable component)
{
Type = component.GetType();
Position = component.Position;
Rotation = component.Rotation;
Scale = component.Scale;
Anchor = component.Anchor;
Origin = component.Origin;
if (component is Container<Drawable> container)
{
foreach (var child in container.OfType<ISkinSerialisable>().OfType<Drawable>())
Children.Add(child.CreateSerialisedInformation());
}
}
/// <summary>
/// Construct an instance of the drawable with all attributes applied.
/// </summary>
/// <returns>The new instance.</returns>
public Drawable CreateInstance()
{
Drawable d = (Drawable)Activator.CreateInstance(Type);
d.ApplySerialisedInformation(this);
return d;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Extensions;
using osu.Game.IO.Serialization;
using osu.Game.Skinning;
using osuTK;
namespace osu.Game.Screens.Play.HUD
{
/// <summary>
/// Serialised information governing custom changes to an <see cref="ISkinSerialisable"/>.
/// </summary>
[Serializable]
public class SkinnableInfo : IJsonSerializable
{
public Type Type { get; set; }
public Vector2 Position { get; set; }
public float Rotation { get; set; }
public Vector2 Scale { get; set; }
public Anchor Anchor { get; set; }
public Anchor Origin { get; set; }
public List<SkinnableInfo> Children { get; } = new List<SkinnableInfo>();
public SkinnableInfo()
{
}
public SkinnableInfo(Drawable component)
{
Type = component.GetType();
Position = component.Position;
Rotation = component.Rotation;
Scale = component.Scale;
Anchor = component.Anchor;
Origin = component.Origin;
if (component is Container container)
{
foreach (var child in container.Children.OfType<ISkinSerialisable>().OfType<Drawable>())
Children.Add(child.CreateSerialisedInformation());
}
}
public Drawable CreateInstance()
{
Drawable d = (Drawable)Activator.CreateInstance(Type);
d.ApplySerialisedInformation(this);
return d;
}
}
}
| mit | C# |
daeabae36521df2c4f308627aadd4f605a8ed245 | Update TelemetrySeverityLevel.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Telemetry/TelemetrySeverityLevel.cs | TIKSN.Core/Analytics/Telemetry/TelemetrySeverityLevel.cs | namespace TIKSN.Analytics.Telemetry
{
public enum TelemetrySeverityLevel
{
Verbose,
Information,
Warning,
Error,
Critical
}
}
| namespace TIKSN.Analytics.Telemetry
{
public enum TelemetrySeverityLevel
{
Verbose,
Information,
Warning,
Error,
Critical
}
} | mit | C# |
355caf41ae633e4b4ec88fac9e213079e0219e56 | Update local echo server to work with binary messages | Chelaris182/wslib | LocalServer/Program.cs | LocalServer/Program.cs | using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using wslib;
namespace LocalServer
{
class Program
{
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += LogUnobservedTaskException;
var listenerOptions = new WebSocketListenerOptions { Endpoint = new IPEndPoint(IPAddress.Loopback, 8080) };
using (var listener = new WebSocketListener(listenerOptions, appFunc))
{
listener.StartAccepting();
Console.ReadLine();
}
}
private static void LogUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
//Console.WriteLine(unobservedTaskExceptionEventArgs.Exception);
}
private static async Task appFunc(IWebSocket webSocket)
{
while (webSocket.IsConnected())
{
using (var msg = await webSocket.ReadMessageAsync(CancellationToken.None))
{
if (msg == null) continue;
using (var ms = new MemoryStream())
{
await msg.ReadStream.CopyToAsync(ms);
byte[] array = ms.ToArray();
using (var w = await webSocket.CreateMessageWriter(msg.Type, CancellationToken.None))
{
await w.WriteMessageAsync(array, 0, array.Length, CancellationToken.None);
}
}
}
}
}
}
} | using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wslib;
using wslib.Protocol;
namespace LocalServer
{
class Program
{
static void Main(string[] args)
{
TaskScheduler.UnobservedTaskException += LogUnobservedTaskException;
var listenerOptions = new WebSocketListenerOptions { Endpoint = new IPEndPoint(IPAddress.Loopback, 8080) };
using (var listener = new WebSocketListener(listenerOptions, appFunc))
{
listener.StartAccepting();
Console.ReadLine();
}
}
private static void LogUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
{
throw new NotImplementedException(); // TODO: log
}
private static async Task appFunc(IWebSocket webSocket)
{
while (webSocket.IsConnected())
{
using (var msg = await webSocket.ReadMessageAsync(CancellationToken.None))
{
if (msg != null)
{
using (var ms = new MemoryStream())
{
await msg.ReadStream.CopyToAsync(ms);
var text = Encoding.UTF8.GetString(ms.ToArray());
using (var w = await webSocket.CreateMessageWriter(MessageType.Text, CancellationToken.None))
{
await w.WriteMessageAsync(ms.ToArray(), 0, (int)ms.Length, CancellationToken.None);
}
}
}
}
}
}
}
} | mit | C# |
d7f934b35d97e2bc5e9ac352c5b918ea4b4ce02c | Add files via upload | bugfi5h/Alexa-Smart-Home | Response/Payloads/HealthCheckResponsePayload.cs | Response/Payloads/HealthCheckResponsePayload.cs | using Newtonsoft.Json;
namespace RKon.Alexa.NET.Response
{
/// <summary>
/// Payload für eine HealthCheckResponse
/// </summary>
public class HealthCheckResponsePayload : ResponsePayload
{
[JsonRequired]
[JsonProperty("description")]
public string Description { get; private set; }
[JsonRequired]
[JsonProperty("isHealthy")]
public bool IsHealthy { get; private set; }
/// <summary>
/// Konstruktor setzt IsHealthy auf false und Description auf The system is currenty not healthy
/// </summary>
public HealthCheckResponsePayload()
{
Description = "The system is currenty not healthy";
IsHealthy = false;
}
/// <summary>
/// Setzt die Beschreibung und IsHealthy an Hand des übergebenen Zustands
/// </summary>
/// <param name="isHealthy">Zustand des Geräts</param>
public void SetHealthyStatus(bool isHealthy)
{
IsHealthy = isHealthy;
if (!IsHealthy)
{
Description = "The system is currenty not healthy";
}else
{
Description = "The system is currenty healthy";
}
}
}
}
| using Newtonsoft.Json;
namespace RKon.Alexa.NET.Response
{
/// <summary>
/// Payload für eine HealthCheckResponse
/// </summary>
public class HealthCheckResponsePayload : ResponsePayload
{
[JsonRequired]
[JsonProperty("description")]
private string Description { get; set; }
[JsonRequired]
[JsonProperty("isHealthy")]
private bool IsHealthy { get; set; }
/// <summary>
/// Konstruktor setzt IsHealthy auf false und Description auf The system is currenty not healthy
/// </summary>
public HealthCheckResponsePayload()
{
Description = "The system is currenty not healthy";
IsHealthy = false;
}
/// <summary>
/// Setzt die Beschreibung und IsHealthy an Hand des übergebenen Zustands
/// </summary>
/// <param name="isHealthy">Zustand des Geräts</param>
public void SetHealthyStatus(bool isHealthy)
{
IsHealthy = isHealthy;
if (!IsHealthy)
{
Description = "The system is currenty not healthy";
}else
{
Description = "The system is currenty healthy";
}
}
}
}
| mit | C# |
0ee2bd18c7b92bca0b7c1e614b3a1b817190d10a | Update cashtransactionlines, fix subaccount | ON-IT/Visma.Net | Visma.net/Models/CashTransactionDetails.cs | Visma.net/Models/CashTransactionDetails.cs | using Newtonsoft.Json;
using ONIT.VismaNetApi.Lib;
using ONIT.VismaNetApi.Models.Enums;
using System;
namespace ONIT.VismaNetApi.Models
{
public class CashTransactionDetails : DtoProviderBase
{
public CashTransactionDetails()
{
DtoFields.Add("operation", new NotDto<ApiOperation>(ApiOperation.Insert));
}
public ApiOperation operation
{
get => Get(defaultValue: new NotDto<ApiOperation>(ApiOperation.Insert)).Value;
set => Set(new NotDto<ApiOperation>(value));
}
public string branchNumber { get => Get<string>(); set => Set(value); }
public string inventoryNumber { get => Get<string>(); set => Set(value); }
public string description { get => Get<string>(); set => Set(value); }
[JsonProperty]
public decimal quantity { get => Get<decimal>(); set => Set(value); }
public string uom { get => Get<string>(); set => Set(value); }
[JsonProperty]
public decimal price { get => Get<decimal>(); set => Set(value); }
[JsonProperty]
public decimal amount { get => Get<decimal>(); set => Set(value); }
public string offsetAccount { get => Get<string>(); set => Set(value); }
//[JsonProperty]
//public Subaccount offsetSubaccount { get; private set; }
//public CustomDto.Subaccount offsetSubaccount
//{
// get => Get(defaultValue: new CustomDto.Subaccount());
// set => Set(value);
//}
public CustomDto.Subaccount offsetSubaccount
{
get => Get(defaultValue: new CustomDto.Subaccount());
set => Set(value);
}
public string vatCode { get => Get<string>(); set => Set(value); }
public bool notInvoiceable
{
get => Get<bool>();
set => Set(value);
}
public string project { get => Get<string>(); set => Set(value); }
public string projectTask { get => Get<string>(); set => Set(value); }
}
}
| using Newtonsoft.Json;
using ONIT.VismaNetApi.Lib;
using ONIT.VismaNetApi.Models.Enums;
using System;
namespace ONIT.VismaNetApi.Models
{
public class CashTransactionDetails : DtoProviderBase
{
public CashTransactionDetails()
{
DtoFields.Add("operation", new NotDto<ApiOperation>(ApiOperation.Insert));
}
public ApiOperation operation
{
get => Get(defaultValue: new NotDto<ApiOperation>(ApiOperation.Insert)).Value;
set => Set(new NotDto<ApiOperation>(value));
}
public string branchNumber { get => Get<string>(); set => Set(value); }
public string inventoryNumber { get => Get<string>(); set => Set(value); }
public string description { get => Get<string>(); set => Set(value); }
[JsonProperty]
public decimal quantity { get => Get<decimal>(); set => Set(value); }
public string uom { get => Get<string>(); set => Set(value); }
[JsonProperty]
public decimal price { get => Get<decimal>(); set => Set(value); }
[JsonProperty]
public decimal amount { get => Get<decimal>(); set => Set(value); }
public string offsetAccount { get => Get<string>(); set => Set(value); }
[JsonProperty]
public Subaccount offsetSubaccount { get; private set; }
public string vatCode { get => Get<string>(); set => Set(value); }
public bool notInvoiceable
{
get => Get<bool>();
set => Set(value);
}
public string project { get => Get<string>(); set => Set(value); }
public string projectTask { get => Get<string>(); set => Set(value); }
}
}
| mit | C# |
35abdbeb69a5eb4e5bf2d1fc8c0c70c576ce424d | Comment in Signum.Upgrade | signumsoftware/framework,signumsoftware/framework | Signum.Upgrade/Program.cs | Signum.Upgrade/Program.cs | using Signum.Utilities;
using System;
namespace Signum.Upgrade;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine(" ..:: Welcome to Signum Upgrade ::..");
Console.WriteLine();
SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " This application helps you upgrade a Signum Framework application by modifying your source code.");
SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " The closer your application resembles Southwind, the better it works.");
SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " Review all the changes carefully");
Console.WriteLine();
var uctx = UpgradeContext.CreateFromCurrentDirectory();
Console.Write(" RootFolder = "); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, uctx.RootFolder);
Console.Write(" ApplicationName = "); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, uctx.ApplicationName);
//UpgradeContext.DefaultIgnoreDirectories = UpgradeContext.DefaultIgnoreDirectories.Where(a => a != "Framework").ToArray();
new CodeUpgradeRunner(autoDiscover: true).Run(uctx);
}
}
| using Signum.Utilities;
using System;
namespace Signum.Upgrade;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine(" ..:: Welcome to Signum Upgrade ::..");
Console.WriteLine();
SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " This application helps you upgrade a Signum Framework application by modifying your source code.");
SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " The closer your application resembles Southwind, the better it works.");
SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " Review all the changes carefully");
Console.WriteLine();
var uctx = UpgradeContext.CreateFromCurrentDirectory();
Console.Write(" RootFolder = "); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, uctx.RootFolder);
Console.Write(" ApplicationName = "); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, uctx.ApplicationName);
UpgradeContext.DefaultIgnoreDirectories = UpgradeContext.DefaultIgnoreDirectories.Where(a => a != "Framework").ToArray();
new CodeUpgradeRunner(autoDiscover: true).Run(uctx);
}
}
| mit | C# |
5f5ebf46464722151ecbe969fc4b8c5f795e9288 | Set Treenumerable version to 1.0.0 | jasonmcboyd/Treenumerable | Source/Treenumerable/Properties/AssemblyInfo.cs | Source/Treenumerable/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
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("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Toshiba")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Toshiba 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| using System.Reflection;
using System.Resources;
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("Treenumerable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Toshiba")]
[assembly: AssemblyProduct("Treenumerable")]
[assembly: AssemblyCopyright("Copyright © Toshiba 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
| mit | C# |
beeb19e65f83626fd4a2d9f7ab07f5cf9df209ca | Bump version again | alecgorge/adzerk-dot-net | StackExchange.Adzerk/Properties/AssemblyInfo.cs | StackExchange.Adzerk/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("StackExchange.Adzerk")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Overflow")]
[assembly: AssemblyProduct("StackExchange.Adzerk")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// 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.0.0.43")]
[assembly: AssemblyFileVersion("0.0.0.43")]
| 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("StackExchange.Adzerk")]
[assembly: AssemblyDescription("Unofficial Adzerk API client.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stack Overflow")]
[assembly: AssemblyProduct("StackExchange.Adzerk")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")]
// 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.0.0.42")]
[assembly: AssemblyFileVersion("0.0.0.42")]
| mit | C# |
e566215be43d258b513ec9864f0dde95d1eca434 | Update EdibleStack.cs | Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/Food/EdibleStack.cs | UnityProject/Assets/Scripts/Food/EdibleStack.cs | /// <summary>
/// Edible stack function for foods that stack. Multiplies satiation and heal amount by number in stack before eating.
/// </summary>
public class EdibleStack : Edible
{
//Stacking component for the object.
private Stackable stckCmp;
private void Awake()
{
stckCmp = gameObject.GetComponent<Stackable>();
}
public override void TryEat()
{
//Check if stack component exists. If not, consume whole stack normally.
if (stckCmp == null)
{
base.TryEat();
} else {
//Multiply hunger and heal by the amoount of items stored, then try eat.
//base.healAmount = stckCmp.Amount*base.healAmount;
//base.healHungerAmount = stckCmp.Amount*base.healHungerAmount;
base.TryEat();
}
}
} | /// <summary>
/// Edible stack function for foods that stack. Multiplies satiation and heal amount by number in stack before eating.
/// </summary>
public class EdibleStack : Edible
{
//Stacking component for the object.
private Stackable stckCmp;
private void Awake()
{
stckCmp = gameObject.GetComponent<Stackable>();
}
public override void TryEat()
{
//Check if stack component exists. If not, consume whole stack normally.
if (stckCmp == null)
{
base.TryEat();
} else {
//Multiply hunger and heal by the amoount of items stored, then try eat.
base.healAmount = stckCmp.Amount*base.healAmount;
base.healHungerAmount = stckCmp.Amount*base.healHungerAmount;
base.TryEat();
}
}
} | agpl-3.0 | C# |
ee43a996cc5d59f6303c95a8a2e5436be580a091 | Update Tile.cs | thejonathanr/SudokuSolver | SudokuSolver_Try1/Tile.cs | SudokuSolver_Try1/Tile.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SudokuSolver_Try1 {
public class Tile {
public enum TileType {
Empty,
InProgress,
Solved
};
public int x;
public int y;
public int group;
public string value = "";
public List<string> ideas = new List<string>();
public TextBox field;
public Panel panel;
public bool hasField = false;
public TileType tileType = TileType.Empty;
public Tile(int _x, int _y, TileType _TileType, string _value, List<string> _ideas, TextBox _field, Panel _panel, bool _hasField ) {
this.x = _x;
this.y = _y;
this.tileType = _TileType;
this.value = _value;
this.ideas = _ideas;
this.field = _field;
this.panel = _panel;
this.hasField = _hasField;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SudokuSolver_Try1 {
public class Tile {
public enum TileType {
Empty,
InProgress,
Solved
};
public int x;
public int y;
public string value = "";
public List<string> ideas = new List<string>();
public TextBox field;
public Panel panel;
public bool hasField = false;
public TileType tileType = TileType.Empty;
public Tile(int _x, int _y, TileType _TileType, string _value, List<string> _ideas, TextBox _field, Panel _panel, bool _hasField ) {
this.x = _x;
this.y = _y;
this.tileType = _TileType;
this.value = _value;
this.ideas = _ideas;
this.field = _field;
this.panel = _panel;
this.hasField = _hasField;
}
}
}
| agpl-3.0 | C# |
bf6bd649aaa116ebc98cff568ff51e1abfebc60f | Update Tests/AssemblyLocation.cs | SimonCropp/CaptureSnippets | Tests/AssemblyLocation.cs | Tests/AssemblyLocation.cs | using System.IO;
public static class AssemblyLocation
{
static AssemblyLocation()
{
var assembly = typeof(AssemblyLocation).Assembly;
var path = assembly.CodeBase
.Replace("file:///", "")
.Replace("file://", "")
.Replace(@"file:\\\", "")
.Replace(@"file:\\", "");
CurrentDirectory = Path.GetDirectoryName(path);
}
public static string CurrentDirectory;
} | public static class AssemblyLocation
{
static AssemblyLocation()
{
CurrentDirectory = System.AppContext.BaseDirectory;
}
public static string CurrentDirectory;
} | mit | C# |
ac6322715814609b6b6feff9104e3f72ad93b068 | Fix for #55 | pombredanne/lessmsi,activescott/lessmsi,activescott/lessmsi,pombredanne/lessmsi,activescott/lessmsi | src/LessMsi.Cli/ExtractCommand.cs | src/LessMsi.Cli/ExtractCommand.cs | using System.Collections.Generic;
using System.IO;
using System.Linq;
using NDesk.Options;
namespace LessMsi.Cli
{
internal class ExtractCommand : LessMsiCommand
{
public override void Run(List<string> allArgs)
{
var args = allArgs.Skip(1).ToList();
// "x msi_name [path_to_extract\] [file_names]+
if (args.Count < 1)
throw new OptionException("Invalid argument. Extract command must at least specify the name of an msi file.", "x");
var i = 0;
var msiFile = args[i++];
if (!File.Exists(msiFile))
throw new OptionException("Invalid argument. Specified msi file does not exist.", "x");
var filesToExtract = new List<string>();
var extractDir = "";
if (i < args.Count)
{
if (extractDir == "" && (args[i].EndsWith("\\") || args[i].EndsWith("\"")))
extractDir = args[i];
else
filesToExtract.Add(args[i]);
}
while (++i < args.Count)
filesToExtract.Add(args[i]);
Program.DoExtraction(msiFile, extractDir.TrimEnd('\"'), filesToExtract);
}
}
} | using System.Collections.Generic;
using System.Linq;
using NDesk.Options;
namespace LessMsi.Cli
{
internal class ExtractCommand : LessMsiCommand
{
public override void Run(List<string> allArgs)
{
var args = allArgs.Skip(1).ToList();
// "x msi_name [path_to_extract\] [file_names]+
if (args.Count < 1)
throw new OptionException("Invalid argument. Extract command must at least specify the name of an msi file.", "x");
var i = 0;
var msiFile = args[i++];
var filesToExtract = new List<string>();
var extractDir = "";
if (i < args.Count)
{
if (args[i].EndsWith("\\"))
extractDir = args[i];
else
filesToExtract.Add(args[i]);
}
while (++i < args.Count)
filesToExtract.Add(args[i]);
Program.DoExtraction(msiFile, extractDir.TrimEnd('\"'), filesToExtract);
}
}
} | mit | C# |
f06de650ee7a3b37478c1ed2632391cb99bdad2f | Update ZUGFeRDVersion.cs | stephanstapel/ZUGFeRD-csharp,stephanstapel/ZUGFeRD-csharp | ZUGFeRD/ZUGFeRDVersion.cs | ZUGFeRD/ZUGFeRDVersion.cs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace s2industries.ZUGFeRD
{
public enum ZUGFeRDVersion
{
Version1 = 100,
Version20 = 200,
Version21 = 210
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace s2industries.ZUGFeRD
{
public enum ZUGFeRDVersion
{
Version1 = 100,
Version20 = 200,
Version21 = 210
}
}
| apache-2.0 | C# |
5b6f9bafe46b65f7a5746001c3266055c7d95a2e | update Base controller | csyntax/BlogSystem | BlogSystem.Web/Controllers/BaseController.cs | BlogSystem.Web/Controllers/BaseController.cs | namespace BlogSystem.Web.Controllers
{
using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using BlogSystem.Data.Models;
using BlogSystem.Data.UnitOfWork;
using Microsoft.AspNet.Identity;
public class BaseController : Controller
{
protected BaseController(IBlogSystemData data)
{
this.Data = data;
}
protected BaseController(IBlogSystemData data, ApplicationUser userProfile) : this(data)
{
this.UserProfile = userProfile;
}
public IBlogSystemData Data { get; }
public ApplicationUser UserProfile { get; private set; }
//[NonAction]
protected override IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state)
{
if (requestContext.HttpContext.User.Identity.IsAuthenticated)
{
var username = requestContext.HttpContext.User.Identity.GetUserName();
var user = this.Data.Users.All().FirstOrDefault(u => u.UserName == username);
this.UserProfile = user;
this.ViewBag.UserProfile = user;
}
return base.BeginExecute(requestContext, callback, state);
}
}
} | namespace BlogSystem.Web.Controllers
{
using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using BlogSystem.Data.Models;
using BlogSystem.Data.UnitOfWork;
using Microsoft.AspNet.Identity;
public class BaseController : Controller
{
protected BaseController(IBlogSystemData data)
{
this.Data = data;
}
protected BaseController(IBlogSystemData data, ApplicationUser userProfile) : this(data)
{
this.UserProfile = userProfile;
}
public IBlogSystemData Data { get; }
public ApplicationUser UserProfile { get; private set; }
protected override IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state)
{
if (requestContext.HttpContext.User.Identity.IsAuthenticated)
{
var username = requestContext.HttpContext.User.Identity.GetUserName();
var user = this.Data.Users.All().FirstOrDefault(u => u.UserName == username);
this.UserProfile = user;
this.ViewBag.UserProfile = user;
}
return base.BeginExecute(requestContext, callback, state);
}
}
} | mit | C# |
49dd8d67de4d118698ebfd98808e93e674ebed67 | Fix culture-sensitive test. | nodatime/nodatime,jskeet/nodatime,jskeet/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,zaccharles/nodatime,nodatime/nodatime,zaccharles/nodatime | src/NodaTime.Demo/LocalTimeDemo.cs | src/NodaTime.Demo/LocalTimeDemo.cs | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// 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
using NUnit.Framework;
using NodaTime.Globalization;
namespace NodaTime.Demo
{
[TestFixture]
public class LocalTimeDemo
{
[Test]
public void Construction()
{
LocalTime time = new LocalTime(16, 20, 0);
Assert.AreEqual("16:20:00", time.ToString("HH:mm:ss", NodaFormatInfo.InvariantInfo));
}
}
} | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// 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
using NUnit.Framework;
namespace NodaTime.Demo
{
[TestFixture]
public class LocalTimeDemo
{
[Test]
public void Construction()
{
LocalTime time = new LocalTime(16, 20, 0);
Assert.AreEqual("16:20:00", time.ToString());
}
}
} | apache-2.0 | C# |
18313ee25b5614fe64b398a5badb70e935b549f8 | Rename a unit test. | ZenLulz/Matrix.NET | tests/MatrixUnitTests/InstantiationTests.cs | tests/MatrixUnitTests/InstantiationTests.cs | using System;
using Binarysharp.Maths;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Binarysharp.Tests
{
[TestClass]
public class InstantiationTests
{
[TestMethod]
public void CreateMatrixWithIntegerArrays()
{
// Arrange
Matrix<int> matrix = null;
var values = new[]
{
new[] {1, 0, 0},
new[] {0, 1, 0},
new[] {0, 0, 1}
};
try
{
// Act
matrix = new Matrix<int>(values);
}
catch (Exception ex)
{
Assert.Fail("The matrix couldn't be created with valid arrays of integers. {0}", ex);
}
Assert.IsNotNull(matrix);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException), "The matrix cannot be created with an unbalanced number of values.")]
public void CreateMatrixWithUnbalancedValues()
{
// Arrange
var values = new[]
{
new[] {1, 0, 0},
new[] {0, 1, 0},
new[] {0, 1}
};
// Act
var matrix = new Matrix<int>(values);
// Assert
Assert.IsNotNull(matrix);
}
}
}
| using System;
using Binarysharp.Maths;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Binarysharp.Tests
{
[TestClass]
public class InstantiationTests
{
[TestMethod]
public void CreateMatrixWithIntegerArrays()
{
// Arrange
Matrix<int> matrix = null;
var values = new[]
{
new[] {1, 0, 0},
new[] {0, 1, 0},
new[] {0, 0, 1}
};
try
{
// Act
matrix = new Matrix<int>(values);
}
catch (Exception ex)
{
Assert.Fail("The matrix couldn't be created with valid arrays of integers. {0}", ex);
}
Assert.IsNotNull(matrix);
}
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException), "The matrix cannot be created with an unbalanced number of values.")]
public void CreateMatrixWithNotProperSizedValues()
{
// Arrange
var values = new[]
{
new[] {1, 0, 0},
new[] {0, 1, 0},
new[] {0, 1}
};
// Act
var matrix = new Matrix<int>(values);
// Assert
Assert.IsNotNull(matrix);
}
}
}
| mit | C# |
adacda1a6b9ba18021d0cc345023b65ea0394d00 | Add conditional public methods for unit testing the internal methods | sbennett1990/signify.cs | SignifyCS/Verify.cs | SignifyCS/Verify.cs | /*
* Copyright (c) 2017 Scott Bennett <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System;
using System.Diagnostics;
using Sodium;
namespace SignifyCS {
public class Verify {
public static bool VerifyMessage(PubKey pub_key, Signature sig, byte[] message) {
checkAlgorithms(pub_key, sig);
checkKeys(pub_key, sig);
return verifyCrypto(sig, message, pub_key);
}
private static void checkAlgorithms(PubKey pub_key, Signature sig) {
if (!pub_key.Algorithm.Equals(BaseCryptoFile.PK_ALGORITHM)) {
throw new Exception($"unsupported public key; unexpected algorithm '{pub_key.Algorithm}'");
}
if (!sig.Algorithm.Equals(BaseCryptoFile.PK_ALGORITHM)) {
throw new Exception($"unsupported signature; unexpected algorithm '{sig.Algorithm}'");
}
}
private static void checkKeys(PubKey pub_key, Signature sig) {
if (!CryptoBytes.ConstantTimeEquals(pub_key.KeyNum, sig.KeyNum)) {
throw new Exception("verification failed: checked against wrong key");
}
}
private static bool verifyCrypto(Signature sig, byte[] message, PubKey pub_key) {
return PublicKeyAuth.VerifyDetached(sig.SigData, message, pub_key.PubKeyData);
}
[Conditional("TEST")]
public static void CheckAlgorithms(PubKey pub_key, Signature sig) {
checkAlgorithms(pub_key, sig);
}
[Conditional("TEST")]
public static void CheckKeys(PubKey pub_key, Signature sig) {
checkKeys(pub_key, sig);
}
}
}
| /*
* Copyright (c) 2017 Scott Bennett <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System;
using Sodium;
namespace SignifyCS {
public class Verify {
public static bool VerifyMessage(PubKey pub_key, Signature sig, byte[] message) {
checkAlgorithms(pub_key, sig);
checkKeys(pub_key, sig);
return verifyCrypto(sig, message, pub_key);
}
private static void checkAlgorithms(PubKey pub_key, Signature sig) {
if (!pub_key.Algorithm.Equals(BaseCryptoFile.PK_ALGORITHM)) {
throw new Exception($"unsupported public key; unexpected algorithm '{pub_key.Algorithm}'");
}
if (!sig.Algorithm.Equals(BaseCryptoFile.PK_ALGORITHM)) {
throw new Exception($"unsupported signature; unexpected algorithm '{sig.Algorithm}'");
}
}
private static void checkKeys(PubKey pub_key, Signature sig) {
if (!CryptoBytes.ConstantTimeEquals(pub_key.KeyNum, sig.KeyNum)) {
throw new Exception("verification failed: checked against wrong key");
}
}
private static bool verifyCrypto(Signature sig, byte[] message, PubKey pub_key) {
return PublicKeyAuth.VerifyDetached(sig.SigData, message, pub_key.PubKeyData);
}
}
}
| isc | C# |
cafb24f72c828e5a37794a370c258dcaef8aff99 | Add flow tree body to the function | coffeecup-winner/unwind-mc,coffeecup-winner/unwind-mc,coffeecup-winner/unwind-mc,coffeecup-winner/unwind-mc,coffeecup-winner/unwind-mc | src/UnwindMC/Analysis/Function.cs | src/UnwindMC/Analysis/Function.cs | using System;
using System.Collections.Generic;
using UnwindMC.Analysis.Flow;
using UnwindMC.Analysis.IL;
namespace UnwindMC.Analysis
{
public class Function
{
private List<IBlock> _blocks;
public Function(ulong address)
{
Address = address;
Status = FunctionStatus.Created;
}
public ulong Address { get; }
public FunctionStatus Status { get; set; }
public IReadOnlyList<IBlock> Blocks => _blocks;
public ILInstruction FirstInstruction
{
get
{
if (_blocks == null || _blocks.Count == 0)
{
return null;
}
var seq = _blocks[0] as SequentialBlock;
if (seq != null)
{
return seq.Instructions[0];
}
var loop = _blocks[0] as LoopBlock;
if (loop != null)
{
return loop.Condition;
}
var cond = _blocks[0] as ConditionalBlock;
if (cond != null)
{
return cond.Condition;
}
throw new InvalidOperationException("Unknown block type");
}
}
public void ResolveBody(InstructionGraph graph)
{
if (Status != FunctionStatus.BoundsResolved)
{
throw new InvalidOperationException("Cannot resolve function body when bounds are not resolved");
}
_blocks = FlowAnalyzer.Analyze(ILDecompiler.Decompile(graph, Address));
Status = FunctionStatus.BodyResolved;
}
}
public enum FunctionStatus
{
Created,
BoundsResolved,
BoundsNotResolvedInvalidAddress,
BoundsNotResolvedIncompleteGraph,
BodyResolved,
}
}
| namespace UnwindMC.Analysis
{
public class Function
{
public Function(ulong address)
{
Address = address;
Status = FunctionStatus.Created;
}
public ulong Address { get; }
public FunctionStatus Status { get; set; }
}
public enum FunctionStatus
{
Created,
BoundsResolved,
BoundsNotResolvedInvalidAddress,
BoundsNotResolvedIncompleteGraph,
}
}
| mit | C# |
339549a3b02870af90550362e490dbe62c077c80 | set sortable false for fields with NotMapped attribute | rolembergfilho/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,dfaruque/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity | Serenity.Data.Entity/PropertyGrid/BasicPropertyProcessor/BasicPropertyProcessor.Sorting.cs | Serenity.Data.Entity/PropertyGrid/BasicPropertyProcessor/BasicPropertyProcessor.Sorting.cs | using Serenity.ComponentModel;
using Serenity.Data;
namespace Serenity.PropertyGrid
{
public partial class BasicPropertyProcessor : PropertyProcessor
{
private void SetSorting(IPropertySource source, PropertyItem item)
{
var sortOrderAttr = source.GetAttribute<SortOrderAttribute>();
if (sortOrderAttr != null && sortOrderAttr.SortOrder != 0)
item.SortOrder = sortOrderAttr.SortOrder;
var sortableAttr = source.GetAttribute<SortableAttribute>();
if (sortableAttr != null)
{
if (!sortableAttr.Value)
item.Sortable = false;
return;
}
if (!ReferenceEquals(null, source.BasedOnField) &&
source.BasedOnField.Flags.HasFlag(FieldFlags.NotMapped))
item.Sortable = false;
}
}
} | using Serenity.ComponentModel;
namespace Serenity.PropertyGrid
{
public partial class BasicPropertyProcessor : PropertyProcessor
{
private void SetSorting(IPropertySource source, PropertyItem item)
{
var sortOrderAttr = source.GetAttribute<SortOrderAttribute>();
if (sortOrderAttr != null && sortOrderAttr.SortOrder != 0)
item.SortOrder = sortOrderAttr.SortOrder;
var sortableAttr = source.GetAttribute<SortableAttribute>();
if (sortableAttr != null && !sortableAttr.Value)
item.Sortable = false;
}
}
} | mit | C# |
1be22e5b1a67c6542c125a97ce85703766e69099 | Make Args a static class | wjkohnen/antlr4,supriyantomaftuh/antlr4,joshids/antlr4,cooperra/antlr4,krzkaczor/antlr4,joshids/antlr4,antlr/antlr4,supriyantomaftuh/antlr4,Pursuit92/antlr4,chienjchienj/antlr4,cooperra/antlr4,Distrotech/antlr4,ericvergnaud/antlr4,chandler14362/antlr4,krzkaczor/antlr4,joshids/antlr4,jvanzyl/antlr4,chandler14362/antlr4,antlr/antlr4,wjkohnen/antlr4,mcanthony/antlr4,Pursuit92/antlr4,Pursuit92/antlr4,cocosli/antlr4,parrt/antlr4,mcanthony/antlr4,wjkohnen/antlr4,wjkohnen/antlr4,lncosie/antlr4,supriyantomaftuh/antlr4,chandler14362/antlr4,chandler14362/antlr4,ericvergnaud/antlr4,lncosie/antlr4,wjkohnen/antlr4,worsht/antlr4,Distrotech/antlr4,antlr/antlr4,parrt/antlr4,wjkohnen/antlr4,sidhart/antlr4,jvanzyl/antlr4,antlr/antlr4,wjkohnen/antlr4,parrt/antlr4,Pursuit92/antlr4,wjkohnen/antlr4,joshids/antlr4,jvanzyl/antlr4,joshids/antlr4,parrt/antlr4,chandler14362/antlr4,cocosli/antlr4,parrt/antlr4,parrt/antlr4,Pursuit92/antlr4,Distrotech/antlr4,cooperra/antlr4,wjkohnen/antlr4,sidhart/antlr4,Distrotech/antlr4,chienjchienj/antlr4,chienjchienj/antlr4,Pursuit92/antlr4,ericvergnaud/antlr4,parrt/antlr4,cooperra/antlr4,worsht/antlr4,lncosie/antlr4,cocosli/antlr4,worsht/antlr4,ericvergnaud/antlr4,supriyantomaftuh/antlr4,joshids/antlr4,worsht/antlr4,antlr/antlr4,ericvergnaud/antlr4,sidhart/antlr4,sidhart/antlr4,hce/antlr4,hce/antlr4,chandler14362/antlr4,worsht/antlr4,sidhart/antlr4,chandler14362/antlr4,cocosli/antlr4,ericvergnaud/antlr4,chandler14362/antlr4,parrt/antlr4,antlr/antlr4,hce/antlr4,Distrotech/antlr4,chandler14362/antlr4,antlr/antlr4,hce/antlr4,supriyantomaftuh/antlr4,mcanthony/antlr4,ericvergnaud/antlr4,krzkaczor/antlr4,krzkaczor/antlr4,antlr/antlr4,lncosie/antlr4,krzkaczor/antlr4,joshids/antlr4,jvanzyl/antlr4,mcanthony/antlr4,Pursuit92/antlr4,Pursuit92/antlr4,ericvergnaud/antlr4,mcanthony/antlr4,Pursuit92/antlr4,antlr/antlr4,parrt/antlr4,chienjchienj/antlr4,antlr/antlr4,ericvergnaud/antlr4,joshids/antlr4,parrt/antlr4,lncosie/antlr4,ericvergnaud/antlr4,chienjchienj/antlr4 | runtime/CSharp/Antlr4.Runtime/Misc/Args.cs | runtime/CSharp/Antlr4.Runtime/Misc/Args.cs | /*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
using System;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
/// <author>Sam Harwell</author>
public static class Args
{
/// <exception cref="System.ArgumentNullException">
/// if
/// <code>value</code>
/// is
/// <code>null</code>
/// .
/// </exception>
public static void NotNull(string parameterName, object value)
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
}
}
}
| /*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
using System;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
/// <author>Sam Harwell</author>
public sealed class Args
{
/// <exception cref="System.ArgumentNullException">
/// if
/// <code>value</code>
/// is
/// <code>null</code>
/// .
/// </exception>
public static void NotNull(string parameterName, object value)
{
if (value == null)
{
throw new ArgumentNullException(parameterName + " cannot be null.");
}
}
private Args()
{
}
}
}
| bsd-3-clause | C# |
6535aaf0b649c4b4fd038250436fa989b66bfc7e | clear the test... | Pondidum/Conifer,Pondidum/Conifer | Tests/Scratchpad.cs | Tests/Scratchpad.cs | using System.Collections.Generic;
using System.Web.Http;
using RestRouter;
using RestRouter.Conventions;
using Shouldly;
using Xunit;
namespace Tests
{
public class Scratchpad
{
[Fact]
public void When_testing_something()
{
}
}
} | using System.Collections.Generic;
using System.Web.Http;
using RestRouter;
using RestRouter.Conventions;
using Shouldly;
using Xunit;
namespace Tests
{
public class Scratchpad
{
[Fact]
public void When_testing_something()
{
//var conventions = new List<IRouteConvetion>
//{
// new ControllerNameRouteConvention(),
// new SpecifiedPartRouteConvention("ref"),
// new ParameterNameRouteConvention(),
// new RawOptionRouteConvention()
//};
//var config = new HttpConfiguration();
//var router = new ConventionalRouter(config);
//router.AddRoutes<CandidateController>(conventions);
//var builder = new RouteBuilder(router.Routes);
//var route = builder.RouteFor<CandidateController>(c => c.GetRefFileRaw(GetRef(), "cvs", "file.docx"));
//route.ShouldBe("candidate/ref/456/cvs/file.docx/raw", Case.Insensitive);
}
private int GetRef()
{
return 456;
}
}
} | lgpl-2.1 | C# |
427f7cb407bda07f0ddad721e4dba4f40653558e | Change example to contain default values | tparviainen/oscilloscope | SCPI/Display/DISPLAY_GRID.cs | SCPI/Display/DISPLAY_GRID.cs | using System;
using System.Text;
namespace SCPI.Display
{
public class DISPLAY_GRID : ICommand
{
public string Description => "Set or query the grid type of screen display.";
public string Grid { get; private set; }
private readonly string[] gridRange = new string[] { "FULL", "HALF", "NONE" };
public string Command(params string[] parameters)
{
var cmd = ":DISPlay:GRID";
if (parameters.Length > 0)
{
var grid = parameters[0];
cmd = $"{cmd} {grid}";
}
else
{
cmd += "?";
}
return cmd;
}
public string HelpMessage()
{
var syntax = nameof(DISPLAY_GRID) + "\n" +
nameof(DISPLAY_GRID) + " <grid>";
var parameters = " <grid> = {"+ string.Join("|", gridRange) +"}\n";
var example = "Example: " + nameof(DISPLAY_GRID) + " FULL";
return $"{syntax}\n{parameters}\n{example}";
}
public bool Parse(byte[] data)
{
if (data != null)
{
Grid = Encoding.ASCII.GetString(data).Trim();
if (Array.Exists(gridRange, g => g.Equals(Grid)))
{
return true;
}
}
Grid = null;
return false;
}
}
}
| using System;
using System.Text;
namespace SCPI.Display
{
public class DISPLAY_GRID : ICommand
{
public string Description => "Set or query the grid type of screen display.";
public string Grid { get; private set; }
private readonly string[] gridRange = new string[] { "FULL", "HALF", "NONE" };
public string Command(params string[] parameters)
{
var cmd = ":DISPlay:GRID";
if (parameters.Length > 0)
{
var grid = parameters[0];
cmd = $"{cmd} {grid}";
}
else
{
cmd += "?";
}
return cmd;
}
public string HelpMessage()
{
var syntax = nameof(DISPLAY_GRID) + "\n" +
nameof(DISPLAY_GRID) + " <grid>";
var parameters = " <grid> = {"+ string.Join("|", gridRange) +"}\n";
var example = "Example: " + nameof(DISPLAY_GRID) + "?";
return $"{syntax}\n{parameters}\n{example}";
}
public bool Parse(byte[] data)
{
if (data != null)
{
Grid = Encoding.ASCII.GetString(data).Trim();
if (Array.Exists(gridRange, g => g.Equals(Grid)))
{
return true;
}
}
Grid = null;
return false;
}
}
}
| mit | C# |
3d49d1bc47f76fd81a8fc7f0eb29463d954238a2 | test fix | Teleopti/Stardust | Manager/ManagerTest/Database/DatabaseTest.cs | Manager/ManagerTest/Database/DatabaseTest.cs | using NUnit.Framework;
namespace ManagerTest.Database
{
public class DatabaseTest
{
private DatabaseHelper _databaseHelper;
[TestFixtureSetUp]
public void BaseTestTestFixtureSetup()
{
_databaseHelper = new DatabaseHelper();
_databaseHelper.Create();
}
[SetUp]
public void BasteTestSetup()
{
_databaseHelper.TryClearDatabase();
}
}
} | using NUnit.Framework;
namespace ManagerTest.Database
{
public class DatabaseTest
{
[SetUp]
public void BaseTestSetup()
{
var databaseHelper = new DatabaseHelper();
databaseHelper.Create();
}
}
} | mit | C# |
66c51c031c4476e026d5d9752a0673ff6c9fae1f | Fix a small mistake. | Grabacr07/MetroTrilithon | src/MetroTrilithon.Desktop/UI/Controls/NavigationHelper.cs | src/MetroTrilithon.Desktop/UI/Controls/NavigationHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Xaml.Behaviors;
using Wpf.Ui.Common;
using Wpf.Ui.Controls;
using Wpf.Ui.Controls.Navigation;
namespace MetroTrilithon.UI.Controls;
public class NavigationHelper
{
#region PropagationContext attached property
private static readonly HashSet<NavigationBase> _knownItems = new();
public static readonly DependencyProperty PropagationContextProperty
= DependencyProperty.RegisterAttached(
nameof(PropagationContextProperty).GetPropertyName(),
typeof(object),
typeof(NavigationHelper),
new PropertyMetadata(null, HandlePropagationContextChanged));
public static void SetPropagationContext(DependencyObject element, object value)
=> element.SetValue(PropagationContextProperty, value);
public static object GetPropagationContext(DependencyObject element)
=> element.GetValue(PropagationContextProperty);
private static void HandlePropagationContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not NavigationItem item) throw new NotSupportedException($"The '{nameof(PropagationContextProperty).GetPropertyName()}' attached property is only supported for the '{nameof(NavigationItem)}' type.");
var navigation = item.GetSelfAndAncestors()
.OfType<NavigationBase>()
.FirstOrDefault();
if (navigation?.Frame == null || _knownItems.Add(navigation) == false) return;
Observable.FromEvent<RoutedNavigationEvent, RoutedNavigationEventArgs>(
#pragma warning disable CS8622
handler => (_, args) => handler(args),
#pragma warning restore CS8622
handler => navigation.Navigated += handler,
handler => navigation.Navigated -= handler)
.Zip(Observable.FromEvent<NavigatedEventHandler, NavigationEventArgs>(
handler => (_, args) => handler(args),
handler => navigation.Frame.Navigated += handler,
handler => navigation.Frame.Navigated -= handler))
.Subscribe(args =>
{
if (args.First.CurrentPage is NavigationItem navigationItem
&& args.Second.Content is FrameworkElement element)
{
element.DataContext = GetPropagationContext(navigationItem);
}
});
}
#endregion
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Xaml.Behaviors;
using Wpf.Ui.Common;
using Wpf.Ui.Controls;
using Wpf.Ui.Controls.Navigation;
namespace MetroTrilithon.UI.Controls;
public class NavigationHelper
{
#region PropagationContext attached property
private static readonly HashSet<NavigationBase> _knownItems = new();
public static readonly DependencyProperty PropagationContextProperty
= DependencyProperty.RegisterAttached(
nameof(PropagationContextProperty).GetPropertyName(),
typeof(object),
typeof(NavigationHelper),
new PropertyMetadata(null, HandlePropagationContextChanged));
public static void SetPropagationContext(DependencyObject element, object value)
=> element.SetValue(PropagationContextProperty, value);
public static object GetPropagationContext(DependencyObject element)
=> element.GetValue(PropagationContextProperty);
private static void HandlePropagationContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not NavigationItem item) throw new NotSupportedException($"The '{nameof(PropagationContextProperty).GetPropertyName()}' attached property is only supported for the '{nameof(NavigationItem)}' type.");
var navigation = item.GetSelfAndAncestors()
.OfType<NavigationBase>()
.FirstOrDefault();
if (navigation?.Frame == null || _knownItems.Add(navigation) == false) return;
Observable.FromEvent<RoutedNavigationEvent, RoutedNavigationEventArgs>(
#pragma warning disable CS8622
handler => (_, args) => handler(args),
#pragma warning restore CS8622
handler => navigation.Navigated += handler,
handler => navigation.Navigated -= handler)
.Zip(Observable.FromEvent<NavigatedEventHandler, NavigationEventArgs>(
handler => (_, args) => handler(args),
handler => navigation.Frame.Navigated += handler,
handler => navigation.Frame.Navigated -= handler))
.Subscribe(args =>
{
if (args.First.CurrentPage is NavigationItem navigationItem
&& args.Second.Content is FrameworkElement element)
{
element.DataContext = element.DataContext = GetPropagationContext(navigationItem);
}
});
#endregion
}
}
| mit | C# |
e5ca378a27f677fb1e6c8f9edd08a6b2e972d5c3 | Add EurekaServiceInstance.InstanceId (#55) | SteelToeOSS/Discovery,SteelToeOSS/Discovery,SteelToeOSS/Discovery | src/Steeltoe.Discovery.EurekaBase/EurekaServiceInstance.cs | src/Steeltoe.Discovery.EurekaBase/EurekaServiceInstance.cs | // Copyright 2017 the original author or authors.
//
// 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 Steeltoe.Common.Discovery;
using Steeltoe.Discovery.Eureka.AppInfo;
using System;
using System.Collections.Generic;
namespace Steeltoe.Discovery.Eureka
{
public class EurekaServiceInstance : IServiceInstance
{
private InstanceInfo _info;
public EurekaServiceInstance(InstanceInfo info)
{
this._info = info;
}
public string GetHost()
{
return _info.HostName;
}
public bool IsSecure
{
get
{
return _info.IsSecurePortEnabled;
}
}
public IDictionary<string, string> Metadata
{
get
{
return _info.Metadata;
}
}
public int Port
{
get
{
if (IsSecure)
{
return _info.SecurePort;
}
return _info.Port;
}
}
public string ServiceId
{
get
{
return _info.AppName;
}
}
public Uri Uri
{
get
{
string scheme = IsSecure ? "https" : "http";
return new Uri(scheme + "://" + GetHost() + ":" + Port.ToString());
}
}
public string Host => GetHost();
public string InstanceId => _info.InstanceId;
}
}
| // Copyright 2017 the original author or authors.
//
// 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 Steeltoe.Common.Discovery;
using Steeltoe.Discovery.Eureka.AppInfo;
using System;
using System.Collections.Generic;
namespace Steeltoe.Discovery.Eureka
{
public class EurekaServiceInstance : IServiceInstance
{
private InstanceInfo _info;
public EurekaServiceInstance(InstanceInfo info)
{
this._info = info;
}
public string GetHost()
{
return _info.HostName;
}
public bool IsSecure
{
get
{
return _info.IsSecurePortEnabled;
}
}
public IDictionary<string, string> Metadata
{
get
{
return _info.Metadata;
}
}
public int Port
{
get
{
if (IsSecure)
{
return _info.SecurePort;
}
return _info.Port;
}
}
public string ServiceId
{
get
{
return _info.AppName;
}
}
public Uri Uri
{
get
{
string scheme = IsSecure ? "https" : "http";
return new Uri(scheme + "://" + GetHost() + ":" + Port.ToString());
}
}
public string Host => GetHost();
}
}
| apache-2.0 | C# |
f720b23bc413a77e98e09781d389d52c38214ef7 | Fix BCC for EOI emails | croquet-australia/api.croquet-australia.com.au | source/CroquetAustralia.QueueProcessor/Email/EmailGenerators/U21WorldsEOIEmailGenerator.cs | source/CroquetAustralia.QueueProcessor/Email/EmailGenerators/U21WorldsEOIEmailGenerator.cs | using System.Linq;
using CroquetAustralia.Domain.Features.TournamentEntry.Events;
namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
public class U21WorldsEOIEmailGenerator : BaseEmailGenerator
{
/* todo: remove hard coding of email addresses */
private static readonly EmailAddress U21Coordinator = new EmailAddress("[email protected]", "Croquet Australia - National Co-ordinator Under 21 Croquet");
private static readonly EmailAddress[] BCC =
{
U21Coordinator,
new EmailAddress("[email protected]", "Croquet Australia")
};
public U21WorldsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
: base(emailMessageSettings, U21Coordinator, GetBCC(emailMessageSettings))
{
}
protected override string GetTemplateName(EntrySubmitted entrySubmitted)
{
return "EOI";
}
private static EmailAddress[] GetBCC(EmailMessageSettings emailMessageSettings)
{
return emailMessageSettings.Bcc.Any() ? BCC : new EmailAddress[] {};
}
}
} | using CroquetAustralia.Domain.Features.TournamentEntry.Events;
namespace CroquetAustralia.QueueProcessor.Email.EmailGenerators
{
public class U21WorldsEOIEmailGenerator : BaseEmailGenerator
{
/* todo: remove hard coding of email addresses */
private static readonly EmailAddress U21Coordinator = new EmailAddress("[email protected]", "Croquet Australia - National Co-ordinator Under 21 Croquet");
private static readonly EmailAddress[] BCC =
{
U21Coordinator,
new EmailAddress("[email protected]", "Croquet Australia")
};
public U21WorldsEOIEmailGenerator(EmailMessageSettings emailMessageSettings)
: base(emailMessageSettings, U21Coordinator, BCC)
{
}
protected override string GetTemplateName(EntrySubmitted entrySubmitted)
{
return "EOI";
}
}
} | mit | C# |
d854f712b57fab8bcc506525a15c5d385f75626a | Remove performance optimization. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Models/Label.cs | WalletWasabi/Models/Label.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WalletWasabi.Models
{
public class Label : IEquatable<Label>
{
public static Label Empty { get; } = new Label();
public static char[] Separators { get; } = new[] { ',', ':' };
public IEnumerable<string> Labels { get; }
public bool IsEmpty { get; }
private string LabelString { get; }
public Label(params string[] labels) : this(labels as IEnumerable<string>)
{
}
public Label(IEnumerable<string> labels)
{
labels = labels ?? Enumerable.Empty<string>();
Labels = labels
.SelectMany(x => x?.Split(Separators, StringSplitOptions.RemoveEmptyEntries) ?? new string[0])
.Select(x => x.Trim())
.Where(x => x != "")
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(x => x)
.ToArray();
HashCode = ((IStructuralEquatable)Labels).GetHashCode(EqualityComparer<string>.Default);
IsEmpty = !Labels.Any();
LabelString = string.Join(", ", Labels);
}
public override string ToString() => LabelString;
public static Label Merge(IEnumerable<Label> labels)
{
IEnumerable<string> labelStrings = labels
?.SelectMany(x => x?.Labels ?? Enumerable.Empty<string>())
?.Where(x => x != null);
return new Label(labelStrings);
}
public static Label Merge(params Label[] labels) => Merge(labels as IEnumerable<Label>);
#region Equality
public override bool Equals(object obj) => obj is Label label && this == label;
public bool Equals(Label other) => this == other;
private int HashCode { get; }
public override int GetHashCode() => HashCode;
public static bool operator ==(Label x, Label y)
{
if (x is null && y is null)
{
return true;
}
if (x is null && y != null)
{
return false;
}
if (x != null && y is null)
{
return false;
}
return x.Labels.SequenceEqual(y.Labels);
}
public static bool operator !=(Label x, Label y) => !(x == y);
#endregion Equality
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WalletWasabi.Models
{
public class Label : IEquatable<Label>
{
public static Label Empty { get; } = new Label();
public static char[] Separators { get; } = new[] { ',', ':' };
public IEnumerable<string> Labels { get; }
public bool IsEmpty { get; }
private string LabelString { get; }
public Label(params string[] labels) : this(labels as IEnumerable<string>)
{
}
public Label(IEnumerable<string> labels)
{
labels = labels ?? Enumerable.Empty<string>();
Labels = labels
.SelectMany(x => x?.Split(Separators, StringSplitOptions.RemoveEmptyEntries) ?? new string[0])
.Select(x => x.Trim())
.Where(x => x != "")
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(x => x)
.ToArray();
HashCode = ((IStructuralEquatable)Labels).GetHashCode(EqualityComparer<string>.Default);
IsEmpty = !Labels.Any();
LabelString = string.Join(", ", Labels);
}
public override string ToString() => LabelString;
public static Label Merge(IEnumerable<Label> labels)
{
IEnumerable<string> labelStrings = labels
?.SelectMany(x => x?.Labels ?? Enumerable.Empty<string>())
?.Where(x => x != null);
return new Label(labelStrings);
}
public static Label Merge(params Label[] labels) => Merge(labels as IEnumerable<Label>);
#region Equality
public override bool Equals(object obj) => obj is Label label && this == label;
public bool Equals(Label other) => this == other;
private int HashCode { get; }
public override int GetHashCode() => HashCode;
public static bool operator ==(Label x, Label y)
{
if (x is null)
{
if (y is null)
{
return true;
}
else
{
return false;
}
}
else
{
if (y is null)
{
return false;
}
else
{
return x.Labels.SequenceEqual(y.Labels);
}
}
}
public static bool operator !=(Label x, Label y) => !(x == y);
#endregion Equality
}
}
| mit | C# |
9f34ec90c9d841558e03acdb17fdbe25ee1383af | remove useless code | DanGould/NTumbleBit,NTumbleBit/NTumbleBit | NTumbleBit/Utils.cs | NTumbleBit/Utils.cs | using NBitcoin;
using NTumbleBit.BouncyCastle.Crypto.Engines;
using NTumbleBit.BouncyCastle.Crypto.Parameters;
using NTumbleBit.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NTumbleBit
{
internal static class Utils
{
public static byte[] ChachaEncrypt(byte[] data, ref byte[] key)
{
byte[] iv = null;
return ChachaEncrypt(data, ref key, ref iv);
}
public static byte[] ChachaEncrypt(byte[] data, ref byte[] key, ref byte[] iv)
{
ChaChaEngine engine = new ChaChaEngine();
key = key ?? RandomUtils.GetBytes(128 / 8);
iv = iv ?? RandomUtils.GetBytes(64 / 8);
engine.Init(true, new ParametersWithIV(new KeyParameter(key), iv));
byte[] result = new byte[iv.Length + data.Length];
Array.Copy(iv, result, iv.Length);
engine.ProcessBytes(data, 0, data.Length, result, iv.Length);
return result;
}
public static byte[] ChachaDecrypt(byte[] encrypted, byte[] key)
{
ChaChaEngine engine = new ChaChaEngine();
var iv = new byte[(64 / 8)];
Array.Copy(encrypted, iv, iv.Length);
engine.Init(false, new ParametersWithIV(new KeyParameter(key), iv));
byte[] result = new byte[encrypted.Length - iv.Length];
engine.ProcessBytes(encrypted, iv.Length, encrypted.Length - iv.Length, result, 0);
return result;
}
public static byte[] GenerateEncryptableData(RsaKeyParameters key)
{
while(true)
{
var bytes = RandomUtils.GetBytes(RsaKey.KeySize / 8);
BigInteger input = new BigInteger(1, bytes);
if(input.CompareTo(key.Modulus) >= 0)
continue;
return bytes;
}
}
internal static BigInteger GenerateEncryptableInteger(RsaKeyParameters key)
{
while(true)
{
var bytes = RandomUtils.GetBytes(RsaKey.KeySize / 8);
BigInteger input = new BigInteger(1, bytes);
if(input.CompareTo(key.Modulus) >= 0)
continue;
return input;
}
}
}
}
| using NBitcoin;
using NTumbleBit.BouncyCastle.Crypto.Engines;
using NTumbleBit.BouncyCastle.Crypto.Parameters;
using NTumbleBit.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NTumbleBit
{
internal static class Utils
{
public static byte[] ToBytes(BigInteger num)
{
if(num == null)
throw new ArgumentNullException("num");
return num.ToByteArrayUnsigned();
}
public static byte[] ChachaEncrypt(byte[] data, ref byte[] key)
{
byte[] iv = null;
return ChachaEncrypt(data, ref key, ref iv);
}
public static byte[] ChachaEncrypt(byte[] data, ref byte[] key, ref byte[] iv)
{
ChaChaEngine engine = new ChaChaEngine();
key = key ?? RandomUtils.GetBytes(128 / 8);
iv = iv ?? RandomUtils.GetBytes(64 / 8);
engine.Init(true, new ParametersWithIV(new KeyParameter(key), iv));
byte[] result = new byte[iv.Length + data.Length];
Array.Copy(iv, result, iv.Length);
engine.ProcessBytes(data, 0, data.Length, result, iv.Length);
return result;
}
public static byte[] ChachaDecrypt(byte[] encrypted, byte[] key)
{
ChaChaEngine engine = new ChaChaEngine();
var iv = new byte[(64 / 8)];
Array.Copy(encrypted, iv, iv.Length);
engine.Init(false, new ParametersWithIV(new KeyParameter(key), iv));
byte[] result = new byte[encrypted.Length - iv.Length];
engine.ProcessBytes(encrypted, iv.Length, encrypted.Length - iv.Length, result, 0);
return result;
}
public static BigInteger FromBytes(byte[] data)
{
if(data == null)
throw new ArgumentNullException("data");
return new BigInteger(1, data);
}
public static byte[] GenerateEncryptableData(RsaKeyParameters key)
{
while(true)
{
var bytes = RandomUtils.GetBytes(RsaKey.KeySize / 8);
BigInteger input = new BigInteger(1, bytes);
if(input.CompareTo(key.Modulus) >= 0)
continue;
return bytes;
}
}
internal static BigInteger GenerateEncryptableInteger(RsaKeyParameters key)
{
while(true)
{
var bytes = RandomUtils.GetBytes(RsaKey.KeySize / 8);
BigInteger input = new BigInteger(1, bytes);
if(input.CompareTo(key.Modulus) >= 0)
continue;
return input;
}
}
}
}
| mit | C# |
1398a406e451caac124374cf7f95eb5a7a19ea2e | Use GetDigestSize() | CryptoManiac/NovacoinLibrary | Novacoin/Hash160.cs | Novacoin/Hash160.cs | /**
* Novacoin classes library
* Copyright (C) 2015 Alex D. ([email protected])
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Linq;
using Org.BouncyCastle.Crypto.Digests;
namespace Novacoin
{
/// <summary>
/// Representation of pubkey/script hash.
/// </summary>
public class Hash160 : Hash
{
/// <summary>
/// Computes RIPEMD160 hash using managed library
/// </summary>
//private static readonly RIPEMD160Managed _hasher160 = new RIPEMD160Managed();
private static RipeMD160Digest _hasher160 = new RipeMD160Digest();
private static Sha256Digest _hasher256 = new Sha256Digest();
// 20 bytes
public override int hashSize
{
get { return _hasher160.GetDigestSize(); }
}
public Hash160() : base() { }
public Hash160(byte[] bytes, int offset = 0) : base(bytes, offset) { }
public Hash160(Hash160 h) : base(h) { }
public static Hash160 Compute160(byte[] inputBytes)
{
var dataBytes = inputBytes.ToArray();
var digest1 = new byte[_hasher256.GetDigestSize()];
var digest2 = new byte[_hasher160.GetDigestSize()];
_hasher256.BlockUpdate(dataBytes, 0, dataBytes.Length);
_hasher256.DoFinal(digest1, 0);
_hasher160.BlockUpdate(digest1, 0, digest1.Length);
_hasher160.DoFinal(digest2, 0);
return new Hash160(digest2);
}
}
}
| /**
* Novacoin classes library
* Copyright (C) 2015 Alex D. ([email protected])
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Linq;
using Org.BouncyCastle.Crypto.Digests;
namespace Novacoin
{
/// <summary>
/// Representation of pubkey/script hash.
/// </summary>
public class Hash160 : Hash
{
/// <summary>
/// Computes RIPEMD160 hash using managed library
/// </summary>
//private static readonly RIPEMD160Managed _hasher160 = new RIPEMD160Managed();
private static RipeMD160Digest _hasher160 = new RipeMD160Digest();
private static Sha256Digest _hasher256 = new Sha256Digest();
// 20 bytes
public override int hashSize
{
get { return _hasher160.GetDigestSize(); }
}
public Hash160() : base() { }
public Hash160(byte[] bytes, int offset = 0) : base(bytes, offset) { }
public Hash160(Hash160 h) : base(h) { }
public static Hash160 Compute160(byte[] inputBytes)
{
var dataBytes = inputBytes.ToArray();
var digest1 = new byte[32];
var digest2 = new byte[20];
_hasher256.BlockUpdate(dataBytes, 0, dataBytes.Length);
_hasher256.DoFinal(digest1, 0);
_hasher160.BlockUpdate(digest1, 0, digest1.Length);
_hasher160.DoFinal(digest2, 0);
return new Hash160(digest2);
}
}
}
| agpl-3.0 | C# |
72eb082f916b849ad58041ecf27fa89e6da2251b | Use .Equals | UselessToucan/osu,UselessToucan/osu,Nabile-Rahmani/osu,naoey/osu,naoey/osu,Drezi126/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,DrabWeb/osu,johnneijzen/osu,DrabWeb/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,2yangk23/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,Damnae/osu,smoogipooo/osu,peppy/osu,naoey/osu,Frontear/osuKyzer,DrabWeb/osu,ZLima12/osu,2yangk23/osu | osu.Game/Overlays/KeyConfiguration/KeyBindingsSection.cs | osu.Game/Overlays/KeyConfiguration/KeyBindingsSection.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Input.Bindings;
using osu.Game.Input;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets;
using OpenTK;
namespace osu.Game.Overlays.KeyConfiguration
{
public abstract class KeyBindingsSection : SettingsSection
{
protected IEnumerable<KeyBinding> Defaults;
protected RulesetInfo Ruleset;
protected KeyBindingsSection()
{
FlowContent.Spacing = new Vector2(0, 1);
}
[BackgroundDependencyLoader]
private void load(KeyBindingStore store)
{
var firstDefault = Defaults?.FirstOrDefault();
if (firstDefault == null) return;
var actionType = firstDefault.Action.GetType();
int? variant = null;
// for now let's just assume a variant of zero.
// this will need to be implemented in a better way in the future.
if (Ruleset != null)
variant = 0;
var bindings = store.Query(Ruleset?.ID, variant);
foreach (Enum v in Enum.GetValues(actionType))
{
Add(new KeyBindingRow(v, bindings.Where(b => b.Action.Equals((int)(object)v))));
}
}
}
} | // Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Input.Bindings;
using osu.Game.Input;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets;
using OpenTK;
namespace osu.Game.Overlays.KeyConfiguration
{
public abstract class KeyBindingsSection : SettingsSection
{
protected IEnumerable<KeyBinding> Defaults;
protected RulesetInfo Ruleset;
protected KeyBindingsSection()
{
FlowContent.Spacing = new Vector2(0, 1);
}
[BackgroundDependencyLoader]
private void load(KeyBindingStore store)
{
var firstDefault = Defaults?.FirstOrDefault();
if (firstDefault == null) return;
var actionType = firstDefault.Action.GetType();
int? variant = null;
// for now let's just assume a variant of zero.
// this will need to be implemented in a better way in the future.
if (Ruleset != null)
variant = 0;
var bindings = store.Query(Ruleset?.ID, variant);
foreach (Enum v in Enum.GetValues(actionType))
{
Add(new KeyBindingRow(v, bindings.Where(b => (int)b.Action == (int)(object)v)));
}
}
}
} | mit | C# |
e73aca8f6ed9dab736c21c6fcc5f99ee2b90f6c4 | Remove duplicate code. | nbarbettini/corefx,axelheer/corefx,seanshpark/corefx,krk/corefx,seanshpark/corefx,rubo/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,Ermiar/corefx,alexperovich/corefx,krk/corefx,shimingsg/corefx,Jiayili1/corefx,ptoonen/corefx,gkhanna79/corefx,ravimeda/corefx,the-dwyer/corefx,parjong/corefx,mazong1123/corefx,ptoonen/corefx,ericstj/corefx,krytarowski/corefx,ravimeda/corefx,mazong1123/corefx,richlander/corefx,yizhang82/corefx,axelheer/corefx,wtgodbe/corefx,BrennanConroy/corefx,ravimeda/corefx,Ermiar/corefx,cydhaselton/corefx,ViktorHofer/corefx,stone-li/corefx,nbarbettini/corefx,stone-li/corefx,nbarbettini/corefx,zhenlan/corefx,alexperovich/corefx,dotnet-bot/corefx,billwert/corefx,ViktorHofer/corefx,cydhaselton/corefx,Ermiar/corefx,mmitche/corefx,MaggieTsang/corefx,mazong1123/corefx,gkhanna79/corefx,shimingsg/corefx,krk/corefx,axelheer/corefx,twsouthwick/corefx,alexperovich/corefx,wtgodbe/corefx,richlander/corefx,gkhanna79/corefx,krytarowski/corefx,alexperovich/corefx,dotnet-bot/corefx,jlin177/corefx,ravimeda/corefx,tijoytom/corefx,yizhang82/corefx,gkhanna79/corefx,ericstj/corefx,ptoonen/corefx,axelheer/corefx,ptoonen/corefx,yizhang82/corefx,rubo/corefx,MaggieTsang/corefx,rubo/corefx,gkhanna79/corefx,zhenlan/corefx,seanshpark/corefx,fgreinacher/corefx,seanshpark/corefx,stone-li/corefx,nchikanov/corefx,tijoytom/corefx,seanshpark/corefx,nchikanov/corefx,Ermiar/corefx,mmitche/corefx,Jiayili1/corefx,Ermiar/corefx,dotnet-bot/corefx,richlander/corefx,axelheer/corefx,richlander/corefx,stone-li/corefx,Jiayili1/corefx,ViktorHofer/corefx,DnlHarvey/corefx,nchikanov/corefx,BrennanConroy/corefx,ViktorHofer/corefx,the-dwyer/corefx,nchikanov/corefx,ViktorHofer/corefx,stone-li/corefx,DnlHarvey/corefx,wtgodbe/corefx,shimingsg/corefx,the-dwyer/corefx,fgreinacher/corefx,Jiayili1/corefx,nbarbettini/corefx,dotnet-bot/corefx,Jiayili1/corefx,MaggieTsang/corefx,shimingsg/corefx,yizhang82/corefx,ericstj/corefx,seanshpark/corefx,twsouthwick/corefx,DnlHarvey/corefx,shimingsg/corefx,ericstj/corefx,mmitche/corefx,tijoytom/corefx,the-dwyer/corefx,cydhaselton/corefx,jlin177/corefx,the-dwyer/corefx,richlander/corefx,cydhaselton/corefx,cydhaselton/corefx,mazong1123/corefx,nchikanov/corefx,billwert/corefx,rubo/corefx,yizhang82/corefx,parjong/corefx,krytarowski/corefx,MaggieTsang/corefx,krk/corefx,mmitche/corefx,ericstj/corefx,yizhang82/corefx,shimingsg/corefx,Ermiar/corefx,jlin177/corefx,nbarbettini/corefx,jlin177/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,billwert/corefx,zhenlan/corefx,billwert/corefx,jlin177/corefx,yizhang82/corefx,parjong/corefx,wtgodbe/corefx,zhenlan/corefx,tijoytom/corefx,Ermiar/corefx,twsouthwick/corefx,tijoytom/corefx,richlander/corefx,nbarbettini/corefx,fgreinacher/corefx,mmitche/corefx,ptoonen/corefx,krytarowski/corefx,shimingsg/corefx,tijoytom/corefx,krk/corefx,zhenlan/corefx,billwert/corefx,ptoonen/corefx,mazong1123/corefx,twsouthwick/corefx,gkhanna79/corefx,parjong/corefx,MaggieTsang/corefx,axelheer/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,rubo/corefx,krytarowski/corefx,Jiayili1/corefx,ravimeda/corefx,billwert/corefx,mazong1123/corefx,Jiayili1/corefx,ericstj/corefx,alexperovich/corefx,MaggieTsang/corefx,parjong/corefx,alexperovich/corefx,ericstj/corefx,twsouthwick/corefx,zhenlan/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,BrennanConroy/corefx,DnlHarvey/corefx,jlin177/corefx,nchikanov/corefx,nchikanov/corefx,krk/corefx,MaggieTsang/corefx,nbarbettini/corefx,wtgodbe/corefx,seanshpark/corefx,stone-li/corefx,JosephTremoulet/corefx,the-dwyer/corefx,mmitche/corefx,ViktorHofer/corefx,tijoytom/corefx,twsouthwick/corefx,twsouthwick/corefx,krytarowski/corefx,parjong/corefx,ravimeda/corefx,mazong1123/corefx,billwert/corefx,wtgodbe/corefx,zhenlan/corefx,alexperovich/corefx,dotnet-bot/corefx,krk/corefx,stone-li/corefx,the-dwyer/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,mmitche/corefx,krytarowski/corefx,fgreinacher/corefx,ptoonen/corefx,parjong/corefx,richlander/corefx,cydhaselton/corefx,jlin177/corefx,wtgodbe/corefx,gkhanna79/corefx,ravimeda/corefx,dotnet-bot/corefx,ViktorHofer/corefx,cydhaselton/corefx | src/System.Runtime.InteropServices/src/System/Runtime/InteropServices/RuntimeEnvironment.cs | src/System.Runtime.InteropServices/src/System/Runtime/InteropServices/RuntimeEnvironment.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.IO;
using System.Reflection;
namespace System.Runtime.InteropServices
{
public static class RuntimeEnvironment
{
public static string SystemConfigurationFile
{
get
{
throw new PlatformNotSupportedException();
}
}
public static bool FromGlobalAccessCache(System.Reflection.Assembly a)
{
return false;
}
public static string GetRuntimeDirectory()
{
string runtimeDirectory = typeof(object).Assembly.Location;
if (!Path.IsPathRooted(runtimeDirectory))
{
runtimeDirectory = AppDomain.CurrentDomain.BaseDirectory;
}
return Path.GetDirectoryName(runtimeDirectory) + Path.DirectorySeparatorChar;
}
public static System.IntPtr GetRuntimeInterfaceAsIntPtr(Guid clsid, Guid riid)
{
throw new PlatformNotSupportedException();
}
public static object GetRuntimeInterfaceAsObject(Guid clsid, Guid riid)
{
throw new PlatformNotSupportedException();
}
public static string GetSystemVersion()
{
return typeof(object).Assembly.ImageRuntimeVersion;
}
}
}
| // 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.IO;
using System.Reflection;
namespace System.Runtime.InteropServices
{
public static class RuntimeEnvironment
{
public static string SystemConfigurationFile
{
get
{
throw new PlatformNotSupportedException();
}
}
public static bool FromGlobalAccessCache(System.Reflection.Assembly a)
{
return false;
}
public static string GetRuntimeDirectory()
{
string runtimeDirectory = typeof(object).Assembly.Location;
if(string.IsNullOrEmpty(runtimeDirectory) || !Path.IsPathRooted(runtimeDirectory))
{
return Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) + Path.DirectorySeparatorChar;
}
return Path.GetDirectoryName(runtimeDirectory) + Path.DirectorySeparatorChar;
}
public static System.IntPtr GetRuntimeInterfaceAsIntPtr(Guid clsid, Guid riid)
{
throw new PlatformNotSupportedException();
}
public static object GetRuntimeInterfaceAsObject(Guid clsid, Guid riid)
{
throw new PlatformNotSupportedException();
}
public static string GetSystemVersion()
{
return typeof(object).Assembly.ImageRuntimeVersion;
}
}
}
| mit | C# |
d4cbd2d2f1eda571547d020d8a1dc98759f866e2 | Update AddressDialog.cs | Esri/workflowmanager-samples,Esri/workflowmanager-samples,Esri/workflowmanager-samples | CustomAOICommand/CSharp/AddressDialog.cs | CustomAOICommand/CSharp/AddressDialog.cs | /*Copyright 2015 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace JTXSamples
{
public partial class AddressDialog : Form
{
public AddressDialog()
{
InitializeComponent();
}
public string street;
private void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
street = txtStreetAddress.Text;
this.Hide();
}
private void cmdCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
this.Hide();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace JTXSamples
{
public partial class AddressDialog : Form
{
public AddressDialog()
{
InitializeComponent();
}
public string street;
private void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
street = txtStreetAddress.Text;
this.Hide();
}
private void cmdCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
this.Hide();
}
}
} | apache-2.0 | C# |
1b7f603cf68ea1fd28f16e339fbf8af4d9a8fbcd | Add edge and add edge impl | DasAllFolks/SharpGraphs | Graph/AbstractGraph.cs | Graph/AbstractGraph.cs | using System;
using System.Collections.Generic;
namespace Graph
{
/// <summary>
/// Implements shared functionality among both
/// see cref="SimpleGraph{V, E, W}"/>s and
/// <see cref="MultiGraph{V, E, W}"/>s.
/// </summary>
/// <typeparam name="V">
/// The type used to create vertex (node) labels.
/// </typeparam>
/// <typeparam name="E">The edge type.</typeparam>
/// <typeparam name="W">
/// The type used for the edge weight.
/// </typeparam>
public abstract class AbstractGraph<V, E, W> : IGraph<V, E, W>
where V : struct, IEquatable<V>
where E : IEdge<V, W>
where W : struct, IComparable<W>, IEquatable<W>
{
/// <summary>
/// The graph's vertices.
/// </summary>
protected readonly ISet<V> vertices = new HashSet<V>();
/// <summary>
/// Attempts to add a vertex to the graph.
/// </summary>
/// <param name="vertex">The vertex.</param>
/// <returns>
/// True if the vertex was successfully added, false if it already
/// existed.
/// </returns>
public bool TryAddVertex(V vertex)
{
return vertices.Add(vertex);
}
/// <summary>
/// Attempts to remove a vertex from the graph.
/// </summary>
/// <param name="vertex">The vertex.</param>
/// <returns>
/// True if the vertex was successfully removed, false if no such
/// vertex was found in the graph.
/// </returns>
public bool TryRemoveVertex(V vertex)
{
return vertices.Remove(vertex);
}
/// <summary>
/// Attempts to add an edge to the graph.
/// </summary>
/// <param name="edge">
/// The edge.
/// </param>
/// <param name="allowNewVertices">
/// Iff true, add vertices in the edge which aren't yet in the graph
/// to the graph's vertex set.
/// </param>
/// <returns>
/// True if the edge was successfully added (the definition of
/// "success" may vary from implementation to implementation).
/// </returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the edge contains at least one edge not in the graph,
/// and allowNewVertices is set to false.
/// </exception>
public bool TryAddEdge(E edge, bool allowNewVertices = false)
{
if (edge == null)
{
throw new ArgumentNullException();
}
// XXXX: Need a way to check vertices here.
if (!allowNewVertices && !())
{
}
return TryAddEdgeImpl(edge);
}
protected bool TryAddEdgeImpl(E edge)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
namespace Graph
{
/// <summary>
/// Implements shared functionality among both
/// see cref="SimpleGraph{V, E, W}"/>s and
/// <see cref="MultiGraph{V, E, W}"/>s.
/// </summary>
/// <typeparam name="V">
/// The type used to create vertex (node) labels.
/// </typeparam>
/// <typeparam name="E">The edge type.</typeparam>
/// <typeparam name="W">
/// The type used for the edge weight.
/// </typeparam>
public abstract class AbstractGraph<V, E, W> : IGraph<V, E, W>
where V : struct, IEquatable<V>
where E : IEdge<V, W>
where W : struct, IComparable<W>, IEquatable<W>
{
/// <summary>
/// The graph's vertices.
/// </summary>
protected readonly ISet<V> vertices = new HashSet<V>();
/// <summary>
/// Attempts to add a vertex to the graph.
/// </summary>
/// <param name="vertex">The vertex.</param>
/// <returns>
/// True if the vertex was successfully added, false if it already
/// existed.
/// </returns>
public bool TryAddVertex(V vertex)
{
return vertices.Add(vertex);
}
/// <summary>
/// Attempts to remove a vertex from the graph.
/// </summary>
/// <param name="vertex">The vertex.</param>
/// <returns>
/// True if the vertex was successfully removed, false if no such
/// vertex was found in the graph.
/// </returns>
public bool TryRemoveVertex(V vertex)
{
return vertices.Remove(vertex);
}
}
}
| apache-2.0 | C# |
4bff85e6ba0f6f56d995f7e0ef3016994a920478 | Fix keys on the server app | ermau/Tempest.Social | Desktop/Tempest.Social.Server/Program.cs | Desktop/Tempest.Social.Server/Program.cs | using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Tempest.Providers.Network;
namespace Tempest.Social.Server
{
class Program
{
private static readonly PublicKeyIdentityProvider IdentityProvider = new PublicKeyIdentityProvider();
static void Main (string[] args)
{
Console.WriteLine ("Getting server key...");
RSAAsymmetricKey key = GetKey ("server.key");
Console.WriteLine ("Got it.");
var provider = new NetworkConnectionProvider (
new[] { SocialProtocol.Instance },
new Target (Target.AnyIP, 42912),
10000,
key);
SocialServer server = new SocialServer (new MemoryWatchListProvider(), IdentityProvider);
server.ConnectionMade += OnConnectionMade;
server.AddConnectionProvider (provider);
server.Start();
Console.WriteLine ("Server ready.");
while (true)
Thread.Sleep (1000);
}
private static void OnConnectionMade (object sender, ConnectionMadeEventArgs e)
{
Console.WriteLine ("Connection made");
}
sealed class RSAParametersSerializer
: ISerializer<RSAParameters>
{
public static readonly RSAParametersSerializer Instance = new RSAParametersSerializer();
public static void Serialize (IValueWriter writer, RSAParameters element)
{
Instance.Serialize (null, writer, element);
}
public static RSAParameters Deserialize (IValueReader reader)
{
return Instance.Deserialize (null, reader);
}
public void Serialize (ISerializationContext context, IValueWriter writer, RSAParameters element)
{
writer.WriteBytes (element.D);
writer.WriteBytes (element.DP);
writer.WriteBytes (element.DQ);
writer.WriteBytes (element.Exponent);
writer.WriteBytes (element.InverseQ);
writer.WriteBytes (element.Modulus);
writer.WriteBytes (element.P);
writer.WriteBytes (element.Q);
}
public RSAParameters Deserialize (ISerializationContext context, IValueReader reader)
{
return new RSAParameters {
D = reader.ReadBytes(),
DP = reader.ReadBytes(),
DQ = reader.ReadBytes(),
Exponent = reader.ReadBytes(),
InverseQ = reader.ReadBytes(),
Modulus = reader.ReadBytes(),
P = reader.ReadBytes(),
Q = reader.ReadBytes()
};
}
}
private static RSAAsymmetricKey GetKey (string keypath)
{
if (!File.Exists (keypath)) {
var rsa = new RSACrypto();
RSAParameters parameters = rsa.ExportKey (true);
using (var stream = File.OpenWrite (keypath)) {
var writer = new StreamValueWriter (stream);
RSAParametersSerializer.Serialize (writer, parameters);
}
}
RSAAsymmetricKey key;
using (var stream = File.OpenRead (keypath)) {
var reader = new StreamValueReader (stream);
RSAParameters parameters = RSAParametersSerializer.Deserialize (reader);
key = new RSAAsymmetricKey (parameters);
}
return key;
}
}
}
| using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using Tempest.Providers.Network;
namespace Tempest.Social.Server
{
class Program
{
private static readonly PublicKeyIdentityProvider IdentityProvider = new PublicKeyIdentityProvider();
static void Main (string[] args)
{
Console.WriteLine ("Getting server key...");
RSAAsymmetricKey key = GetKey ("server.key");
Console.WriteLine ("Got it.");
var provider = new NetworkConnectionProvider (
new[] { SocialProtocol.Instance },
new Target (Target.AnyIP, 42912),
10000,
key);
SocialServer server = new SocialServer (new MemoryWatchListProvider(), IdentityProvider);
server.ConnectionMade += OnConnectionMade;
server.AddConnectionProvider (provider);
server.Start();
Console.WriteLine ("Server ready.");
while (true)
Thread.Sleep (1000);
}
private static void OnConnectionMade (object sender, ConnectionMadeEventArgs e)
{
Console.WriteLine ("Connection made");
}
private static RSAAsymmetricKey GetKey (string path)
{
RSAAsymmetricKey key = null;
if (!File.Exists (path))
{
RSACrypto crypto = new RSACrypto();
key = crypto.ExportKey (true);
using (FileStream stream = File.Create (path))
key.Serialize (null, new StreamValueWriter (stream));
}
if (key == null)
{
using (FileStream stream = File.OpenRead (path))
key = new RSAAsymmetricKey (null, new StreamValueReader (stream));
}
return key;
}
}
}
| mit | C# |
11f4dc0d10baa1c421b10fc2f6ffd8d8a7f2ae21 | Add a missing null-conditional in CommandContext#ctor | LassieME/Discord.Net,RogueException/Discord.Net,Confruggy/Discord.Net,AntiTcb/Discord.Net | src/Discord.Net.Commands/CommandContext.cs | src/Discord.Net.Commands/CommandContext.cs | namespace Discord.Commands
{
public struct CommandContext
{
public IDiscordClient Client { get; }
public IGuild Guild { get; }
public IMessageChannel Channel { get; }
public IUser User { get; }
public IUserMessage Message { get; }
public bool IsPrivate => Channel is IPrivateChannel;
public CommandContext(IDiscordClient client, IGuild guild, IMessageChannel channel, IUser user, IUserMessage msg)
{
Client = client;
Guild = guild;
Channel = channel;
User = user;
Message = msg;
}
public CommandContext(IDiscordClient client, IUserMessage msg)
{
Client = client;
Guild = (msg.Channel as IGuildChannel)?.Guild;
Channel = msg.Channel;
User = msg.Author;
Message = msg;
}
}
}
| namespace Discord.Commands
{
public struct CommandContext
{
public IDiscordClient Client { get; }
public IGuild Guild { get; }
public IMessageChannel Channel { get; }
public IUser User { get; }
public IUserMessage Message { get; }
public bool IsPrivate => Channel is IPrivateChannel;
public CommandContext(IDiscordClient client, IGuild guild, IMessageChannel channel, IUser user, IUserMessage msg)
{
Client = client;
Guild = guild;
Channel = channel;
User = user;
Message = msg;
}
public CommandContext(IDiscordClient client, IUserMessage msg)
{
Client = client;
Guild = (msg.Channel as IGuildChannel).Guild;
Channel = msg.Channel;
User = msg.Author;
Message = msg;
}
}
}
| mit | C# |
230f40540cb21abec4d0ba3f6206a3f38ff8437a | fix typo | AdaptiveConsulting/ReactiveTrader,LeeCampbell/ReactiveTrader,abbasmhd/ReactiveTrader,AdaptiveConsulting/ReactiveTrader,rikoe/ReactiveTrader,mrClapham/ReactiveTrader,LeeCampbell/ReactiveTrader,singhdev/ReactiveTrader,akrisiun/ReactiveTrader,singhdev/ReactiveTrader,abbasmhd/ReactiveTrader,HalidCisse/ReactiveTrader,jorik041/ReactiveTrader,abbasmhd/ReactiveTrader,akrisiun/ReactiveTrader,mrClapham/ReactiveTrader,jorik041/ReactiveTrader,HalidCisse/ReactiveTrader,mrClapham/ReactiveTrader,mrClapham/ReactiveTrader,rikoe/ReactiveTrader,LeeCampbell/ReactiveTrader,LeeCampbell/ReactiveTrader,singhdev/ReactiveTrader,akrisiun/ReactiveTrader,jorik041/ReactiveTrader,abbasmhd/ReactiveTrader,rikoe/ReactiveTrader,HalidCisse/ReactiveTrader,akrisiun/ReactiveTrader,singhdev/ReactiveTrader,rikoe/ReactiveTrader,HalidCisse/ReactiveTrader,jorik041/ReactiveTrader | src/Adaptive.ReactiveTrader.Client.WindowsStoreApp/App.xaml.cs | src/Adaptive.ReactiveTrader.Client.WindowsStoreApp/App.xaml.cs | using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Adaptive.ReactiveTrader.Client.Configuration;
using Adaptive.ReactiveTrader.Client.Domain;
using Adaptive.ReactiveTrader.Client.UI.Shell;
using Adaptive.ReactiveTrader.Shared.Logging;
using Autofac;
namespace Adaptive.ReactiveTrader.Client
{
sealed partial class App : Application
{
public App()
{
InitializeComponent();
Suspending += OnSuspending;
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
DebugSettings.EnableFrameRateCounter = true;
}
#endif
var shellView = Window.Current.Content as ShellView;
if (shellView == null)
{
var bootstrapper = new Bootstrapper();
var container = bootstrapper.Build();
var reactiveTraderApi = container.Resolve<IReactiveTrader>();
var username = container.Resolve<IUserProvider>().Username;
reactiveTraderApi.Initialize(username, container.Resolve<IConfigurationProvider>().Servers, container.Resolve<ILoggerFactory>());
shellView = new ShellView {DataContext = container.Resolve<IShellViewModel>()};
Window.Current.Content = shellView;
}
Window.Current.Activate();
}
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Adaptive.ReactiveTrader.Client.Configuration;
using Adaptive.ReactiveTrader.Client.Domain;
using Adaptive.ReactiveTrader.Client.UI.Shell;
using Adaptive.ReactiveTrader.Shared.Logging;
using Autofac;
namespace Adaptive.ReactiveTrader.Client
{
sealed partial class App : Application
{
public App()
{
InitializeComponent();
Suspending += OnSuspending;
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
DebugSettings.EnableFrameRateCounter = true;
}
#endif
var shellView = Window.Current.Content as ShellView;
if (shellView == null)
{
var bootstrapper = new Bootstrapper();
var container = bootstrapper.Build();
var reactiveTraderApi = container.Resolve<IReactiveTrader>();
var username = container.Resolve<IUserProvider>().Username;
reactiveTraderApi.Initialize(username, container.Resolve<IConfigurationProvider>().Servers, container.Resolve<ILoggerFactory>()));
shellView = new ShellView {DataContext = container.Resolve<IShellViewModel>()};
Window.Current.Content = shellView;
}
Window.Current.Activate();
}
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| apache-2.0 | C# |
291d3fe4e49894a7850a98d0e4a823398e741591 | Update OpeningFilesThroughStream.cs | asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Files/Handling/OpeningFilesThroughStream.cs | Examples/CSharp/Files/Handling/OpeningFilesThroughStream.cs | using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Files.Handling
{
public class OpeningFilesThroughStream
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Opening through Stream
//Create a Stream object
FileStream fstream = new FileStream(dataDir + "Book2.xls", FileMode.Open);
//Creating a Workbook object, open the file from a Stream object
//that contains the content of file and it should support seeking
Workbook workbook2 = new Workbook(fstream);
Console.WriteLine("Workbook opened using stream successfully!");
fstream.Close();
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.Files.Handling
{
public class OpeningFilesThroughStream
{
public static void Main(string[] args)
{
//Exstart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Opening through Stream
//Create a Stream object
FileStream fstream = new FileStream(dataDir + "Book2.xls", FileMode.Open);
//Creating a Workbook object, open the file from a Stream object
//that contains the content of file and it should support seeking
Workbook workbook2 = new Workbook(fstream);
Console.WriteLine("Workbook opened using stream successfully!");
fstream.Close();
//ExEnd:1
}
}
}
| mit | C# |
f96bab6e8ab38f72e9829a4ed91e3a7cba3766c2 | Fix one final snippet | nodatime/nodatime,malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,malcolmr/nodatime,malcolmr/nodatime,jskeet/nodatime,BenJenkinson/nodatime,BenJenkinson/nodatime,jskeet/nodatime | src/NodaTime.Demo/YearMonthDemo.cs | src/NodaTime.Demo/YearMonthDemo.cs | // Copyright 2019 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NUnit.Framework;
using NodaTime.Calendars;
namespace NodaTime.Demo
{
public class YearMonthDemo
{
[Test]
public void ConstructionWithExplicitYearAndMonth()
{
YearMonth yearMonth = Snippet.For(new YearMonth(2019, 5));
Assert.AreEqual(2019, yearMonth.Year);
Assert.AreEqual(5, yearMonth.Month);
Assert.AreEqual(CalendarSystem.Iso, yearMonth.Calendar);
}
[Test]
public void ConstructionFromEra()
{
YearMonth yearMonth = Snippet.For(new YearMonth(Era.Common, 1994, 5));
Assert.AreEqual(1994, yearMonth.Year);
Assert.AreEqual(5, yearMonth.Month);
Assert.AreEqual(CalendarSystem.Iso, yearMonth.Calendar);
Assert.AreEqual(Era.Common, yearMonth.Era);
}
[Test]
public void ConstructionWithExplicitCalendar()
{
YearMonth yearMonth = Snippet.For(new YearMonth(2014, 3, CalendarSystem.Julian));
Assert.AreEqual(2014, yearMonth.Year);
Assert.AreEqual(3, yearMonth.Month);
Assert.AreEqual(CalendarSystem.Julian, yearMonth.Calendar);
}
[Test]
public void ConstructionWithExplicitCalendar2()
{
YearMonth yearMonth = Snippet.For(new YearMonth(Era.Common, 2019, 5, CalendarSystem.Gregorian));
Assert.AreEqual(2019, yearMonth.Year);
Assert.AreEqual(5, yearMonth.Month);
Assert.AreEqual(CalendarSystem.Gregorian, yearMonth.Calendar);
Assert.AreEqual(Era.Common, yearMonth.Era);
}
[Test]
public void ToDateInterval()
{
YearMonth yearMonth = new YearMonth(2019, 5);
DateInterval interval = Snippet.For(yearMonth.ToDateInterval());
Assert.AreEqual(new LocalDate(2019, 5, 1), interval.Start);
Assert.AreEqual(new LocalDate(2019, 5, 31), interval.End);
}
}
}
| // Copyright 2019 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NUnit.Framework;
using NodaTime.Calendars;
namespace NodaTime.Demo
{
public class YearMonthDemo
{
[Test]
public void ConstructionWithExplicitYearAndMonth()
{
YearMonth yearMonth = Snippet.For(new YearMonth(2019, 5));
Assert.AreEqual(2019, yearMonth.Year);
Assert.AreEqual(5, yearMonth.Month);
Assert.AreEqual(CalendarSystem.Iso, yearMonth.Calendar);
}
[Test]
public void ConstructionFromEra()
{
YearMonth yearMonth = Snippet.For(new YearMonth(Era.Common, 1994, 5));
Assert.AreEqual(1994, yearMonth.Year);
Assert.AreEqual(5, yearMonth.Month);
Assert.AreEqual(CalendarSystem.Iso, yearMonth.Calendar);
Assert.AreEqual(Calendars.Era.Common, yearMonth.Era);
}
[Test]
public void ConstructionWithExplicitCalendar()
{
YearMonth yearMonth = Snippet.For(new YearMonth(2014, 3, CalendarSystem.Julian));
Assert.AreEqual(2014, yearMonth.Year);
Assert.AreEqual(3, yearMonth.Month);
Assert.AreEqual(CalendarSystem.Julian, yearMonth.Calendar);
}
[Test]
public void ConstructionWithExplicitCalendar2()
{
YearMonth yearMonth = Snippet.For(new YearMonth(Era.Common, 2019, 5, CalendarSystem.Gregorian));
Assert.AreEqual(2019, yearMonth.Year);
Assert.AreEqual(5, yearMonth.Month);
Assert.AreEqual(CalendarSystem.Gregorian, yearMonth.Calendar);
Assert.AreEqual(Era.Common, yearMonth.Era);
}
[Test]
public void ToDateInterval()
{
YearMonth yearMonth = new YearMonth(2019, 5);
DateInterval interval = Snippet.For(yearMonth.ToDateInterval());
Assert.AreEqual(new LocalDate(2019, 5, 1), interval.Start);
Assert.AreEqual(new LocalDate(2019, 5, 31), interval.End);
}
}
}
| apache-2.0 | C# |
35a9ad7de7ae6532ca5c482c69788202db936cd6 | Include text in message | amattias/Telegram-Bot-API-Client | src/TelegramBotAPIClient/Models/Message.cs | src/TelegramBotAPIClient/Models/Message.cs | using Newtonsoft.Json;
using System;
using TelegramBotAPIClient.Converters;
namespace TelegramBotAPIClient.Models
{
/// <summary>
/// This object represents a message.
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class Message
{
/// <summary>
/// Unique message identifier
/// </summary>
[JsonProperty("message_id", Required = Required.Always)]
public int MessageId { get; set; }
/// <summary>
/// Sender
/// </summary>
[JsonProperty("from", Required = Required.Default)]
public User From { get; set; }
/// <summary>
/// Conversation the message belongs to
/// </summary>
[JsonProperty("chat", Required = Required.Always)]
public Chat Chat { get; set; }
/// <summary>
/// Date the message was sent
/// </summary>
[JsonProperty("date", Required = Required.Always)]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Date { get; set; }
/// <summary>
/// Optional. Title, for channels and group chats
/// </summary>
[JsonProperty(PropertyName = "text", Required = Required.Default)]
public string Text { get; set; }
}
}
| using Newtonsoft.Json;
using System;
using TelegramBotAPIClient.Converters;
namespace TelegramBotAPIClient.Models
{
/// <summary>
/// This object represents a message.
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class Message
{
/// <summary>
/// Unique message identifier
/// </summary>
[JsonProperty("message_id", Required = Required.Always)]
public int MessageId { get; set; }
/// <summary>
/// Sender
/// </summary>
[JsonProperty("from", Required = Required.Default)]
public User From { get; set; }
/// <summary>
/// Conversation the message belongs to
/// </summary>
[JsonProperty("chat", Required = Required.Always)]
public Chat Chat { get; set; }
/// <summary>
/// Date the message was sent
/// </summary>
[JsonProperty("date", Required = Required.Always)]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Date { get; set; }
}
}
| mit | C# |
69bf9caa7f922e0902dfd232a18a55ab81f555ba | Update ArgbColorTypeConverter.cs | wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Serializer.Xaml/Converters/ArgbColorTypeConverter.cs | src/Serializer.Xaml/Converters/ArgbColorTypeConverter.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;
using System.Globalization;
#if NETSTANDARD
using System.ComponentModel;
#else
using Portable.Xaml.ComponentModel;
#endif
using Core2D.Style;
namespace Serializer.Xaml.Converters
{
/// <summary>
/// Defines <see cref="ArgbColor"/> type converter.
/// </summary>
internal class ArgbColorTypeConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ArgbColor.Parse((string)value);
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var color = value as ArgbColor;
if (color != null)
{
return ArgbColor.ToHtml(color);
}
throw new NotSupportedException();
}
}
}
| // 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 Core2D.Style;
using Portable.Xaml.ComponentModel;
using System;
using System.ComponentModel;
using System.Globalization;
namespace Serializer.Xaml.Converters
{
/// <summary>
/// Defines <see cref="ArgbColor"/> type converter.
/// </summary>
internal class ArgbColorTypeConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ArgbColor.Parse((string)value);
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var color = value as ArgbColor;
if (color != null)
{
return ArgbColor.ToHtml(color);
}
throw new NotSupportedException();
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.