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 |
---|---|---|---|---|---|---|---|---|
055b85109bbc23ad7a93ca281ef30e7d844d5491 | Update QuickFind.cs | qdimka/Algorithms,qdimka/Algorithms,Oscarbralo/Algorithms,Oscarbralo/Algorithms,qdimka/Algorithms,Oscarbralo/Algorithms | CSharpQuickFind/QuickFind.cs | CSharpQuickFind/QuickFind.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickFind
{
public class QuickFind
{
private int[] id;
//Initialize the quick find data structure
public QuickFind(int n)
{
int count = -1;
id = new int[n].Select(x => x = ++count).ToArray<int>();
}
//Join two components
public void Union(int p, int q)
{
id = (id[p] != id[q]) ? id.Select(x => (x == id[p]) ? x = id[q] : x).ToArray<int>() : id;
}
//CHeck if two components are connected
public bool AreConnected(int p, int q)
{
return (id[p] == id[q]) ? true : false;
}
//Count the number of connected components
public int CountComponents()
{
return id.Distinct().Count();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickFind
{
public class QuickFind
{
private int[] id;
//Initialize the quick find data structure
public QuickFind(int n)
{
int count = -1;
id = new int[n].Select(x => x = ++count).ToArray<int>();
}
//Join two components
public void union(int p, int q)
{
id = (id[p] != id[q]) ? id.Select(x => (x == id[p]) ? x = id[q] : x).ToArray<int>() : id;
}
//CHeck if two components are connected
public bool areConnected(int p, int q)
{
return (id[p] == id[q]) ? true : false;
}
//Count the number of connected components
public int countComponents()
{
return id.Distinct().Count();
}
}
}
| mit | C# |
8fad2161792e7e92694e3256ef9ee8bb42be3325 | Expand on the JwsHeader class. | PaulTrampert/CertManager,PaulTrampert/CertManager | CertManager/Jws/JwsHeader.cs | CertManager/Jws/JwsHeader.cs | namespace CertManager.Jws
{
public class JwsHeader
{
/// <summary>
/// Algorithm
/// </summary>
public string Alg { get; set; }
/// <summary>
/// JWK Set Url
/// </summary>
public string Jku { get; set; }
/// <summary>
/// JSON Web Key
/// </summary>
public string Jwk { get; set; }
/// <summary>
/// Key ID
/// </summary>
public string Kid { get; set; }
/// <summary>
/// X.509 URL
/// </summary>
public string X5u { get; set; }
/// <summary>
/// X.509 Certificate Chain
/// </summary>
public string[] X5c { get; set; }
/// <summary>
/// X.509 Certificate SHA-1 Thumbprint
/// </summary>
public string X5t { get; set; }
/// <summary>
/// X.509 Certificate SHA-256 Thumbprint
/// </summary>
public string X5ts256 { get; set; }
/// <summary>
/// Type
/// </summary>
public string Typ { get; set; }
/// <summary>
/// Content Type
/// </summary>
public string Cty { get; set; }
/// <summary>
/// Critical
/// </summary>
public string Crit { get; set; }
}
} | namespace CertManager.Jws
{
public class JwsHeader
{
public string Alg { get; set; }
public string Jwk { get; set; }
public string Nonce { get; set; }
}
} | mit | C# |
d6ba314d54b75caad3fcbb7370f7032be3073f56 | Make Setting.asset files | CloudBreadProject/CloudBread-Unity-SDK | Assets/CloudBread/Editor/CBAuthEditor.cs | Assets/CloudBread/Editor/CBAuthEditor.cs | using UnityEngine;
using UnityEditor;
using System.Collections;
namespace CloudBread
{
public class CBAuthEditor : EditorWindow
{
private const string LoginSettingsAssetName = "FacebookLoginSettings";
private const string LoginSettingsPath = "CloudBread/Resources";
private const string LoginSettingsAssetExtension = ".asset";
static CBAuthEditor _instance = null;
[MenuItem("CloudBread/CB-Authentication")]
public static void InitWindow()
{
if (null == _instance)
{
_instance = GetWindow<CBAuthEditor>();
}
else
{
_instance.Close();
}
}
bool _useFacebookAuth = true;
bool _useGoogleAuth = false;
void OnGUI()
{
GUILayout.BeginVertical ();
{
// GUILayout.Box("CloudBread Login Service - OAuth 2.0", "IN BigTitle");
// GUILayout.Label("");
GUILayout.Label ("CloudBread Login Service - OAuth 2.0");
GUILayout.Box ("To configure CloudBread Login Service in this Project,\n" +
"you can get more information in our Project Sites", "IN Title");
GUILayout.Label ("CloudBread 로그인 서비스를 설정하려면, 아래 프로젝트 사이트를 참조하세요.");
if (GUILayout.Button("OpenSource Project - CloudBread.", GUI.skin.box))
{
Application.OpenURL("https://github.com/CloudBreadProject/");
}
if (GUILayout.Toggle (_useFacebookAuth, "Facebook Authentication")) {
GUILayout.Box ("difjdijsojf");
GUILayout.BeginHorizontal ();
{
GUILayout.Label ("Redirection URL : ");
GUILayout.TextField ("", GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal ();
}
GUILayout.Label ("CloudBread 로그인 서비스");
GUILayout.Label ("");
}
GUILayout.EndVertical ();
}
}
}
| using UnityEngine;
using UnityEditor;
using System.Collections;
namespace CloudBread
{
public class CBAuthEditor : EditorWindow
{
static CBAuthEditor _instance = null;
[MenuItem("CloudBread/CB-Authentication")]
public static void InitWindow()
{
if (null == _instance)
{
_instance = GetWindow<CBAuthEditor>();
}
else
{
_instance.Close();
}
}
bool _useFacebookAuth = true;
bool _useGoogleAuth = false;
void OnGUI()
{
GUILayout.BeginVertical ();
{
// GUILayout.Box("CloudBread Login Service - OAuth 2.0", "IN BigTitle");
// GUILayout.Label("");
GUILayout.Label ("CloudBread Login Service - OAuth 2.0");
GUILayout.Box ("To configure CloudBread Login Service in this Project,\n" +
"you can get more information in our Project Sites", "IN Title");
GUILayout.Label ("CloudBread 로그인 서비스를 설정하려면, 아래 프로젝트 사이트를 참조하세요.");
if (GUILayout.Button("OpenSource Project - CloudBread.", GUI.skin.box))
{
Application.OpenURL("https://github.com/CloudBreadProject/");
}
if (GUILayout.Toggle (_useFacebookAuth, "Facebook Authentication")) {
GUILayout.Box ("difjdijsojf");
GUILayout.BeginHorizontal ();
{
GUILayout.Label ("Redirection URL : ");
GUILayout.TextField ("", GUILayout.ExpandWidth(true));
}
GUILayout.EndHorizontal ();
}
}
GUILayout.EndVertical ();
}
}
}
| mit | C# |
3cf162f6f047ef0e8c731d6297a7e3d71f6304f8 | Switch Collapse function to correctly call the Collapse function of the expand pattern | Roemer/FlaUI | src/FlaUI.Core/AutomationElements/PatternElements/ExpandCollapseAutomationElement.cs | src/FlaUI.Core/AutomationElements/PatternElements/ExpandCollapseAutomationElement.cs | using FlaUI.Core.Definitions;
using FlaUI.Core.Patterns;
namespace FlaUI.Core.AutomationElements.PatternElements
{
/// <summary>
/// An element that supports the <see cref="IExpandCollapsePattern"/>.
/// </summary>
public class ExpandCollapseAutomationElement : AutomationElement
{
public ExpandCollapseAutomationElement(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement)
{
}
public IExpandCollapsePattern ExpandCollapsePattern => Patterns.ExpandCollapse.Pattern;
/// <summary>
/// Gets the current expand / collapse state.
/// </summary>
public ExpandCollapseState ExpandCollapseState => ExpandCollapsePattern.ExpandCollapseState;
/// <summary>
/// Expands the element.
/// </summary>
public void Expand()
{
ExpandCollapsePattern.Expand();
}
/// <summary>
/// Collapses the element.
/// </summary>
public void Collapse()
{
ExpandCollapsePattern.Collapse();
}
}
}
| using FlaUI.Core.Definitions;
using FlaUI.Core.Patterns;
namespace FlaUI.Core.AutomationElements.PatternElements
{
/// <summary>
/// An element that supports the <see cref="IExpandCollapsePattern"/>.
/// </summary>
public class ExpandCollapseAutomationElement : AutomationElement
{
public ExpandCollapseAutomationElement(FrameworkAutomationElementBase frameworkAutomationElement) : base(frameworkAutomationElement)
{
}
public IExpandCollapsePattern ExpandCollapsePattern => Patterns.ExpandCollapse.Pattern;
/// <summary>
/// Gets the current expand / collapse state.
/// </summary>
public ExpandCollapseState ExpandCollapseState => ExpandCollapsePattern.ExpandCollapseState;
/// <summary>
/// Expands the element.
/// </summary>
public void Expand()
{
ExpandCollapsePattern.Expand();
}
/// <summary>
/// Collapses the element.
/// </summary>
public void Collapse()
{
ExpandCollapsePattern.Expand();
}
}
}
| mit | C# |
2194c5305219940976d6035d0f2e6c17f462a7c7 | fix color conversions | RPCS3/discord-bot | CompatBot/Utils/Extensions/Converters.cs | CompatBot/Utils/Extensions/Converters.cs | using System;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.ColorSpaces;
using SixLabors.ImageSharp.ColorSpaces.Conversion;
using SixLabors.ImageSharp.PixelFormats;
namespace CompatBot.Utils.Extensions
{
internal static class Converters
{
private static readonly ColorSpaceConverter colorSpaceConverter = new ColorSpaceConverter();
public static Color ToStandardColor(this ColorThiefDotNet.Color c)
=> new Rgba32(c.R, c.G, c.B, c.A);
public static Color GetComplementary(this Color src, bool preserveOpacity = false)
{
var c = src.ToPixel<Rgba32>();
var a = c.A;
//if RGB values are close to each other by a diff less than 10%, then if RGB values are lighter side,
//decrease the blue by 50% (eventually it will increase in conversion below),
//if RBB values are on darker side, decrease yellow by about 50% (it will increase in conversion)
var avgColorValue = (c.R + c.G + c.B) / 3.0;
var dR = Math.Abs(c.R - avgColorValue);
var dG = Math.Abs(c.G - avgColorValue);
var dB = Math.Abs(c.B - avgColorValue);
if (dR < 20 && dG < 20 && dB < 20) //The color is a shade of gray
{
if (avgColorValue < 123) //color is dark
c = new Rgba32(220, 230, 50, a);
else
c = new Rgba32(255, 255, 50, a);
}
if (!preserveOpacity)
a = Math.Max(a, (byte)127); //We don't want contrast color to be more than 50% transparent ever.
var hsb = colorSpaceConverter.ToHsv(new Rgb24(c.R, c.G, c.B));
var h = hsb.H;
h = h < 180 ? h + 180 : h - 180;
var r = colorSpaceConverter.ToRgb(new Hsv(h, hsb.S, hsb.V));
return new Rgba32(r.R, r.G, r.B, a);
}
}
} | using System;
using CompatApiClient.Utils;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.ColorSpaces;
using SixLabors.ImageSharp.ColorSpaces.Conversion;
using SixLabors.ImageSharp.PixelFormats;
namespace CompatBot.Utils.Extensions
{
internal static class Converters
{
private static readonly ColorSpaceConverter colorSpaceConverter = new ColorSpaceConverter();
public static Color ToStandardColor(this ColorThiefDotNet.Color c)
=> new Argb32(c.R, c.G, c.B, c.A);
public static Color GetComplementary(this Color src, bool preserveOpacity = false)
{
var c = src.ToPixel<Argb32>();
var a = c.A;
//if RGB values are close to each other by a diff less than 10%, then if RGB values are lighter side, decrease the blue by 50% (eventually it will increase in conversion below), if RBB values are on darker side, decrease yellow by about 50% (it will increase in conversion)
var avgColorValue = (c.R + c.G + c.B) / 3.0;
var dR = Math.Abs(c.R - avgColorValue);
var dG = Math.Abs(c.G - avgColorValue);
var dB = Math.Abs(c.B - avgColorValue);
if (dR < 20 && dG < 20 && dB < 20) //The color is a shade of gray
{
if (avgColorValue < 123) //color is dark
c = new Argb32(a, 220, 230, 50);
else
c = new Argb32(a, 255, 255, 50);
}
if (!preserveOpacity)
a = Math.Max(a, (byte)127); //We don't want contrast color to be more than 50% transparent ever.
var hsb = colorSpaceConverter.ToHsv(new Rgb24(c.R, c.G, c.B));
var h = hsb.H;
h = h < 180 ? h + 180 : h - 180;
var r = colorSpaceConverter.ToRgb(new Hsv(h, hsb.S, hsb.V));
return new Argb32(a, r.R, r.G, r.B);
}
}
} | lgpl-2.1 | C# |
1977536b25f76fe2fe739332dd05672f80877540 | Fix namespace ordering in WebApi Program.cs | lambdakris/templating,rschiefer/templating,danroth27/templating,seancpeters/templating,lambdakris/templating,rschiefer/templating,seancpeters/templating,mlorbetske/templating,danroth27/templating,danroth27/templating,seancpeters/templating,lambdakris/templating,mlorbetske/templating,seancpeters/templating,rschiefer/templating | template_feed/Microsoft.DotNet.Web.ProjectTemplates/content/WebApi-CSharp/Program.cs | template_feed/Microsoft.DotNet.Web.ProjectTemplates/content/WebApi-CSharp/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| mit | C# |
421df8ea950e57f162264a427c95e5f3a81a2079 | Add Flaky to list of test constants | AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell | src/ResourceManager/Common/Commands.ScenarioTests.ResourceManager.Common/Constants.cs | src/ResourceManager/Common/Commands.ScenarioTests.ResourceManager.Common/Constants.cs |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.ScenarioTest
{
public class Category
{
// Service
public const string Service = "Service";
public const string All = "All";
public const string Automation = "Automation";
public const string ServiceBus = "ServiceBus";
public const string CloudService = "CloudService";
public const string Management = "Management";
public const string MediaServices = "MediaServices";
public const string Websites = "Websites";
public const string Storage = "Storage";
public const string Store = "Store";
public const string Sql = "Sql";
public const string ServiceManagement = "ServiceManagement";
public const string Resources = "Resources";
public const string Tags = "Tags";
public const string TrafficManager = "TrafficManager";
public const string Scheduler = "Scheduler";
public const string KeyVault = "KeyVault";
public const string Network = "Network";
// Owners
public const string OneSDK = "OneSDK";
// Acceptance type
public const string AcceptanceType = "AcceptanceType";
public const string CIT = "CIT";
public const string BVT = "BVT";
public const string CheckIn = "CheckIn";
public const string Flaky = "Flaky";
// Run Type
public const string RunType = "RunType";
public const string LiveOnly = "LiveOnly";
//Uncomment when we need to tag on only run under mock
//public const string MockedOnly = "MockedOnly";
// Environment
public const string Environment = "Environment";
public const string WAPack = "WAPack";
}
public class Variables
{
public const string SubscriptionId = "SubscriptionId";
public const string Username = "Username";
public const string Tenantd = "Tenantd";
}
}
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.ScenarioTest
{
public class Category
{
// Service
public const string Service = "Service";
public const string All = "All";
public const string Automation = "Automation";
public const string ServiceBus = "ServiceBus";
public const string CloudService = "CloudService";
public const string Management = "Management";
public const string MediaServices = "MediaServices";
public const string Websites = "Websites";
public const string Storage = "Storage";
public const string Store = "Store";
public const string Sql = "Sql";
public const string ServiceManagement = "ServiceManagement";
public const string Resources = "Resources";
public const string Tags = "Tags";
public const string TrafficManager = "TrafficManager";
public const string Scheduler = "Scheduler";
public const string KeyVault = "KeyVault";
public const string Network = "Network";
// Owners
public const string OneSDK = "OneSDK";
// Acceptance type
public const string AcceptanceType = "AcceptanceType";
public const string CIT = "CIT";
public const string BVT = "BVT";
public const string CheckIn = "CheckIn";
// Run Type
public const string RunType = "RunType";
public const string LiveOnly = "LiveOnly";
//Uncomment when we need to tag on only run under mock
//public const string MockedOnly = "MockedOnly";
// Environment
public const string Environment = "Environment";
public const string WAPack = "WAPack";
}
public class Variables
{
public const string SubscriptionId = "SubscriptionId";
public const string Username = "Username";
public const string Tenantd = "Tenantd";
}
}
| apache-2.0 | C# |
4f5dad568f0465c5faf7d71ac36d595bef079fdc | add new message | toannvqo/dnn_publish | GitDemo/GitDemo/Program.cs | GitDemo/GitDemo/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GitDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello world world world!");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GitDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hello world!");
}
}
}
| mit | C# |
7de0cfdee55bc3ccfbfb1e0898b444e2f5c0ce04 | Add EmptyIfNull and WhereNotNull | SaberSnail/GoldenAnvil.Utility | GoldenAnvil.Utility/EnumerableUtility.cs | GoldenAnvil.Utility/EnumerableUtility.cs | using System.Collections.Generic;
using System.Linq;
namespace GoldenAnvil.Utility
{
public static class EnumerableUtility
{
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
{
return new HashSet<T>(items);
}
public static IEnumerable<T> Append<T>(this IEnumerable<T> items, T value)
{
foreach (T item in items)
yield return item;
yield return value;
}
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items)
{
return items ?? Enumerable.Empty<T>();
}
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items)
{
return items.Where(x => x != null);
}
}
}
| using System.Collections.Generic;
namespace GoldenAnvil.Utility
{
public static class EnumerableUtility
{
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T value)
{
foreach (T item in source)
yield return item;
yield return value;
}
}
}
| mit | C# |
e3d42226575e2a544fb77d7c85d08ee7dfdd1ee6 | add width and height to constructor | Kentico/Deliver-.NET-SDK,Kentico/delivery-sdk-net | Kentico.Kontent.Delivery/Models/Asset.cs | Kentico.Kontent.Delivery/Models/Asset.cs | using Newtonsoft.Json;
namespace Kentico.Kontent.Delivery
{
/// <summary>
/// Represents a digital asset, such as a document or image.
/// </summary>
public sealed class Asset
{
/// <summary>
/// Gets the name of the asset.
/// </summary>
[JsonProperty("name")]
public string Name { get; }
/// <summary>
/// Gets the description of the asset.
/// </summary>
[JsonProperty("description")]
public string Description { get; }
/// <summary>
/// Gets the media type of the asset, for example "image/jpeg".
/// </summary>
[JsonProperty("type")]
public string Type { get; }
/// <summary>
/// Gets the asset size in bytes.
/// </summary>
[JsonProperty("size")]
public int Size { get; }
/// <summary>
/// Gets the URL of the asset.
/// </summary>
[JsonProperty("url")]
public string Url { get; }
/// <summary>
/// Gets the width of the asset
/// </summary>
[JsonProperty("width")]
public int Width { get; set; }
/// <summary>
/// Gets the height of the asset
/// </summary>
[JsonProperty("height")]
public int Height { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Asset"/> class.
/// </summary>
[JsonConstructor]
internal Asset(string name, string type, int size, string url, string description, int width, int height)
{
Name = name;
Type = type;
Size = size;
Url = url;
Description = description;
Width = width;
Height = height;
}
}
}
| using Newtonsoft.Json;
namespace Kentico.Kontent.Delivery
{
/// <summary>
/// Represents a digital asset, such as a document or image.
/// </summary>
public sealed class Asset
{
/// <summary>
/// Gets the name of the asset.
/// </summary>
[JsonProperty("name")]
public string Name { get; }
/// <summary>
/// Gets the description of the asset.
/// </summary>
[JsonProperty("description")]
public string Description { get; }
/// <summary>
/// Gets the media type of the asset, for example "image/jpeg".
/// </summary>
[JsonProperty("type")]
public string Type { get; }
/// <summary>
/// Gets the asset size in bytes.
/// </summary>
[JsonProperty("size")]
public int Size { get; }
/// <summary>
/// Gets the URL of the asset.
/// </summary>
[JsonProperty("url")]
public string Url { get; }
/// <summary>
/// Gets the width of the asset
/// </summary>
[JsonProperty("width")]
public int Width { get; set; }
/// <summary>
/// Gets the height of the asset
/// </summary>
[JsonProperty("height")]
public int Height { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Asset"/> class.
/// </summary>
[JsonConstructor]
internal Asset(string name, string type, int size, string url, string description)
{
Name = name;
Type = type;
Size = size;
Url = url;
Description = description;
}
}
}
| mit | C# |
5ccdb70c6d9c69ab828860cd78fbfd994f3b5fec | Remove unused member | oliver-feng/kudu,dev-enthusiast/kudu,chrisrpatterson/kudu,duncansmart/kudu,chrisrpatterson/kudu,dev-enthusiast/kudu,juoni/kudu,bbauya/kudu,mauricionr/kudu,YOTOV-LIMITED/kudu,juvchan/kudu,MavenRain/kudu,shibayan/kudu,oliver-feng/kudu,bbauya/kudu,WeAreMammoth/kudu-obsolete,juvchan/kudu,juoni/kudu,barnyp/kudu,shanselman/kudu,badescuga/kudu,MavenRain/kudu,oliver-feng/kudu,EricSten-MSFT/kudu,oliver-feng/kudu,shibayan/kudu,kenegozi/kudu,MavenRain/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,projectkudu/kudu,badescuga/kudu,sitereactor/kudu,MavenRain/kudu,uQr/kudu,kali786516/kudu,dev-enthusiast/kudu,shrimpy/kudu,projectkudu/kudu,chrisrpatterson/kudu,WeAreMammoth/kudu-obsolete,shibayan/kudu,juvchan/kudu,kali786516/kudu,shrimpy/kudu,shibayan/kudu,shibayan/kudu,juoni/kudu,EricSten-MSFT/kudu,YOTOV-LIMITED/kudu,mauricionr/kudu,projectkudu/kudu,kali786516/kudu,juvchan/kudu,shrimpy/kudu,puneet-gupta/kudu,projectkudu/kudu,uQr/kudu,EricSten-MSFT/kudu,juvchan/kudu,duncansmart/kudu,bbauya/kudu,barnyp/kudu,sitereactor/kudu,sitereactor/kudu,EricSten-MSFT/kudu,kenegozi/kudu,puneet-gupta/kudu,duncansmart/kudu,projectkudu/kudu,shrimpy/kudu,duncansmart/kudu,shanselman/kudu,sitereactor/kudu,badescuga/kudu,puneet-gupta/kudu,badescuga/kudu,kali786516/kudu,dev-enthusiast/kudu,puneet-gupta/kudu,sitereactor/kudu,barnyp/kudu,kenegozi/kudu,WeAreMammoth/kudu-obsolete,mauricionr/kudu,puneet-gupta/kudu,barnyp/kudu,bbauya/kudu,uQr/kudu,YOTOV-LIMITED/kudu,chrisrpatterson/kudu,mauricionr/kudu,juoni/kudu,kenegozi/kudu,EricSten-MSFT/kudu,uQr/kudu,shanselman/kudu | Kudu.Core/Deployment/DeploymentHelper.cs | Kudu.Core/Deployment/DeploymentHelper.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Kudu.Core.Infrastructure;
using Kudu.Core.SourceControl;
namespace Kudu.Core.Deployment
{
public static class DeploymentHelper
{
private static readonly string[] _projectFileExtensions = new[] { ".csproj", ".vbproj" };
private static readonly string[] _projectFileLookup = _projectFileExtensions.Select(p => "*" + p).ToArray();
public static IList<string> GetProjects(string path, IFileFinder fileFinder, SearchOption searchOption = SearchOption.AllDirectories)
{
IEnumerable<string> filesList = fileFinder.ListFiles(path, searchOption, _projectFileLookup);
return filesList.ToList();
}
public static bool IsProject(string path)
{
return _projectFileExtensions.Any(extension => path.EndsWith(extension, StringComparison.OrdinalIgnoreCase));
}
public static bool IsDeployableProject(string path)
{
return IsProject(path) && VsHelper.IsWap(path);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Kudu.Core.Infrastructure;
using Kudu.Core.SourceControl;
namespace Kudu.Core.Deployment
{
public static class DeploymentHelper
{
private static readonly string[] _projectFileExtensions = new[] { ".csproj", ".vbproj" };
private static readonly string[] _projectFileLookup = _projectFileExtensions.Select(p => "*" + p).ToArray();
private static readonly List<string> _emptyList = Enumerable.Empty<string>().ToList();
public static IList<string> GetProjects(string path, IFileFinder fileFinder, SearchOption searchOption = SearchOption.AllDirectories)
{
IEnumerable<string> filesList = fileFinder.ListFiles(path, searchOption, _projectFileLookup);
return filesList.ToList();
}
public static bool IsProject(string path)
{
return _projectFileExtensions.Any(extension => path.EndsWith(extension, StringComparison.OrdinalIgnoreCase));
}
public static bool IsDeployableProject(string path)
{
return IsProject(path) && VsHelper.IsWap(path);
}
}
}
| apache-2.0 | C# |
519e08c1c6d8777a1519a488cfb3e41d82b9d815 | Create Extension.cs | fengdingfeilong/MicroRPC | MicroRPC.Core/Extension.cs | MicroRPC.Core/Extension.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MicroRPC.Core
{
public static class Extension
{
/// <summary>
/// Test whether the socket is connected or not, find detail in msdn Socket.Connected
/// </summary>
public static bool IsConnected(this Socket socket)
{
bool blockingState = socket.Blocking;
try
{
byte[] tmp = new byte[1];
socket.Blocking = false;
socket.Send(tmp, 0, 0);
}
catch (SocketException e)
{
if (e.NativeErrorCode.Equals(10035))// 10035 == WSAEWOULDBLOCK
Console.WriteLine("Still Connected, but the Send would block");
else
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
}
finally
{
try
{
socket.Blocking = blockingState;
}
catch
{ }
}
return socket.Connected;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace MicroRPC.Core
{
public static class Extension
{
/// <summary>
/// Test whether the socket is connected or not, find detail in msdn Socket.Connected
/// </summary>
public static bool IsConnected(this Socket socket)
{
bool blockingState = socket.Blocking;
try
{
byte[] tmp = new byte[1];
socket.Blocking = false;
socket.Send(tmp, 0, 0);
}
catch (SocketException e)
{
if (e.NativeErrorCode.Equals(10035))// 10035 == WSAEWOULDBLOCK
Console.WriteLine("Still Connected, but the Send would block");
else
Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
}
finally
{
socket.Blocking = blockingState;
}
return socket.Connected;
}
}
}
| mit | C# |
3ad10ec2cc94751dd323aba665a9f633fc8f685c | Fix tag line for Telegram | dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua | src/Core/Services/Crosspost/TelegramCrosspostService.cs | src/Core/Services/Crosspost/TelegramCrosspostService.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Core.Logging;
using DAL;
using Serilog.Events;
using Telegram.Bot;
namespace Core.Services.Crosspost
{
public class TelegramCrosspostService : ICrossPostService
{
private readonly Core.Logging.ILogger _logger;
private readonly string _token;
private readonly string _name;
public TelegramCrosspostService(string token, string name, ILogger logger)
{
_logger = logger;
_token = token;
_name = name;
}
public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags)
{
var sb = new StringBuilder();
sb.Append(message);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(link);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(string.Join(" ", tags));
try
{
var bot = new TelegramBotClient(_token);
await bot.SendTextMessageAsync(_name, sb.ToString());
_logger.Write(LogEventLevel.Information, $"Message was sent to Telegram channel `{_name}`: `{sb}`");
}
catch (Exception ex)
{
_logger.Write(LogEventLevel.Error, $"Error during send message to Telegram: `{sb}`", ex);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Core.Logging;
using DAL;
using Serilog.Events;
using Telegram.Bot;
namespace Core.Services.Crosspost
{
public class TelegramCrosspostService : ICrossPostService
{
private readonly Core.Logging.ILogger _logger;
private readonly string _token;
private readonly string _name;
public TelegramCrosspostService(string token, string name, ILogger logger)
{
_logger = logger;
_token = token;
_name = name;
}
public async Task Send(string message, Uri link, IReadOnlyCollection<string> tags)
{
var sb = new StringBuilder();
sb.Append(message);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(link);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(string.Join(", ", tags));
try
{
var bot = new TelegramBotClient(_token);
await bot.SendTextMessageAsync(_name, sb.ToString());
_logger.Write(LogEventLevel.Information, $"Message was sent to Telegram channel `{_name}`: `{sb}`");
}
catch (Exception ex)
{
_logger.Write(LogEventLevel.Error, $"Error during send message to Telegram: `{sb}`", ex);
}
}
}
} | mit | C# |
9e80cb5a7145a9473dc8a095eaec031822f701fe | Fix http logging log typo (#36871) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Middleware/HttpLogging/src/HttpLoggingExtensions.cs | src/Middleware/HttpLogging/src/HttpLoggingExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.HttpLogging
{
internal static partial class HttpLoggingExtensions
{
public static void RequestLog(this ILogger logger, HttpRequestLog requestLog) => logger.Log(
LogLevel.Information,
new EventId(1, "RequestLogLog"),
requestLog,
exception: null,
formatter: HttpRequestLog.Callback);
public static void ResponseLog(this ILogger logger, HttpResponseLog responseLog) => logger.Log(
LogLevel.Information,
new EventId(2, "ResponseLog"),
responseLog,
exception: null,
formatter: HttpResponseLog.Callback);
[LoggerMessage(3, LogLevel.Information, "RequestBody: {Body}", EventName = "RequestBody")]
public static partial void RequestBody(this ILogger logger, string body);
[LoggerMessage(4, LogLevel.Information, "ResponseBody: {Body}", EventName = "ResponseBody")]
public static partial void ResponseBody(this ILogger logger, string body);
[LoggerMessage(5, LogLevel.Debug, "Decode failure while converting body.", EventName = "DecodeFailure")]
public static partial void DecodeFailure(this ILogger logger, Exception ex);
[LoggerMessage(6, LogLevel.Debug, "Unrecognized Content-Type for body.", EventName = "UnrecognizedMediaType")]
public static partial void UnrecognizedMediaType(this ILogger logger);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.HttpLogging
{
internal static partial class HttpLoggingExtensions
{
public static void RequestLog(this ILogger logger, HttpRequestLog requestLog) => logger.Log(
LogLevel.Information,
new EventId(1, "RequestLogLog"),
requestLog,
exception: null,
formatter: HttpRequestLog.Callback);
public static void ResponseLog(this ILogger logger, HttpResponseLog responseLog) => logger.Log(
LogLevel.Information,
new EventId(2, "ResponseLog"),
responseLog,
exception: null,
formatter: HttpResponseLog.Callback);
[LoggerMessage(3, LogLevel.Information, "RequestBody: {Body}", EventName = "RequestBody")]
public static partial void RequestBody(this ILogger logger, string body);
[LoggerMessage(4, LogLevel.Information, "ResponseBody: {Body}", EventName = "ResponseBody")]
public static partial void ResponseBody(this ILogger logger, string body);
[LoggerMessage(5, LogLevel.Debug, "Decode failure while converting body.", EventName = "DecodeFaulure")]
public static partial void DecodeFailure(this ILogger logger, Exception ex);
[LoggerMessage(6, LogLevel.Debug, "Unrecognized Content-Type for body.", EventName = "UnrecognizedMediaType")]
public static partial void UnrecognizedMediaType(this ILogger logger);
}
}
| apache-2.0 | C# |
2eb024d0ce5c911e85d3e4093d6ffaaa002277a1 | Update version numbers to 1.2.0 | CamTechConsultants/CvsntGitImporter | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CvsntGitImporter")]
[assembly: AssemblyDescription("CVSNT to Git Importer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Cambridge Technology Consultants")]
[assembly: AssemblyProduct("CvsntGitImporter")]
[assembly: AssemblyCopyright("Copyright © 2013 Cambridge Technology Consultants Ltd.")]
[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("ec661d49-de7f-45ce-85a6-e1b2319499f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: InternalsVisibleTo("CvsntGitImporterTest")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] | 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("CvsntGitImporter")]
[assembly: AssemblyDescription("CVSNT to Git Importer")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Cambridge Technology Consultants")]
[assembly: AssemblyProduct("CvsntGitImporter")]
[assembly: AssemblyCopyright("Copyright © 2013 Cambridge Technology Consultants Ltd.")]
[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("ec661d49-de7f-45ce-85a6-e1b2319499f4")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: InternalsVisibleTo("CvsntGitImporterTest")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] | mit | C# |
c27a0cbb6fdda17cf9c49acc56a724b120fd9528 | Fix incorrect project path resolver | DustinCampbell/omnisharp-roslyn,jtbm37/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,jtbm37/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,nabychan/omnisharp-roslyn,nabychan/omnisharp-roslyn,OmniSharp/omnisharp-roslyn | src/OmniSharp.DotNetTest/Helpers/ProjectPathResolver.cs | src/OmniSharp.DotNetTest/Helpers/ProjectPathResolver.cs | using System.IO;
namespace OmniSharp.DotNetTest.Helpers
{
internal class ProjectPathResolver
{
public static string GetProjectPathFromFile(string filepath)
{
// TODO: revisit this logic, too clumsy
var projectFolder = Path.GetDirectoryName(filepath);
while (!File.Exists(Path.Combine(projectFolder, "project.json")))
{
var parent = Path.GetDirectoryName(projectFolder);
if (parent == projectFolder)
{
break;
}
else
{
projectFolder = parent;
}
}
return projectFolder;
}
}
}
| using System.IO;
namespace OmniSharp.DotNetTest.Helpers
{
internal class ProjectPathResolver
{
public static string GetProjectPathFromFile(string filepath)
{
// TODO: revisit this logic, too clumsy
var projectFolder = Path.GetDirectoryName(filepath);
while (!File.Exists(Path.Combine(projectFolder, "project.json")))
{
var parent = Path.GetDirectoryName(filepath);
if (parent == projectFolder)
{
break;
}
else
{
projectFolder = parent;
}
}
return projectFolder;
}
}
}
| mit | C# |
788f8c6ab32401a069648b4ccdc998bd82ca4d95 | Undo breaking change | abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/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>
[Obsolete("Will no longer be required with the new backoffice API")]
[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>
[Obsolete("Will no longer be required with the new backoffice API")]
[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# |
81319ac9588af2cbdc4f9decaf7a21f4e8f21e2e | fix statistic method | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date.Website/Controllers/PublicHolidayApiController.cs | Src/Nager.Date.Website/Controllers/PublicHolidayApiController.cs | using Nager.Date.Website.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
namespace Nager.Date.Website.Controllers
{
[RoutePrefix("api/v1")]
public class PublicHolidayApiController : ApiController
{
private static ConcurrentDictionary<string, int> ApiStatistic = new ConcurrentDictionary<string, int>();
[HttpGet]
[Route("statistic")]
public KeyValuePair<string, int>[] Statistic()
{
return ApiStatistic.Select(o => new KeyValuePair<string, int>(o.Key, o.Value)).ToArray();
}
[HttpGet]
[Route("get/{countrycode}/{year}")]
public IEnumerable<PublicHoliday> CountryJson(string countrycode, int year)
{
var ipAddress = HttpContext.Current.Request.UserHostAddress;
ApiStatistic.AddOrUpdate(ipAddress, 1, (s, i) => i + 1);
CountryCode countryCode;
if (!Enum.TryParse(countrycode, true, out countryCode))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var publicHolidays = DateSystem.GetPublicHoliday(countryCode, year);
if (publicHolidays?.Count() > 0)
{
var items = publicHolidays.Select(o => new PublicHoliday(o));
return items;
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
}
| using Nager.Date.Website.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
namespace Nager.Date.Website.Controllers
{
[RoutePrefix("api/v1")]
public class PublicHolidayApiController : ApiController
{
private static ConcurrentDictionary<string, int> ApiStatistic = new ConcurrentDictionary<string, int>();
[HttpGet]
[Route("statistic")]
public KeyValuePair<string, int>[] Statistic()
{
return ApiStatistic.Select(o => new KeyValuePair<string, int>(o.Key, o.Value)).ToArray();
}
[HttpGet]
[Route("get/{countrycode}/{year}")]
public IEnumerable<PublicHoliday> CountryJson(string countrycode, int year)
{
var ipAddress = HttpContext.Current.Request.UserHostAddress;
ApiStatistic.AddOrUpdate(ipAddress, 1, (s, i) => i++);
CountryCode countryCode;
if (!Enum.TryParse(countrycode, true, out countryCode))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
var publicHolidays = DateSystem.GetPublicHoliday(countryCode, year);
if (publicHolidays?.Count() > 0)
{
var items = publicHolidays.Select(o => new PublicHoliday(o));
return items;
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
}
| mit | C# |
a5f9f8c7e4812ec91922cd1e5834aaba0fa0691b | Remove duplicates from Endpoint mappings. | machine/machine,machine/machine | Source/Extensions/Machine.MassTransitExtensions/MessageEndpointLookup.cs | Source/Extensions/Machine.MassTransitExtensions/MessageEndpointLookup.cs | using System;
using System.Collections.Generic;
using System.Reflection;
namespace Machine.MassTransitExtensions
{
public class MessageEndpointLookup : IMessageEndpointLookup
{
private readonly Dictionary<Type, List<EndpointName>> _map = new Dictionary<Type, List<EndpointName>>();
private readonly List<EndpointName> _catchAlls = new List<EndpointName>();
public ICollection<EndpointName> LookupEndpointFor(Type messageType)
{
List<EndpointName> destinations = new List<EndpointName>(_catchAlls);
if (_map.ContainsKey(messageType))
{
foreach (EndpointName endpointName in destinations)
{
if (!destinations.Contains(endpointName))
{
destinations.Add(endpointName);
}
}
}
if (destinations.Count == 0)
{
throw new InvalidOperationException("No endpoints for: " + messageType);
}
return destinations;
}
public void SendMessageTypeTo(Type messageType, EndpointName destination)
{
if (!_map.ContainsKey(messageType))
{
_map[messageType] = new List<EndpointName>();
}
if (!_map[messageType].Contains(destination))
{
_map[messageType].Add(destination);
}
}
public void SendMessageTypeTo<T>(EndpointName destination)
{
SendMessageTypeTo(typeof(T), destination);
}
public void SendAllFromAssemblyTo<T>(Assembly assembly, EndpointName destination)
{
foreach (Type type in assembly.GetTypes())
{
if (typeof(T).IsAssignableFrom(type))
{
SendMessageTypeTo(type, destination);
}
}
}
public void SendAllTo(EndpointName destination)
{
if (!_catchAlls.Contains(destination))
{
_catchAlls.Add(destination);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Reflection;
namespace Machine.MassTransitExtensions
{
public class MessageEndpointLookup : IMessageEndpointLookup
{
private readonly Dictionary<Type, List<EndpointName>> _map = new Dictionary<Type, List<EndpointName>>();
private readonly List<EndpointName> _catchAlls = new List<EndpointName>();
public ICollection<EndpointName> LookupEndpointFor(Type messageType)
{
List<EndpointName> destinations = new List<EndpointName>(_catchAlls);
if (_map.ContainsKey(messageType))
{
destinations.AddRange(_map[messageType]);
}
if (destinations.Count == 0)
{
throw new InvalidOperationException("No endpoints for: " + messageType);
}
return destinations;
}
public void SendMessageTypeTo(Type messageType, EndpointName destination)
{
if (!_map.ContainsKey(messageType))
{
_map[messageType] = new List<EndpointName>();
}
_map[messageType].Add(destination);
}
public void SendMessageTypeTo<T>(EndpointName destination)
{
SendMessageTypeTo(typeof(T), destination);
}
public void SendAllFromAssemblyTo<T>(Assembly assembly, EndpointName destination)
{
foreach (Type type in assembly.GetTypes())
{
if (typeof(T).IsAssignableFrom(type))
{
SendMessageTypeTo(type, destination);
}
}
}
public void SendAllTo(EndpointName destination)
{
_catchAlls.Add(destination);
}
}
} | mit | C# |
322812e5afd0e983ae57988e9b217f6fa69971e1 | Add cache for DotNetBuild #26 | Julien-Mialon/Cake.Storm,Julien-Mialon/Cake.Storm | fluent/src/Cake.Storm.Fluent.DotNetCore/Steps/DotNetBuildStep.cs | fluent/src/Cake.Storm.Fluent.DotNetCore/Steps/DotNetBuildStep.cs | using System.Linq;
using System.Text;
using Cake.Common.IO;
using Cake.Common.Tools.DotNetCore;
using Cake.Common.Tools.DotNetCore.Build;
using Cake.Core;
using Cake.Storm.Fluent.DotNetCore.InternalExtensions;
using Cake.Storm.Fluent.Interfaces;
using Cake.Storm.Fluent.InternalExtensions;
using Cake.Storm.Fluent.Steps;
namespace Cake.Storm.Fluent.DotNetCore.Steps
{
[BuildStep]
internal class DotNetBuildStep : ICacheableStep
{
public void Execute(IConfiguration configuration, StepType currentStep)
{
string solutionPath = configuration.GetSolutionPath();
if (!configuration.Context.CakeContext.FileExists(solutionPath))
{
configuration.Context.CakeContext.LogAndThrow($"Solution file {solutionPath} does not exists");
}
configuration.RunOnConfiguredTargetFramework(framework =>
{
DotNetCoreBuildSettings settings = new DotNetCoreBuildSettings
{
Framework = framework
};
configuration.ApplyBuildParameters(solutionPath, settings);
configuration.Context.CakeContext.DotNetCoreBuild(solutionPath, settings);
});
}
public string GetCacheId(IConfiguration configuration, StepType currentStep)
{
string solutionPath = configuration.GetSolutionPath();
StringBuilder builder = new StringBuilder();
builder.Append($"{solutionPath} ");
configuration.RunOnConfiguredTargetFramework(framework =>
{
builder.Append($"{framework}=(");
DotNetCoreBuildSettings settings = new DotNetCoreBuildSettings();
configuration.ApplyBuildParameters(solutionPath, settings);
builder.Append($"{settings.Configuration}_{settings.Runtime}_{settings.OutputDirectory?.FullPath}_{settings.ToolPath?.FullPath}_{settings.WorkingDirectory?.FullPath}"
+ $"{settings.MSBuildSettings.ToolVersion}_{string.Join(";", settings.MSBuildSettings.Targets)}_{string.Join(";", settings.MSBuildSettings.Properties.Select(x => $"{x.Key}={string.Join(",", x.Value)}"))}");
builder.Append(")");
});
return builder.ToString();
}
}
}
| using Cake.Common.IO;
using Cake.Common.Tools.DotNetCore;
using Cake.Common.Tools.DotNetCore.Build;
using Cake.Core;
using Cake.Storm.Fluent.DotNetCore.InternalExtensions;
using Cake.Storm.Fluent.Interfaces;
using Cake.Storm.Fluent.InternalExtensions;
using Cake.Storm.Fluent.Steps;
namespace Cake.Storm.Fluent.DotNetCore.Steps
{
[BuildStep]
internal class DotNetBuildStep : IStep
{
public void Execute(IConfiguration configuration, StepType currentStep)
{
string solutionPath = configuration.GetSolutionPath();
if (!configuration.Context.CakeContext.FileExists(solutionPath))
{
configuration.Context.CakeContext.LogAndThrow($"Solution file {solutionPath} does not exists");
}
configuration.RunOnConfiguredTargetFramework(framework =>
{
DotNetCoreBuildSettings settings = new DotNetCoreBuildSettings
{
Framework = framework
};
configuration.ApplyBuildParameters(solutionPath, settings);
configuration.Context.CakeContext.DotNetCoreBuild(solutionPath, settings);
});
}
}
}
| mit | C# |
d72c2d6b33636f1210d27af59aee2b441bbb9b1c | fix my own stupidity | FrankyBoy/ApiDoc,FrankyBoy/ApiDoc | ApiDoc/Models/Leaf.cs | ApiDoc/Models/Leaf.cs | using ApiDoc.Utility;
namespace ApiDoc.Models
{
public class Leaf : Node
{
public string HttpVerb { get; set; }
public bool RequiresAuthentication { get; set; }
public bool RequiresAuthorization { get; set; }
public string SampleRequest { get; set; }
public string SampleResponse { get; set; }
public override string Title
{
get { return string.Format("{0} ({1})", Name, HttpVerb.ToUpper()); }
}
public override string GetWikiUrlString()
{
Title.ToWikiUrlString();
}
}
} | using ApiDoc.Utility;
namespace ApiDoc.Models
{
public class Leaf : Node
{
public string HttpVerb { get; set; }
public bool RequiresAuthentication { get; set; }
public bool RequiresAuthorization { get; set; }
public string SampleRequest { get; set; }
public string SampleResponse { get; set; }
public override string Title
{
get { return string.Format("{0} ({1})", Name, HttpVerb.ToUpper()); }
}
public override string GetWikiUrlString()
{
return string.Format("{0}_({1})", Name.ToWikiUrlString(), HttpVerb.ToUpper());
}
}
} | apache-2.0 | C# |
e0fd0bd7f2a2b24ca00cf8d836b217909213c4b0 | add Test_run() | yasokada/unity-150908-udpTimeGraph | Assets/Test_weekly.cs | Assets/Test_weekly.cs | using UnityEngine;
using System.Collections;
public class Test_weekly : MonoBehaviour {
enum xscaletype {
Daily = 0,
Weekly,
Monthly,
Yearly,
};
[Range((int)xscaletype.Daily, (int)xscaletype.Yearly)]
public int xtype = 0;
void Test_addData() {
string [] dts = new string[]{
"2015/09/07 12:30",
"2015/09/08 09:30",
"2015/09/10 11:30",
"2015/09/11 13:30",
"2015/09/12 13:30",
};
System.DateTime curDt;
float yval;
int idx = 0;
foreach(var dt in dts) {
curDt = System.DateTime.Parse(dt);
yval = Random.Range(-1.0f, 1.0f);
timeGraphScript.SetXYVal(curDt, yval);
idx++;
}
}
void Test_run() {
timeGraphScript.SetXType ((int)xtype);
Test_addData ();
}
void Start () {
Test_run ();
}
void Update () {
}
}
| using UnityEngine;
using System.Collections;
public class Test_weekly : MonoBehaviour {
enum xscaletype {
Daily = 0,
Weekly,
Monthly,
Yearly,
};
[Range((int)xscaletype.Daily, (int)xscaletype.Yearly)]
public int xtype = 0;
static public void Test_addWeeklyData() {
string [] dts = new string[]{
"2015/09/07 12:30",
"2015/09/08 09:30",
"2015/09/10 11:30",
"2015/09/11 13:30",
"2015/09/12 13:30",
};
System.DateTime curDt;
float yval;
int idx = 0;
timeGraphScript.SetXType ((int)timeGraphScript.XType.Weekly);
foreach(var dt in dts) {
curDt = System.DateTime.Parse(dt);
yval = Random.Range(-1.0f, 1.0f);
timeGraphScript.SetXYVal(curDt, yval);
idx++;
}
}
void Start () {
Test_addWeeklyData ();
}
void Update () {
}
}
| mit | C# |
2b1c5b2c4a11ffbafbf3fb0361647527de2baaac | Fix test failure due to triangle skin no longer being null intests | peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu | osu.Game.Tests/Visual/Gameplay/SkinnableHUDComponentTestScene.cs | osu.Game.Tests/Visual/Gameplay/SkinnableHUDComponentTestScene.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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
using osu.Game.Skinning;
namespace osu.Game.Tests.Visual.Gameplay
{
public abstract class SkinnableHUDComponentTestScene : SkinnableTestScene
{
protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();
[SetUp]
public void SetUp() => Schedule(() =>
{
SetContents(skin =>
{
var implementation = skin is not TrianglesSkin
? CreateLegacyImplementation()
: CreateDefaultImplementation();
implementation.Anchor = Anchor.Centre;
implementation.Origin = Anchor.Centre;
return implementation;
});
});
protected abstract Drawable CreateDefaultImplementation();
protected abstract Drawable CreateLegacyImplementation();
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu;
namespace osu.Game.Tests.Visual.Gameplay
{
public abstract class SkinnableHUDComponentTestScene : SkinnableTestScene
{
protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset();
[SetUp]
public void SetUp() => Schedule(() =>
{
SetContents(skin =>
{
var implementation = skin != null
? CreateLegacyImplementation()
: CreateDefaultImplementation();
implementation.Anchor = Anchor.Centre;
implementation.Origin = Anchor.Centre;
return implementation;
});
});
protected abstract Drawable CreateDefaultImplementation();
protected abstract Drawable CreateLegacyImplementation();
}
}
| mit | C# |
44212f6b534f75cb4ad937dde474652a72454902 | Revert "the wrong id was used for getting the correct destination url." | tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,rasmuseeg/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS | src/Umbraco.Web/Models/Mapping/RedirectUrlMapperProfile.cs | src/Umbraco.Web/Models/Mapping/RedirectUrlMapperProfile.cs | using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Routing;
namespace Umbraco.Web.Models.Mapping
{
internal class RedirectUrlMapperProfile : Profile
{
public RedirectUrlMapperProfile(IUmbracoContextAccessor umbracoContextAccessor)
{
CreateMap<IRedirectUrl, ContentRedirectUrl>()
.ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url, item.Culture)))
.ForMember(x => x.DestinationUrl, expression => expression.MapFrom(item => item.ContentId > 0 ? GetUrl(umbracoContextAccessor, item) : "#"))
.ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key));
}
private static string GetUrl(IUmbracoContextAccessor umbracoContextAccessor, IRedirectUrl item) => umbracoContextAccessor?.UmbracoContext?.UrlProvider?.GetUrl(item.Id, item.Culture);
}
}
| using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Composing;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Routing;
namespace Umbraco.Web.Models.Mapping
{
internal class RedirectUrlMapperProfile : Profile
{
public RedirectUrlMapperProfile(IUmbracoContextAccessor umbracoContextAccessor)
{
CreateMap<IRedirectUrl, ContentRedirectUrl>()
.ForMember(x => x.OriginalUrl, expression => expression.MapFrom(item => Current.UmbracoContext.UrlProvider.GetUrlFromRoute(item.ContentId, item.Url, item.Culture)))
.ForMember(x => x.DestinationUrl, expression => expression.MapFrom(item => item.ContentId > 0 ? GetUrl(umbracoContextAccessor, item) : "#"))
.ForMember(x => x.RedirectId, expression => expression.MapFrom(item => item.Key));
}
private static string GetUrl(IUmbracoContextAccessor umbracoContextAccessor, IRedirectUrl item) => umbracoContextAccessor?.UmbracoContext?.UrlProvider?.GetUrl(item.ContentId, item.Culture);
}
}
| mit | C# |
6fd10d0bf26739a85e9e2d500f2501fff0a4e1eb | Print usage when parsing did not go right. | SharpNative/CSharpLLVM,SharpNative/CSharpLLVM | CSharpLLVM/Program.cs | CSharpLLVM/Program.cs | using CommandLine;
using CSharpLLVM.Compilation;
using System;
using System.IO;
namespace CSharpLLVM
{
class Program
{
/// <summary>
/// Entrypoint.
/// </summary>
/// <param name="args">Arguments.</param>
static void Main(string[] args)
{
Options options = new Options();
Parser parser = new Parser(setSettings);
if (parser.ParseArguments(args, options))
{
string moduleName = Path.GetFileNameWithoutExtension(options.InputFile);
Compiler compiler = new Compiler(options);
compiler.Compile(moduleName);
}
else
{
Console.WriteLine(options.GetUsage());
}
}
/// <summary>
/// Sets the settings.
/// </summary>
/// <param name="settings">The settings.</param>
private static void setSettings(ParserSettings settings)
{
settings.MutuallyExclusive = true;
}
}
}
| using CommandLine;
using CSharpLLVM.Compilation;
using System.IO;
namespace CSharpLLVM
{
class Program
{
/// <summary>
/// Entrypoint.
/// </summary>
/// <param name="args">Arguments.</param>
static void Main(string[] args)
{
Options options = new Options();
Parser parser = new Parser(setSettings);
if (parser.ParseArguments(args, options))
{
string moduleName = Path.GetFileNameWithoutExtension(options.InputFile);
Compiler compiler = new Compiler(options);
compiler.Compile(moduleName);
}
}
/// <summary>
/// Sets the settings.
/// </summary>
/// <param name="settings">The settings.</param>
private static void setSettings(ParserSettings settings)
{
settings.MutuallyExclusive = true;
}
}
}
| mit | C# |
cb5f89bff40b37fbafad334ad87972c53c8020e1 | exclude "2" | ulrichb/NullGuard,shana/NullGuard,Fody/NullGuard | Tests/LargeAssemblyTest.cs | Tests/LargeAssemblyTest.cs | using System;
using System.Diagnostics;
using System.IO;
using Mono.Cecil;
using NUnit.Framework;
[TestFixture]
public class LargeAssemblyTest
{
[Test]
[Ignore]
public void Run()
{
foreach (var assemblyPath in Directory.EnumerateFiles(Environment.CurrentDirectory, "*.dll"))
{
if (assemblyPath.Contains("AssemblyToProcess"))
{
continue;
}
if (assemblyPath.EndsWith("2.dll"))
{
continue;
}
Debug.WriteLine("Verifying " + assemblyPath);
var newAssembly = assemblyPath.Replace(".dll", "2.dll");
File.Copy(assemblyPath, newAssembly, true);
var assemblyResolver = new MockAssemblyResolver();
var moduleDefinition = ModuleDefinition.ReadModule(newAssembly);
var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
AssemblyResolver = assemblyResolver,
};
weavingTask.Execute();
moduleDefinition.Write(newAssembly);
Verifier.Verify(assemblyPath, newAssembly);
}
}
} | using System;
using System.Diagnostics;
using System.IO;
using Mono.Cecil;
using NUnit.Framework;
[TestFixture]
public class LargeAssemblyTest
{
[Test]
[Ignore]
public void Run()
{
foreach (var assemblyPath in Directory.EnumerateFiles(Environment.CurrentDirectory, "*.dll"))
{
if (assemblyPath.Contains("AssemblyToProcess"))
{
continue;
}
Debug.WriteLine("Verifying " + assemblyPath);
var newAssembly = assemblyPath.Replace(".dll", "2.dll");
File.Copy(assemblyPath, newAssembly, true);
var assemblyResolver = new MockAssemblyResolver();
var moduleDefinition = ModuleDefinition.ReadModule(newAssembly);
var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
AssemblyResolver = assemblyResolver,
};
weavingTask.Execute();
moduleDefinition.Write(newAssembly);
Verifier.Verify(assemblyPath, newAssembly);
}
}
} | mit | C# |
c29545e6cd355ae8783f6473bb698412bdabedf0 | add docs, ctor overload to specify time server | Pondidum/RabbitHarness,Pondidum/RabbitHarness | RabbitHarness/NetworkTime.cs | RabbitHarness/NetworkTime.cs | using System;
using System.Net;
using System.Net.Sockets;
using RabbitMQ.Client;
namespace RabbitHarness
{
public class NetworkTime
{
public static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
private readonly string _ntpServer;
/// <summary>
/// Uses <code>pool.ntp.org</code> by default.
/// </summary>
public NetworkTime() : this("pool.ntp.org")
{
}
/// <summary>
/// Uses <code>pool.ntp.org</code> by default.
/// </summary>
public NetworkTime(string ntpServer)
{
_ntpServer = ntpServer;
}
/// <summary>
/// Returns the current time in UTC.
/// </summary>
/// <remarks>http://stackoverflow.com/questions/1193955</remarks>
public DateTime GetNetworkTime()
{
// NTP message size - 16 bytes of the digest (RFC 2030)
var ntpData = new byte[48];
//Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(_ntpServer).AddressList;
//The UDP port number assigned to NTP is 123
var ipEndPoint = new IPEndPoint(addresses[0], 123);
//NTP uses UDP
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
//Stops code hang if NTP is blocked
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
/// <summary>
/// Returns the current time in UTC as a Linux Epoch timestamp
/// </summary>
public AmqpTimestamp GetNetworkTimestamp()
{
var networkTime = GetNetworkTime();
return new AmqpTimestamp((long)(networkTime - Epoch).TotalSeconds);
}
// stackoverflow.com/a/3294698/162671
private static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
}
}
| using System;
using System.Net;
using System.Net.Sockets;
using RabbitMQ.Client;
namespace RabbitHarness
{
public class NetworkTime
{
public static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0);
//http://stackoverflow.com/questions/1193955
public DateTime GetNetworkTime()
{
//default Windows time server
const string ntpServer = "pool.ntp.org";
// NTP message size - 16 bytes of the digest (RFC 2030)
var ntpData = new byte[48];
//Setting the Leap Indicator, Version Number and Mode values
ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
//The UDP port number assigned to NTP is 123
var ipEndPoint = new IPEndPoint(addresses[0], 123);
//NTP uses UDP
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
//Stops code hang if NTP is blocked
socket.ReceiveTimeout = 3000;
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
public AmqpTimestamp GetNetworkTimestamp()
{
var networkTime = GetNetworkTime();
return new AmqpTimestamp((long)(networkTime - Epoch).TotalSeconds);
}
// stackoverflow.com/a/3294698/162671
private static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
}
}
| lgpl-2.1 | C# |
3002c8bf3be7af094f5655e3091e9255cd469f99 | fix receive timeout | vforteli/RadiusServer | RadiusClient/RadiusClient.cs | RadiusClient/RadiusClient.cs | using Flexinets.Radius.Core;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Flexinets.Radius
{
public class RadiusClient
{
private readonly IPEndPoint _localEndpoint;
private readonly RadiusDictionary _dictionary;
/// <summary>
/// Create a radius client which sends and receives responses on localEndpoint
/// </summary>
/// <param name="localEndpoint"></param>
/// <param name="dictionary"></param>
public RadiusClient(IPEndPoint localEndpoint, RadiusDictionary dictionary)
{
_localEndpoint = localEndpoint;
_dictionary = dictionary;
}
/// <summary>
/// Send a packet with specified timeout
/// </summary>
/// <param name="packet"></param>
/// <param name="remoteEndpoint"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public async Task<IRadiusPacket> SendPacketAsync(IRadiusPacket packet, IPEndPoint remoteEndpoint, TimeSpan timeout)
{
var packetBytes = packet.GetBytes(_dictionary);
using (var udpClient = new UdpClient(_localEndpoint))
{
await udpClient.SendAsync(packetBytes, packetBytes.Length, remoteEndpoint);
// todo use events to create a common udpclient for multiple packets to enable sending and receiving without blocking
var responseTask = udpClient.ReceiveAsync();
var completedTask = await Task.WhenAny(responseTask, Task.Delay(timeout));
if (completedTask == responseTask)
{
return RadiusPacket.Parse(responseTask.Result.Buffer, _dictionary, packet.SharedSecret);
}
throw new TaskCanceledException($"Receive timed out after {timeout}");
}
}
/// <summary>
/// Send a packet with default timeout of 3 seconds
/// </summary>
/// <param name="packet"></param>
/// <param name="remoteEndpoint"></param>
/// <returns></returns>
public async Task<IRadiusPacket> SendPacketAsync(IRadiusPacket packet, IPEndPoint remoteEndpoint)
{
return await SendPacketAsync(packet, remoteEndpoint, TimeSpan.FromSeconds(3));
}
}
}
| using Flexinets.Radius.Core;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Flexinets.Radius
{
public class RadiusClient
{
private readonly UdpClient _udpClient;
private readonly RadiusDictionary _dictionary;
public RadiusClient(IPEndPoint localEndpoint, RadiusDictionary dictionary)
{
_udpClient = new UdpClient(localEndpoint);
_dictionary = dictionary;
}
/// <summary>
/// Send a packet with specified timeout
/// </summary>
/// <param name="packet"></param>
/// <param name="remoteEndpoint"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public async Task<IRadiusPacket> SendPacketAsync(IRadiusPacket packet, IPEndPoint remoteEndpoint, TimeSpan timeout)
{
var packetBytes = packet.GetBytes(_dictionary);
await _udpClient.SendAsync(packetBytes, packetBytes.Length, remoteEndpoint);
Task.Run(() =>
{
Thread.Sleep(timeout);
_udpClient?.Close();
});
// todo use events to create a common udpclient for multiple packets to enable sending and receiving without blocking
var response = await _udpClient.ReceiveAsync();
return RadiusPacket.Parse(response.Buffer, _dictionary, packet.SharedSecret);
}
/// <summary>
/// Send a packet with default timeout of 3 seconds
/// </summary>
/// <param name="packet"></param>
/// <param name="remoteEndpoint"></param>
/// <returns></returns>
public async Task<IRadiusPacket> SendPacketAsync(IRadiusPacket packet, IPEndPoint remoteEndpoint)
{
return await SendPacketAsync(packet, remoteEndpoint, TimeSpan.FromSeconds(3));
}
}
}
| mit | C# |
869042b058cf33136a9bd33f3c28a8411f5e70e7 | remove dangerous function | sebas77/Svelto.ECS,sebas77/Svelto-ECS | Svelto.ECS/EGID.cs | Svelto.ECS/EGID.cs | using Svelto.ECS.Internal;
namespace Svelto.ECS
{
public struct EGID
{
long _GID;
public long GID
{
get { return _GID; }
}
public int entityID
{
get { return (int) (_GID & 0xFFFFFFFF); }
}
public int groupID
{
get { return (int) (_GID >> 32); }
}
public EGID(int entityID, int groupID) : this()
{
_GID = MAKE_GLOBAL_ID(entityID, groupID);
}
public EGID(int entityID) : this()
{
_GID = MAKE_GLOBAL_ID(entityID, ExclusiveGroup.StandardEntitiesGroup);
}
static long MAKE_GLOBAL_ID(int entityId, int groupId)
{
return (long)groupId << 32 | ((long)(uint)entityId & 0xFFFFFFFF);
}
}
} | using Svelto.ECS.Internal;
namespace Svelto.ECS
{
public struct EGID
{
long _GID;
public long GID
{
get { return _GID; }
}
public int entityID
{
get { return (int) (_GID & 0xFFFFFFFF); }
}
public int groupID
{
get { return (int) (_GID >> 32); }
}
public EGID(int entityID, int groupID) : this()
{
_GID = MAKE_GLOBAL_ID(entityID, groupID);
}
public EGID(int entityID) : this()
{
_GID = MAKE_GLOBAL_ID(entityID, ExclusiveGroup.StandardEntitiesGroup);
}
static long MAKE_GLOBAL_ID(int entityId, int groupId)
{
return (long)groupId << 32 | ((long)(uint)entityId & 0xFFFFFFFF);
}
public static implicit operator int(EGID id)
{
return id.entityID;
}
}
} | mit | C# |
1f0df0080ad69a31d894f738ad60f39e9bd85fca | Add request and 'methodresponse' type in JSON body to account for other response types using the WebSocket APIs | faint32/snowflake-1,SnowflakePowered/snowflake,faint32/snowflake-1,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,RonnChyran/snowflake | Snowflake/Ajax/JSResponse.cs | Snowflake/Ajax/JSResponse.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Snowflake.Ajax
{
public class JSResponse : IJSResponse
{
public IJSRequest Request { get; private set; }
public dynamic Payload { get; private set; }
public bool Success { get; set; }
public JSResponse(IJSRequest request, dynamic payload, bool success = true)
{
this.Request = request;
this.Payload = payload;
this.Success = success;
}
public string GetJson()
{
return JSResponse.ProcessJSONP(this.Payload, this.Success, this.Request);
}
private static string ProcessJSONP(dynamic output, bool success, IJSRequest request)
{
if (request.MethodParameters.ContainsKey("jsoncallback"))
{
return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(new Dictionary<string, object>(){
{"request", request},
{"payload", output},
{"success", success},
{"type", "methodresponse"}
}) + ");";
}
else
{
return JsonConvert.SerializeObject(new Dictionary<string, object>(){
{"request", request},
{"payload", output},
{"success", success},
{"type", "methodresponse"}
});
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Snowflake.Ajax
{
public class JSResponse : IJSResponse
{
public IJSRequest Request { get; private set; }
public dynamic Payload { get; private set; }
public bool Success { get; set; }
public JSResponse(IJSRequest request, dynamic payload, bool success = true)
{
this.Request = request;
this.Payload = payload;
this.Success = success;
}
public string GetJson()
{
return JSResponse.ProcessJSONP(this.Payload, this.Success, this.Request);
}
private static string ProcessJSONP(dynamic output, bool success, IJSRequest request)
{
if (request.MethodParameters.ContainsKey("jsoncallback"))
{
return request.MethodParameters["jsoncallback"] + "(" + JsonConvert.SerializeObject(new Dictionary<string, object>(){
{"payload", output},
{"success", success}
}) + ");";
}
else
{
return JsonConvert.SerializeObject(new Dictionary<string, object>(){
{"payload", output},
{"success", success}
});
}
}
}
}
| mpl-2.0 | C# |
f2be4cf658a5ac82a2eeebe1d9905840d63e0843 | Fix Postgres Decimal | KaraokeStu/fluentmigrator,daniellee/fluentmigrator,swalters/fluentmigrator,bluefalcon/fluentmigrator,dealproc/fluentmigrator,spaccabit/fluentmigrator,mstancombe/fluentmig,DefiSolutions/fluentmigrator,fluentmigrator/fluentmigrator,istaheev/fluentmigrator,akema-fr/fluentmigrator,tohagan/fluentmigrator,swalters/fluentmigrator,igitur/fluentmigrator,fluentmigrator/fluentmigrator,dealproc/fluentmigrator,MetSystem/fluentmigrator,itn3000/fluentmigrator,alphamc/fluentmigrator,akema-fr/fluentmigrator,daniellee/fluentmigrator,stsrki/fluentmigrator,jogibear9988/fluentmigrator,tommarien/fluentmigrator,wolfascu/fluentmigrator,modulexcite/fluentmigrator,mstancombe/fluentmig,barser/fluentmigrator,lcharlebois/fluentmigrator,drmohundro/fluentmigrator,stsrki/fluentmigrator,modulexcite/fluentmigrator,mstancombe/fluentmig,drmohundro/fluentmigrator,IRlyDontKnow/fluentmigrator,amroel/fluentmigrator,tohagan/fluentmigrator,istaheev/fluentmigrator,FabioNascimento/fluentmigrator,bluefalcon/fluentmigrator,IRlyDontKnow/fluentmigrator,tohagan/fluentmigrator,KaraokeStu/fluentmigrator,eloekset/fluentmigrator,amroel/fluentmigrator,lahma/fluentmigrator,alphamc/fluentmigrator,schambers/fluentmigrator,DefiSolutions/fluentmigrator,lahma/fluentmigrator,daniellee/fluentmigrator,barser/fluentmigrator,wolfascu/fluentmigrator,spaccabit/fluentmigrator,lcharlebois/fluentmigrator,DefiSolutions/fluentmigrator,vgrigoriu/fluentmigrator,tommarien/fluentmigrator,lahma/fluentmigrator,MetSystem/fluentmigrator,eloekset/fluentmigrator,jogibear9988/fluentmigrator,igitur/fluentmigrator,schambers/fluentmigrator,istaheev/fluentmigrator,mstancombe/fluentmigrator,FabioNascimento/fluentmigrator,mstancombe/fluentmigrator,vgrigoriu/fluentmigrator,itn3000/fluentmigrator | src/FluentMigrator.Runner/Generators/Postgres/PostgresTypeMap.cs | src/FluentMigrator.Runner/Generators/Postgres/PostgresTypeMap.cs | using System.Data;
using FluentMigrator.Runner.Generators.Base;
namespace FluentMigrator.Runner.Generators.Postgres
{
internal class PostgresTypeMap : TypeMapBase
{
private const int DecimalCapacity = 1000;
private const int PostgresMaxVarcharSize = 10485760;
protected override void SetupTypeMaps()
{
SetTypeMap(DbType.AnsiStringFixedLength, "char(255)");
SetTypeMap(DbType.AnsiStringFixedLength, "char($size)", int.MaxValue);
SetTypeMap(DbType.AnsiString, "text");
SetTypeMap(DbType.AnsiString, "varchar($size)", PostgresMaxVarcharSize);
SetTypeMap(DbType.AnsiString, "text", int.MaxValue);
SetTypeMap(DbType.Binary, "bytea");
SetTypeMap(DbType.Boolean, "boolean");
SetTypeMap(DbType.Byte, "smallint"); //no built-in support for single byte unsigned integers
SetTypeMap(DbType.Currency, "money");
SetTypeMap(DbType.Date, "date");
SetTypeMap(DbType.DateTime, "timestamp");
SetTypeMap(DbType.Decimal, "decimal(19,5)");
SetTypeMap(DbType.Decimal, "decimal($precision,$size)", DecimalCapacity);
SetTypeMap(DbType.Double, "float8");
SetTypeMap(DbType.Guid, "uuid");
SetTypeMap(DbType.Int16, "smallint");
SetTypeMap(DbType.Int32, "integer");
SetTypeMap(DbType.Int64, "bigint");
SetTypeMap(DbType.Single, "float4");
SetTypeMap(DbType.StringFixedLength, "char(255)");
SetTypeMap(DbType.StringFixedLength, "char($size)", int.MaxValue);
SetTypeMap(DbType.String, "text");
SetTypeMap(DbType.String, "varchar($size)", PostgresMaxVarcharSize);
SetTypeMap(DbType.String, "text", int.MaxValue);
SetTypeMap(DbType.Time, "time");
}
}
} | using System.Data;
using FluentMigrator.Runner.Generators.Base;
namespace FluentMigrator.Runner.Generators.Postgres
{
internal class PostgresTypeMap : TypeMapBase
{
private const int DecimalCapacity = 1000;
private const int PostgresMaxVarcharSize = 10485760;
protected override void SetupTypeMaps()
{
SetTypeMap(DbType.AnsiStringFixedLength, "char(255)");
SetTypeMap(DbType.AnsiStringFixedLength, "char($size)", int.MaxValue);
SetTypeMap(DbType.AnsiString, "text");
SetTypeMap(DbType.AnsiString, "varchar($size)", PostgresMaxVarcharSize);
SetTypeMap(DbType.AnsiString, "text", int.MaxValue);
SetTypeMap(DbType.Binary, "bytea");
SetTypeMap(DbType.Boolean, "boolean");
SetTypeMap(DbType.Byte, "smallint"); //no built-in support for single byte unsigned integers
SetTypeMap(DbType.Currency, "money");
SetTypeMap(DbType.Date, "date");
SetTypeMap(DbType.DateTime, "timestamp");
SetTypeMap(DbType.Decimal, "decimal(5,19)");
SetTypeMap(DbType.Decimal, "decimal($precision,$size)", DecimalCapacity);
SetTypeMap(DbType.Double, "float8");
SetTypeMap(DbType.Guid, "uuid");
SetTypeMap(DbType.Int16, "smallint");
SetTypeMap(DbType.Int32, "integer");
SetTypeMap(DbType.Int64, "bigint");
SetTypeMap(DbType.Single, "float4");
SetTypeMap(DbType.StringFixedLength, "char(255)");
SetTypeMap(DbType.StringFixedLength, "char($size)", int.MaxValue);
SetTypeMap(DbType.String, "text");
SetTypeMap(DbType.String, "varchar($size)", PostgresMaxVarcharSize);
SetTypeMap(DbType.String, "text", int.MaxValue);
SetTypeMap(DbType.Time, "time");
}
}
} | apache-2.0 | C# |
c47344a5c6d8a16606d642ef22036a7e65726d2c | Remove duplicate code | sergeyshushlyapin/Sitecore.FakeDb,pveller/Sitecore.FakeDb,hermanussen/Sitecore.FakeDb | src/Sitecore.FakeDb/Data/Engines/DataCommands/MoveItemCommand.cs | src/Sitecore.FakeDb/Data/Engines/DataCommands/MoveItemCommand.cs | namespace Sitecore.FakeDb.Data.Engines.DataCommands
{
using Sitecore.Diagnostics;
public class MoveItemCommand : Sitecore.Data.Engines.DataCommands.MoveItemCommand, IDataEngineCommand
{
private readonly DataEngineCommand innerCommand = new DataEngineCommand();
public virtual void Initialize(DataStorage dataStorage)
{
Assert.ArgumentNotNull(dataStorage, "dataStorage");
this.innerCommand.Initialize(dataStorage);
}
protected override Sitecore.Data.Engines.DataCommands.MoveItemCommand CreateInstance()
{
return this.innerCommand.CreateInstance<Sitecore.Data.Engines.DataCommands.MoveItemCommand, MoveItemCommand>();
}
protected override bool DoExecute()
{
var dataStorage = this.innerCommand.DataStorage;
var fakeItem = dataStorage.GetFakeItem(this.Item.ID);
var oldParent = dataStorage.GetFakeItem(fakeItem.ParentID);
oldParent.Children.Remove(fakeItem);
var destination = dataStorage.GetFakeItem(this.Destination.ID);
destination.Children.Add(fakeItem);
return true;
}
}
} | namespace Sitecore.FakeDb.Data.Engines.DataCommands
{
using Sitecore.Diagnostics;
public class MoveItemCommand : Sitecore.Data.Engines.DataCommands.MoveItemCommand, IDataEngineCommand
{
private readonly DataEngineCommand innerCommand = new DataEngineCommand();
public virtual void Initialize(DataStorage dataStorage)
{
Assert.ArgumentNotNull(dataStorage, "dataStorage");
this.innerCommand.Initialize(dataStorage);
}
protected override Sitecore.Data.Engines.DataCommands.MoveItemCommand CreateInstance()
{
return this.innerCommand.CreateInstance<Sitecore.Data.Engines.DataCommands.MoveItemCommand, MoveItemCommand>();
}
protected override bool DoExecute()
{
var dataStorage = this.innerCommand.DataStorage;
var fakeItem = dataStorage.GetFakeItem(this.Item.ID);
var oldParent = dataStorage.GetFakeItem(fakeItem.ParentID);
oldParent.Children.Remove(fakeItem);
var destination = dataStorage.GetFakeItem(Destination.ID);
fakeItem.ParentID = destination.ID;
fakeItem.FullPath = destination.FullPath + "/" + this.Item.Name;
destination.Children.Add(fakeItem);
return true;
}
}
} | mit | C# |
12f407ce302dbe304fbb0ee43ecbe621a3db57c8 | Change up the namespace | awseward/restivus | src/Restivus/Serilog/SerilogExtensions.cs | src/Restivus/Serilog/SerilogExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Restivus;
namespace Serilog.Restivus
{
public static class SerilogExtensions
{
public static LoggerConfiguration FilterRequestQueryParams(
this LoggerConfiguration loggerConfig,
params string[] queryParamKeys)
{
return loggerConfig.Destructure.ByTransforming<HttpRequestMessage>(
request => new
{
request.Method.Method,
Uri = request.RequestUri.FilterQueryParams(queryParamKeys),
Headers = request.Headers._SlightlySimplified(),
}
);
}
public static LoggerConfiguration DestructureHttpResponseMessages(
this LoggerConfiguration loggerConfig)
{
return loggerConfig.Destructure.ByTransforming<HttpResponseMessage>(
response => new
{
Status = (int) response.StatusCode,
response.RequestMessage,
Headers = response.Headers._SlightlySimplified(),
}
);
}
static IDictionary<string, string> _SlightlySimplified(this HttpHeaders headers) =>
headers.ToDictionary(
kvp => kvp.Key,
kvp => string.Join(", ", kvp.Value)
);
}
}
| using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Restivus.Serilog
{
public static class SerilogExtensions
{
public static LoggerConfiguration FilterRequestQueryParams(
this LoggerConfiguration loggerConfig,
params string[] queryParamKeys)
{
return loggerConfig.Destructure.ByTransforming<HttpRequestMessage>(
request => new
{
request.Method.Method,
Uri = request.RequestUri.FilterQueryParams(queryParamKeys),
Headers = request.Headers._SlightlySimplified(),
}
);
}
public static LoggerConfiguration DestructureHttpResponseMessages(
this LoggerConfiguration loggerConfig)
{
return loggerConfig.Destructure.ByTransforming<HttpResponseMessage>(
response => new
{
Status = (int) response.StatusCode,
response.RequestMessage,
Headers = response.Headers._SlightlySimplified(),
}
);
}
static IDictionary<string, string> _SlightlySimplified(this HttpHeaders headers) =>
headers.ToDictionary(
kvp => kvp.Key,
kvp => string.Join(", ", kvp.Value)
);
}
}
| mit | C# |
ee3a3de754839c8ab070144566ac3651b9802a3d | Update EmailSender.cs | Narvalex/SimpleEmailSender,Narvalex/SimpleEmailSender | src/SimpleEmailSender.Core/EmailSender.cs | src/SimpleEmailSender.Core/EmailSender.cs | using Eventing.Utils;
using System;
using System.Linq;
using System.Net.Mail;
namespace SimpleEmailSender
{
public class EmailSender : IEmailSender
{
private readonly Func<SmtpClient> smtpClientFactory;
public EmailSender(string host, int port, bool enableSsl = false)
: this(() => new SmtpClient
{
Host = host,
Port = port,
UseDefaultCredentials = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = enableSsl
})
{ }
public EmailSender(Func<SmtpClient> smtpClientFactory)
{
Ensure.NotNull(smtpClientFactory, nameof(smtpClientFactory));
this.smtpClientFactory = smtpClientFactory;
}
public void Send(Envelope mail)
{
using (var smpt = this.smtpClientFactory.Invoke())
{
var mailMessage = new MailMessage
{
From = new MailAddress(mail.From.Address, mail.From.Name),
Subject = mail.Subject,
Body = mail.Body,
IsBodyHtml = mail.IsBodyHtml,
Priority = mail.Priority
};
mailMessage.To.AddRange(mail.To.Select(c => new MailAddress(c.Address, c.Name)));
mailMessage.CC.AddRange(mail.CarbonCopies.Select(c => new MailAddress(c.Address, c.Name)));
mailMessage.Bcc.AddRange(mail.BlindCarbonCopies.Select(c => new MailAddress(c.Address, c.Name)));
mailMessage.ReplyToList.AddRange(mail.ReplyToList.Select(c => new MailAddress(c.Address, c.Name)));
if (mail.Attachments != null && mail.Attachments.Length > 0)
{
mailMessage.Attachments.AddRange(mail.Attachments);
}
smpt.Send(mailMessage);
}
}
}
}
| using Eventing.Utils;
using System;
using System.Linq;
using System.Net.Mail;
namespace SimpleEmailSender
{
public class EmailSender : IEmailSender
{
private readonly Func<SmtpClient> smtpClientFactory;
public EmailSender(string host, int port, bool enableSsl = false)
: this(() => new SmtpClient
{
Host = host,
Port = port,
UseDefaultCredentials = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = enableSsl
})
{ }
public EmailSender(Func<SmtpClient> smtpClientFactory)
{
Ensure.NotNull(smtpClientFactory, nameof(smtpClientFactory));
this.smtpClientFactory = smtpClientFactory;
}
public void Send(Envelope mail)
{
using (var smpt = this.smtpClientFactory.Invoke())
{
var mailMessage = new MailMessage
{
From = new MailAddress(mail.From.Address, mail.From.Name),
Subject = mail.Subject,
Body = mail.Body,
IsBodyHtml = mail.IsBodyHtml,
Priority = mail.Priority
};
mailMessage.To.AddRange(mail.To.Select(c => new MailAddress(c.Address, c.Name)));
mailMessage.CC.AddRange(mail.CarbonCopies.Select(c => new MailAddress(c.Address, c.Name)));
mailMessage.Bcc.AddRange(mail.BlindCarbonCopies.Select(c => new MailAddress(c.Address, c.Name)));
mailMessage.ReplyToList.AddRange(mail.ReplyToList.Select(c => new MailAddress(c.Address, c.Name)));
smpt.Send(mailMessage);
}
}
}
}
| mit | C# |
847d08c5bbb958b3df90cd76a3bb927c56c2e35a | Change version number for breaking change. | digipost/digipost-api-client-dotnet | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("6.2.*")]
[assembly: AssemblyFileVersion("6.2.*")] | using System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("6.1.*")]
[assembly: AssemblyFileVersion("6.1.*")] | apache-2.0 | C# |
c3c0677d4f07bb97e08b96d1b63c96192ae62e9f | Fix Bundle pietimer.min | Arionildo/Quiz-CWI,Arionildo/Quiz-CWI,Arionildo/Quiz-CWI | Quiz/Quiz.Web/App_Start/BundleConfig.cs | Quiz/Quiz.Web/App_Start/BundleConfig.cs | using System.Web;
using System.Web.Optimization;
namespace Quiz.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/jquery.pietimer").Include(
"~/Scripts/jquery.pietimer.js",
"~/Scripts/jquery.pietimer.min.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| using System.Web;
using System.Web.Optimization;
namespace Quiz.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/jquery.pietimer").Include(
"~/Scripts/jquery.pietimer.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| mit | C# |
2e86bd44dd8dcb71c305b96ac51bbfa0d6fe6867 | Fix warnings | devlights/try-csharp | TryCSharp.Tools.Cui/CuiOutputManager.cs | TryCSharp.Tools.Cui/CuiOutputManager.cs | using System;
using System.IO;
using TryCSharp.Common;
namespace TryCSharp.Tools.Cui
{
/// <summary>
/// CUIアプリでの出力を管理するクラスです。
/// </summary>
public class CuiOutputManager : IOutputManager
{
/// <summary>
/// 指定されたデータを出力します。(改行付与無し)
/// </summary>
/// <param name="data">データ</param>
public void Write(object? data) => Console.Write(data);
/// <summary>
/// 指定されたデータを出力します。(改行付与有り)
/// </summary>
/// <param name="data">データ</param>
public void WriteLine(object? data) => Console.WriteLine(data);
/// <summary>
/// 出力ストリーム
/// </summary>
public Stream OutStream => Console.OpenStandardOutput();
}
} | using System;
using System.IO;
using TryCSharp.Common;
namespace TryCSharp.Tools.Cui
{
/// <summary>
/// CUIアプリでの出力を管理するクラスです。
/// </summary>
public class CuiOutputManager : IOutputManager
{
/// <summary>
/// 指定されたデータを出力します。(改行付与無し)
/// </summary>
/// <param name="data">データ</param>
public void Write(object data) => Console.Write(data);
/// <summary>
/// 指定されたデータを出力します。(改行付与有り)
/// </summary>
/// <param name="data">データ</param>
public void WriteLine(object data) => Console.WriteLine(data);
/// <summary>
/// 出力ストリーム
/// </summary>
public Stream OutStream => Console.OpenStandardOutput();
}
} | mit | C# |
fccfd12d3f5e96cb48f437c6dc31f9996087e536 | Fix unit test | DaveSenn/Extend | PortableExtensions.Testing/System.Object/Convert/Object.ToDecimal.Test.cs | PortableExtensions.Testing/System.Object/Convert/Object.ToDecimal.Test.cs | #region Usings
using System;
using System.Globalization;
using System.Threading;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class ObjectExTest
{
[Test]
public void ToDecimalTestCase ()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo( "en-US" );
var expected = new Decimal( 100.12 );
var value = expected.ToString( Thread.CurrentThread.CurrentCulture );
var actual = ObjectEx.ToDecimal( value );
Assert.AreEqual( expected, actual );
}
[Test]
public void ToDecimalTestCase1 ()
{
var expected = new Decimal( 100.12 );
var value = expected.ToString( CultureInfo.InvariantCulture );
var actual = ObjectEx.ToDecimal( value, CultureInfo.InvariantCulture );
Assert.AreEqual( expected, actual );
}
[Test]
[ExpectedException ( typeof (ArgumentNullException) )]
public void ToDecimalTestCase1NullCheck ()
{
ObjectEx.ToDecimal( null, CultureInfo.InvariantCulture );
}
[Test]
[ExpectedException ( typeof (ArgumentNullException) )]
public void ToDecimalTestCase1NullCheck1 ()
{
ObjectEx.ToDecimal( "false", null );
}
[Test]
[ExpectedException ( typeof (ArgumentNullException) )]
public void ToDecimalTestCaseNullCheck ()
{
ObjectEx.ToDecimal( null );
}
}
} | #region Usings
using System;
using System.Globalization;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class ObjectExTest
{
[Test]
public void ToDecimalTestCase ()
{
var expected = new Decimal( 100.12 );
var value = expected.ToString( CultureInfo.InvariantCulture ).Replace( ".", "," );
var actual = ObjectEx.ToDecimal( value );
Assert.AreEqual( expected, actual );
}
[Test]
public void ToDecimalTestCase1 ()
{
var expected = new Decimal( 100.12 );
var value = expected.ToString( CultureInfo.InvariantCulture );
var actual = ObjectEx.ToDecimal( value, CultureInfo.InvariantCulture );
Assert.AreEqual( expected, actual );
}
[Test]
[ExpectedException ( typeof (ArgumentNullException) )]
public void ToDecimalTestCase1NullCheck ()
{
ObjectEx.ToDecimal( null, CultureInfo.InvariantCulture );
}
[Test]
[ExpectedException ( typeof (ArgumentNullException) )]
public void ToDecimalTestCase1NullCheck1 ()
{
ObjectEx.ToDecimal( "false", null );
}
[Test]
[ExpectedException ( typeof (ArgumentNullException) )]
public void ToDecimalTestCaseNullCheck ()
{
ObjectEx.ToDecimal( null );
}
}
} | mit | C# |
7d3325b35580c30193f2d1c7c600f267c4320969 | Add DecryptionInProgress for EncryptionStatus enum | jtlibing/azure-powershell,krkhan/azure-powershell,pankajsn/azure-powershell,arcadiahlyy/azure-powershell,AzureRT/azure-powershell,yantang-msft/azure-powershell,hungmai-msft/azure-powershell,nemanja88/azure-powershell,AzureAutomationTeam/azure-powershell,seanbamsft/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,yoavrubin/azure-powershell,AzureAutomationTeam/azure-powershell,krkhan/azure-powershell,alfantp/azure-powershell,yantang-msft/azure-powershell,ClogenyTechnologies/azure-powershell,hungmai-msft/azure-powershell,yantang-msft/azure-powershell,atpham256/azure-powershell,hungmai-msft/azure-powershell,jtlibing/azure-powershell,zhencui/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,pankajsn/azure-powershell,pankajsn/azure-powershell,yoavrubin/azure-powershell,nemanja88/azure-powershell,naveedaz/azure-powershell,AzureRT/azure-powershell,AzureAutomationTeam/azure-powershell,naveedaz/azure-powershell,yoavrubin/azure-powershell,jtlibing/azure-powershell,hungmai-msft/azure-powershell,seanbamsft/azure-powershell,AzureRT/azure-powershell,alfantp/azure-powershell,seanbamsft/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,zhencui/azure-powershell,hungmai-msft/azure-powershell,yantang-msft/azure-powershell,jtlibing/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,alfantp/azure-powershell,zhencui/azure-powershell,seanbamsft/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,krkhan/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,arcadiahlyy/azure-powershell,yantang-msft/azure-powershell,seanbamsft/azure-powershell,rohmano/azure-powershell,arcadiahlyy/azure-powershell,yoavrubin/azure-powershell,rohmano/azure-powershell,devigned/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell,AzureAutomationTeam/azure-powershell,AzureRT/azure-powershell,zhencui/azure-powershell,krkhan/azure-powershell,alfantp/azure-powershell,nemanja88/azure-powershell,arcadiahlyy/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,yoavrubin/azure-powershell,nemanja88/azure-powershell,alfantp/azure-powershell,hungmai-msft/azure-powershell,pankajsn/azure-powershell,rohmano/azure-powershell,jtlibing/azure-powershell,pankajsn/azure-powershell,AzureRT/azure-powershell,atpham256/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,seanbamsft/azure-powershell,yantang-msft/azure-powershell,nemanja88/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,rohmano/azure-powershell,krkhan/azure-powershell,arcadiahlyy/azure-powershell | src/ResourceManager/Compute/Commands.Compute/Models/AzureDiskEncryptionStatusContext.cs | src/ResourceManager/Compute/Commands.Compute/Models/AzureDiskEncryptionStatusContext.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json;
namespace Microsoft.Azure.Commands.Compute.Models
{
enum EncryptionStatus
{
Encrypted,
NotEncrypted,
NotMounted,
DecryptionInProgress,
EncryptionInProgress,
VMRestartPending,
Unknown
}
class AzureDiskEncryptionStatusContext
{
public EncryptionStatus OsVolumeEncrypted { get; set; }
public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; }
public EncryptionStatus DataVolumesEncrypted { get; set; }
public string ProgressMessage { get; set; }
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json;
namespace Microsoft.Azure.Commands.Compute.Models
{
enum EncryptionStatus
{
Encrypted,
NotEncrypted,
NotMounted,
EncryptionInProgress,
VMRestartPending,
Unknown
}
class AzureDiskEncryptionStatusContext
{
public EncryptionStatus OsVolumeEncrypted { get; set; }
public DiskEncryptionSettings OsVolumeEncryptionSettings { get; set; }
public EncryptionStatus DataVolumesEncrypted { get; set; }
public string ProgressMessage { get; set; }
}
}
| apache-2.0 | C# |
10dc8c531b0240b6d911277548ca51c485793eae | Update contacts sample for RequestPermission | xamarin/Xamarin.Mobile,xamarin/Xamarin.Mobile,orand/Xamarin.Mobile,nexussays/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile,moljac/Xamarin.Mobile | WindowsPhone/Samples/ContactsSample/MainPageViewModel.cs | WindowsPhone/Samples/ContactsSample/MainPageViewModel.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Media.Imaging;
using Xamarin.Contacts;
using System.Threading.Tasks;
namespace ContactsSample
{
public class MainPageViewModel
: INotifyPropertyChanged
{
public MainPageViewModel()
{
Setup();
}
private async Task Setup()
{
if (!await this.addressBook.RequestPermission())
this.addressBook = null;
}
public event EventHandler SelectedContact;
public event PropertyChangedEventHandler PropertyChanged;
private bool showProgress = true;
public bool ShowProgress
{
get { return this.showProgress; }
set
{
if (this.showProgress == value)
return;
this.showProgress = value;
OnPropertyChanged("ShowProgress");
}
}
public IEnumerable<Contact> Contacts
{
get { return FinishWhenIterated (this.addressBook ?? Enumerable.Empty<Contact>()); }
}
private BitmapImage thumb;
public BitmapImage Thumbnail
{
get
{
if (this.thumb == null && this.contact != null)
this.thumb = this.contact.GetThumbnail();
return this.thumb;
}
}
private Contact contact;
public Contact Contact
{
get { return this.contact; }
set
{
if (this.contact == value)
return;
this.contact = value;
this.thumb = null;
OnPropertyChanged ("Contact");
OnPropertyChanged ("Thumbnail");
if (value != null)
OnSelectedContact (EventArgs.Empty);
}
}
private AddressBook addressBook = new AddressBook();
private IEnumerable<Contact> FinishWhenIterated (IEnumerable<Contact> contacts)
{
foreach (var contact in contacts)
yield return contact;
ShowProgress = false;
}
private void OnPropertyChanged (string name)
{
var changed = PropertyChanged;
if (changed != null)
changed (this, new PropertyChangedEventArgs (name));
}
private void OnSelectedContact (EventArgs e)
{
var selected = SelectedContact;
if (selected != null)
selected (this, e);
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Media.Imaging;
using Xamarin.Contacts;
namespace ContactsSample
{
public class MainPageViewModel
: INotifyPropertyChanged
{
public MainPageViewModel()
{
Contact = Contacts.First();
}
public event EventHandler SelectedContact;
public event PropertyChangedEventHandler PropertyChanged;
private bool showProgress = true;
public bool ShowProgress
{
get { return this.showProgress; }
set
{
if (this.showProgress == value)
return;
this.showProgress = value;
OnPropertyChanged("ShowProgress");
}
}
public IEnumerable<Contact> Contacts
{
get { return FinishWhenIterated (this.addressBook ?? Enumerable.Empty<Contact>()); }
}
private BitmapImage thumb;
public BitmapImage Thumbnail
{
get { return this.thumb ?? (this.thumb = this.contact.GetThumbnail()); }
}
private Contact contact;
public Contact Contact
{
get { return this.contact; }
set
{
if (this.contact == value)
return;
this.contact = value;
this.thumb = null;
OnPropertyChanged ("Contact");
OnPropertyChanged ("Thumbnail");
if (value != null)
OnSelectedContact (EventArgs.Empty);
}
}
private readonly AddressBook addressBook = new AddressBook();
private IEnumerable<Contact> FinishWhenIterated (IEnumerable<Contact> contacts)
{
foreach (var contact in contacts)
yield return contact;
ShowProgress = false;
}
private void OnPropertyChanged (string name)
{
var changed = PropertyChanged;
if (changed != null)
changed (this, new PropertyChangedEventArgs (name));
}
private void OnSelectedContact (EventArgs e)
{
var selected = SelectedContact;
if (selected != null)
selected (this, e);
}
}
}
| apache-2.0 | C# |
7c14208f79310e06ca60581f786059cec2945007 | Add Gateball option to top navigation bar | croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au | source/CroquetAustralia.Website/app/Infrastructure/PublicNavigationBar.cs | source/CroquetAustralia.Website/app/Infrastructure/PublicNavigationBar.cs | using System.Collections.Generic;
namespace CroquetAustralia.Website.App.Infrastructure
{
public static class PublicNavigationBar
{
public static IEnumerable<NavigationItem> GetNavigationItems()
{
return new[]
{
new NavigationItem("Contact Us",
new NavigationItem("Office & Board", "~/governance/contact-us"),
new NavigationItem("Committees", "~/governance/contact-us#committees"),
new NavigationItem("Appointed Officers", "~/governance/contact-us#appointed-officers"),
new NavigationItem("State Associations", "~/governance/state-associations")),
new NavigationItem("Governance",
new NavigationItem("Background", "~/governance/background"),
new NavigationItem("Constitution, Regulations & Policies", "~/governance/constitution-regulations-and-policies"),
new NavigationItem("Members", "~/governance/members"),
new NavigationItem("Board Meeting Minutes", "~/governance/minutes/board-meeting-minutes"),
new NavigationItem("Insurance", "~/governance/insurance")),
new NavigationItem("Tournaments", "~/tournaments"),
new NavigationItem("Disciplines",
new NavigationItem("Association Croquet",
new NavigationItem("Coaching", "~/disciplines/association-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/association-croquet/refereeing"),
new NavigationItem("Resources", "~/disciplines/association-croquet/resources")),
new NavigationItem("Gateball", "http://gateball.com.au"),
new NavigationItem("Golf Croquet",
new NavigationItem("Coaching", "~/disciplines/golf-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/golf-croquet/refereeing"),
new NavigationItem("Resources", "~/disciplines/golf-croquet/resources")))
};
}
}
}
| using System.Collections.Generic;
namespace CroquetAustralia.Website.App.Infrastructure
{
public static class PublicNavigationBar
{
public static IEnumerable<NavigationItem> GetNavigationItems()
{
return new[]
{
new NavigationItem("Contact Us",
new NavigationItem("Office & Board", "~/governance/contact-us"),
new NavigationItem("Committees", "~/governance/contact-us#committees"),
new NavigationItem("Appointed Officers", "~/governance/contact-us#appointed-officers"),
new NavigationItem("State Associations", "~/governance/state-associations")),
new NavigationItem("Governance",
new NavigationItem("Background", "~/governance/background"),
new NavigationItem("Constitution, Regulations & Policies", "~/governance/constitution-regulations-and-policies"),
new NavigationItem("Members", "~/governance/members"),
new NavigationItem("Board Meeting Minutes", "~/governance/minutes/board-meeting-minutes"),
new NavigationItem("Insurance", "~/governance/insurance")),
new NavigationItem("Tournaments", "~/tournaments"),
new NavigationItem("Disciplines",
new NavigationItem("Association Croquet",
new NavigationItem("Coaching", "~/disciplines/association-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/association-croquet/refereeing"),
new NavigationItem("Resources", "~/disciplines/association-croquet/resources")),
new NavigationItem("Golf Croquet",
new NavigationItem("Coaching", "~/disciplines/golf-croquet/coaching"),
new NavigationItem("Refereeing", "~/disciplines/golf-croquet/refereeing"),
new NavigationItem("Resources", "~/disciplines/golf-croquet/resources")))
};
}
}
}
| mit | C# |
c9be768be36aa319c0f01fc89b9f8d651c50cedd | Add analytics event for package rate | opencolorado/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,DenverDev/.NET-Wrapper-for-CKAN-API,DenverDev/.NET-Wrapper-for-CKAN-API | CkanDotNet.Web/Views/Shared/_Rating.cshtml | CkanDotNet.Web/Views/Shared/_Rating.cshtml | @using CkanDotNet.Api.Model
@using CkanDotNet.Web.Models
@using CkanDotNet.Web.Models.Helpers
@model Package
@{
bool editable = Convert.ToBoolean(ViewData["editable"]);
string ratingId = GuidHelper.GetUniqueKey(16);
}
@if (Model.RatingsAverage.HasValue || editable)
{
<div id="@ratingId" class="rating">
@{
int rating = 0;
if (Model.RatingsAverage.HasValue)
{
rating = (int)Math.Round(Model.RatingsAverage.Value);
}
}
@for (int i = 1; i <= 5; i++)
{
@Html.RadioButton("newrate", i, rating == i)
}
</div>
<span class="rating-response"></span>
}
<script language="javascript">
$("#@(ratingId)").stars({
oneVoteOnly: true,
@if (!editable)
{
@:disabled: true,
}
callback: function(ui, type, value){
var url = "http://@SettingsHelper.GetRepositoryHost()/package/rate/@Model.Name?rating=" + value;
$("#@(ratingId)_iframe").get(0).src = url;
$(".rating-response").text("Thanks for your rating!");
// Track the rating event in analytics
debugger;
_gaq.push([
'_trackEvent',
'Package:@Model.Name',
'Rate',
value,
value]);
}
});
</script>
@if (editable)
{
<iframe id="@(ratingId)_iframe" width="0" height="0" frameborder="0" src=""></iframe>
} | @using CkanDotNet.Api.Model
@using CkanDotNet.Web.Models
@using CkanDotNet.Web.Models.Helpers
@model Package
@{
bool editable = Convert.ToBoolean(ViewData["editable"]);
string ratingId = GuidHelper.GetUniqueKey(16);
}
@if (Model.RatingsAverage.HasValue || editable)
{
<div id="@ratingId" class="rating">
@{
int rating = 0;
if (Model.RatingsAverage.HasValue)
{
rating = (int)Math.Round(Model.RatingsAverage.Value);
}
}
@for (int i = 1; i <= 5; i++)
{
@Html.RadioButton("newrate", i, rating == i)
}
</div>
<span class="rating-response"></span>
}
<script language="javascript">
$("#@(ratingId)").stars({
oneVoteOnly: true,
@if (!editable)
{
@:disabled: true,
}
callback: function(ui, type, value){
var url = "http://@SettingsHelper.GetRepositoryHost()/package/rate/@Model.Name?rating=" + value;
$("#@(ratingId)_iframe").get(0).src = url;
$(".rating-response").text("Thanks for your rating!");
}
});
</script>
@if (editable)
{
<iframe id="@(ratingId)_iframe" width="0" height="0" frameborder="0" src=""></iframe>
} | apache-2.0 | C# |
d8a906b448fe9f56163b4a3c4797b5019f3baa2f | Check if status label is constructed before executing update | ethanmoffat/EndlessClient | EndlessClient/UIControls/StatusBarLabel.cs | EndlessClient/UIControls/StatusBarLabel.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using EndlessClient.HUD;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;
namespace EndlessClient.UIControls
{
public class StatusBarLabel : XNALabel
{
private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;
private readonly IStatusLabelTextProvider _statusLabelTextProvider;
private readonly bool _constructed;
public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
IStatusLabelTextProvider statusLabelTextProvider)
: base(GetPositionBasedOnWindowSize(clientWindowSizeProvider), Constants.FontSize07)
{
_statusLabelTextProvider = statusLabelTextProvider;
_constructed = true;
}
public override void Update(GameTime gameTime)
{
if (!_constructed)
return;
if (Text != _statusLabelTextProvider.StatusText)
{
Text = _statusLabelTextProvider.StatusText;
Visible = true;
}
if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
Visible = false;
base.Update(gameTime);
}
private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider clientWindowSizeProvider)
{
return new Rectangle(97, clientWindowSizeProvider.Height - 25, 1, 1);
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using EndlessClient.HUD;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;
namespace EndlessClient.UIControls
{
public class StatusBarLabel : XNALabel
{
private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;
private readonly IStatusLabelTextProvider _statusLabelTextProvider;
public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
IStatusLabelTextProvider statusLabelTextProvider)
: base(GetPositionBasedOnWindowSize(clientWindowSizeProvider), Constants.FontSize07)
{
_statusLabelTextProvider = statusLabelTextProvider;
}
public override void Update(GameTime gameTime)
{
if (Text != _statusLabelTextProvider.StatusText)
{
Text = _statusLabelTextProvider.StatusText;
Visible = true;
}
if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
Visible = false;
base.Update(gameTime);
}
private static Rectangle GetPositionBasedOnWindowSize(IClientWindowSizeProvider clientWindowSizeProvider)
{
return new Rectangle(97, clientWindowSizeProvider.Height - 25, 1, 1);
}
}
}
| mit | C# |
76212a33067cc786fca9979d8aa5c65f84e1fea7 | Fix settings file load issue | Mpstark/articulate,BrunoBrux/ArticulateDVS | Articulate/Settings/Settings.cs | Articulate/Settings/Settings.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;
using System.Diagnostics;
namespace Articulate
{
[Serializable]
public class Settings
{
public Settings()
{
// Initialize default settings
ConfidenceMargin = 80;
PTTKey = System.Windows.Forms.Keys.None;
}
#region File Handling
public static Settings Load()
{
var filePath = Environment.ExpandEnvironmentVariables(@"%AppData%\Articulate\Settings.xml");
if (!File.Exists(filePath)) return new Settings();
try
{
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var serializer = new XmlSerializer(typeof(Settings));
return (Settings)serializer.Deserialize(fs);
}
}
catch (Exception ex)
{
Trace.Write(ex.Message);
return new Settings();
}
}
public void Save()
{
var filePath = Environment.ExpandEnvironmentVariables(@"%AppData%\Articulate\Settings.xml");
try
{
var parentDirectory = Environment.ExpandEnvironmentVariables(@"%AppData%\Articulate");
if (!Directory.Exists(parentDirectory))
Directory.CreateDirectory(parentDirectory);
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
var serializer = new XmlSerializer(typeof(Settings));
serializer.Serialize(fs, this);
}
}
catch(Exception ex)
{
Trace.Write(ex.Message);
}
}
#endregion
public int ConfidenceMargin
{ get; set; }
public System.Windows.Forms.Keys PTTKey
{ get; set; }
public bool PushToIgnore
{ get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;
using System.Diagnostics;
namespace Articulate
{
[Serializable]
public class Settings
{
public Settings()
{
// Initialize default settings
ConfidenceMargin = 80;
PTTKey = System.Windows.Forms.Keys.None;
}
#region File Handling
public static Settings Load()
{
var filePath = Environment.ExpandEnvironmentVariables(@"%AppData%\Articulate\Settings.xml");
if (!File.Exists(filePath)) return new Settings();
try
{
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var serializer = new XmlSerializer(typeof(Settings));
return (Settings)serializer.Deserialize(fs);
}
}
catch (Exception ex)
{
Trace.Write(ex.Message);
return new Settings();
}
}
public void Save()
{
var filePath = Environment.ExpandEnvironmentVariables(@"%AppData%\Articulate\Settings.xml");
try
{
var parentDirectory = Environment.ExpandEnvironmentVariables(@"%AppData%\Articulate");
if (!Directory.Exists(parentDirectory))
Directory.CreateDirectory(parentDirectory);
using (var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
var serializer = new XmlSerializer(typeof(Settings));
serializer.Serialize(fs, this);
}
}
catch(Exception ex)
{
Trace.Write(ex.Message);
}
}
#endregion
public int ConfidenceMargin
{ get; set; }
public System.Windows.Forms.Keys PTTKey
{ get; set; }
public bool PushToIgnore
{ get; set; }
}
}
| mit | C# |
0b51f66cd087eb0783da43fec8888b756d9f8449 | Switch to using ITorrentDetails instead of TorrentDetails for added torrent response type. This results in a null. Return type must be concrete. | dipeshc/BTDeploy | BTDeploy/Client.Commands/Add.cs | BTDeploy/Client.Commands/Add.cs | using ServiceStack.Service;
using ServiceStack.Common.Web;
using System.IO;
using BTDeploy.ServiceDaemon.TorrentClients;
using BTDeploy.ServiceDaemon;
using System.Linq;
using System.Threading;
using System;
using ServiceStack.ServiceClient.Web;
namespace BTDeploy.Client.Commands
{
public class Add : GeneralConsoleCommandBase
{
public string TorrentPath;
public string OuputDirectoryPath;
public bool Mirror = false;
public bool Wait = false;
public Add (IEnvironmentDetails environmentDetails, IRestClient client) : base(environmentDetails, client, "Adds a torrent to be deployed.")
{
HasRequiredOption ("t|torrent=", "Torrent deployment file path.", o => TorrentPath = o);
HasRequiredOption ("o|outputDirectory=", "Output directory path for deployment.", o => OuputDirectoryPath = o);
HasOption ("m|mirror", "Walks the output directory to make sure it mirrors the deployment. Any additional files will be deleted.", o => Mirror = o != null);
HasOption ("w|wait", "Wait for deployment to finish downloading before exiting.", o => Wait = o != null);
}
public override int Run (string[] remainingArguments)
{
var OutputDirectoryPathFull = Path.GetFullPath (OuputDirectoryPath);
var postUri = "/api/torrents?OutputDirectoryPath=" + OutputDirectoryPathFull + "&mirror=" + Mirror.ToString();
var addedTorrentDetails = Client.PostFile<TorrentDetails> (postUri, new FileInfo(TorrentPath), MimeTypes.GetMimeType (TorrentPath));
if (!Wait)
return 0;
var waitCommand = new Wait (EnvironmentDetails, Client);
return waitCommand.Run (new [] { addedTorrentDetails.Id });
}
}
} | using ServiceStack.Service;
using ServiceStack.Common.Web;
using System.IO;
using BTDeploy.ServiceDaemon.TorrentClients;
using BTDeploy.ServiceDaemon;
using System.Linq;
using System.Threading;
using System;
using ServiceStack.ServiceClient.Web;
namespace BTDeploy.Client.Commands
{
public class Add : GeneralConsoleCommandBase
{
public string TorrentPath;
public string OuputDirectoryPath;
public bool Mirror = false;
public bool Wait = false;
public Add (IEnvironmentDetails environmentDetails, IRestClient client) : base(environmentDetails, client, "Adds a torrent to be deployed.")
{
HasRequiredOption ("t|torrent=", "Torrent deployment file path.", o => TorrentPath = o);
HasRequiredOption ("o|outputDirectory=", "Output directory path for deployment.", o => OuputDirectoryPath = o);
HasOption ("m|mirror", "Walks the output directory to make sure it mirrors the deployment. Any additional files will be deleted.", o => Mirror = o != null);
HasOption ("w|wait", "Wait for deployment to finish downloading before exiting.", o => Wait = o != null);
}
public override int Run (string[] remainingArguments)
{
var OutputDirectoryPathFull = Path.GetFullPath (OuputDirectoryPath);
var postUri = "/api/torrents?OutputDirectoryPath=" + OutputDirectoryPathFull + "&mirror=" + Mirror.ToString();
var addedTorrentDetails = Client.PostFile<ITorrentDetails> (postUri, new FileInfo(TorrentPath), MimeTypes.GetMimeType (TorrentPath));
if (!Wait)
return 0;
var waitCommand = new Wait (EnvironmentDetails, Client);
return waitCommand.Run (new [] { addedTorrentDetails.Id });
}
}
} | mit | C# |
06cbae1c8366d35deb32d9d512ce58b34ab1e95e | Update RemoveMember.cs | GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples | iam/api/Access/RemoveMember.cs | iam/api/Access/RemoveMember.cs | // Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START iam_modify_policy_remove_member]
using System.Linq;
using Google.Apis.CloudResourceManager.v1.Data;
public partial class AccessManager
{
public static Policy RemoveMember(Policy policy, string role, string member)
{
var binding = policy.Bindings.First(x => x.Role == role);
if(binding.Members != null && binding.Members.Contains(member))
{
binding.Members.Remove(member);
}
return policy;
}
}
// [END iam_modify_policy_remove_member]
| // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [START iam_modify_policy_remove_member]
using System.Linq;
using Google.Apis.CloudResourceManager.v1.Data;
public partial class AccessManager
{
public static Policy RemoveMember(Policy policy, string role, string member)
{
var binding = policy.Bindings.First(x => x.Role == role);
if(binding.Members != null && binding.Members.Contains(member))
{
binding.Members.Remove(member);
}
return policy;
}
}
// [END iam_modify_policy_remove_member]
| apache-2.0 | C# |
7d87a052bf6dd62bee85a5938f8858c973ae4bc4 | Change Pivorama Icon | pellea/waslibs,janabimustafa/waslibs,janabimustafa/waslibs,wasteam/waslibs,janabimustafa/waslibs,wasteam/waslibs,wasteam/waslibs,pellea/waslibs,pellea/waslibs | samples/AppStudio.Uwp.Samples/Pages/Pivorama/PivoramaPage.xaml.cs | samples/AppStudio.Uwp.Samples/Pages/Pivorama/PivoramaPage.xaml.cs | using System;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace AppStudio.Uwp.Samples
{
[SamplePage(Category = "Layout", Name = "Pivorama", Order = 10)]
public sealed partial class PivoramaPage : SamplePage
{
public PivoramaPage()
{
this.InitializeComponent();
this.DataContext = this;
}
public override string Caption
{
get { return "Pivorama Control"; }
}
#region Items
public ObservableCollection<object> Items
{
get { return (ObservableCollection<object>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<object>), typeof(PivoramaPage), new PropertyMetadata(null));
#endregion
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Items = new ObservableCollection<object>(new DevicesDataSource().GetGroupedItems());
base.OnNavigatedTo(e);
}
protected override void OnSettings()
{
AppShell.Current.Shell.ShowRightPane(new PivoramaSettings() { DataContext = control });
}
}
}
| using System;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace AppStudio.Uwp.Samples
{
[SamplePage(Category = "Layout", Name = "Pivorama", IconPath = "ms-appx:///Assets/Icons/Pivorama.png", Order = 10)]
public sealed partial class PivoramaPage : SamplePage
{
public PivoramaPage()
{
this.InitializeComponent();
this.DataContext = this;
}
public override string Caption
{
get { return "Pivorama Control"; }
}
#region Items
public ObservableCollection<object> Items
{
get { return (ObservableCollection<object>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<object>), typeof(PivoramaPage), new PropertyMetadata(null));
#endregion
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Items = new ObservableCollection<object>(new DevicesDataSource().GetGroupedItems());
base.OnNavigatedTo(e);
}
protected override void OnSettings()
{
AppShell.Current.Shell.ShowRightPane(new PivoramaSettings() { DataContext = control });
}
}
}
| mit | C# |
0034c7a8eef8928961a70c3cf219a99a78167267 | Handle ObjectDisposedException just in case we do end up trying to read properties of a closed message | Microsoft/ApplicationInsights-SDK-Labs | WCF/Shared/Implementation/WcfExtensions.cs | WCF/Shared/Implementation/WcfExtensions.cs | using System;
using System.ServiceModel.Channels;
namespace Microsoft.ApplicationInsights.Wcf.Implementation
{
internal static class WcfExtensions
{
public static HttpRequestMessageProperty GetHttpRequestHeaders(this IOperationContext operation)
{
try
{
if ( operation.HasIncomingMessageProperty(HttpRequestMessageProperty.Name) )
{
return (HttpRequestMessageProperty)operation.GetIncomingMessageProperty(HttpRequestMessageProperty.Name);
}
} catch ( ObjectDisposedException )
{
// WCF message is already disposed, just avoid it
}
return null;
}
public static HttpResponseMessageProperty GetHttpResponseHeaders(this IOperationContext operation)
{
try
{
if ( operation.HasOutgoingMessageProperty(HttpResponseMessageProperty.Name) )
{
return (HttpResponseMessageProperty)operation.GetOutgoingMessageProperty(HttpResponseMessageProperty.Name);
}
} catch ( ObjectDisposedException )
{
// WCF message is already disposed, just avoid it
}
return null;
}
}
}
| using System;
using System.ServiceModel.Channels;
namespace Microsoft.ApplicationInsights.Wcf.Implementation
{
internal static class WcfExtensions
{
public static HttpRequestMessageProperty GetHttpRequestHeaders(this IOperationContext operation)
{
if ( operation.HasIncomingMessageProperty(HttpRequestMessageProperty.Name) )
{
return (HttpRequestMessageProperty)operation.GetIncomingMessageProperty(HttpRequestMessageProperty.Name);
}
return null;
}
public static HttpResponseMessageProperty GetHttpResponseHeaders(this IOperationContext operation)
{
if ( operation.HasOutgoingMessageProperty(HttpResponseMessageProperty.Name) )
{
return (HttpResponseMessageProperty)operation.GetOutgoingMessageProperty(HttpResponseMessageProperty.Name);
}
return null;
}
}
}
| mit | C# |
6fff15fe69eedf7feee0424f728a9c2b1f0a702a | Fix GetSimplestName() | chkn/Tempest | Desktop/Tempest/TypeExtensions.cs | Desktop/Tempest/TypeExtensions.cs | //
// TypeExtensions.cs
//
// Author:
// Eric Maupin <[email protected]>
//
// Copyright (c) 2011-2013 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace Tempest
{
public static class TypeExtensions
{
public static string GetSimplestName (this Type self)
{
if (self == null)
throw new ArgumentNullException ("self");
var typeInfo = self.GetTypeInfo();
if (typeInfo.Assembly == mscorlib || typeInfo.Assembly == Tempest)
return self.FullName;
#if !NETFX_CORE && !SILVERLIGHT
if (!typeInfo.Assembly.GlobalAssemblyCache)
return String.Format ("{0}, {1}", self.FullName, typeInfo.Assembly.GetName().Name);
#endif
return self.AssemblyQualifiedName;
}
#if !NETFX_CORE
public static Type GetTypeInfo (this Type self)
{
return self;
}
#else
public static bool IsAssignableFrom (this Type baseType, Type derivedType)
{
return baseType.GetTypeInfo().IsAssignableFrom (derivedType.GetTypeInfo());
}
public static IEnumerable<Type> GetTypes (this Assembly self)
{
return self.DefinedTypes.Select (ti => ti.BaseType);
}
public static ConstructorInfo GetConstructor (this Type self, Type[] parameterTypes)
{
foreach (ConstructorInfo constructor in self.GetTypeInfo().DeclaredConstructors)
{
ParameterInfo[] parameters = constructor.GetParameters();
if (parameters.Length != parameterTypes.Length)
continue;
bool match = true;
for (int i = 0; i < parameters.Length; i++)
{
if (parameterTypes[i] != parameters[i].ParameterType)
{
match = false;
break;
}
}
if (match)
return constructor;
}
return null;
}
#endif
private static readonly Assembly Tempest = typeof (TypeExtensions).GetTypeInfo().Assembly;
private static readonly Assembly mscorlib = typeof (string).GetTypeInfo().Assembly;
}
} | //
// TypeExtensions.cs
//
// Author:
// Eric Maupin <[email protected]>
//
// Copyright (c) 2011-2013 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace Tempest
{
public static class TypeExtensions
{
public static string GetSimplestName (this Type self)
{
if (self == null)
throw new ArgumentNullException ("self");
var typeInfo = self.GetTypeInfo();
if (typeInfo.Assembly == mscorlib || typeInfo.Assembly == Tempest)
return self.FullName;
#if !NETFX_CORE
if (!typeInfo.Assembly.GlobalAssemblyCache)
return String.Format ("{0}, {1}", self.FullName, typeInfo.Assembly.GetName().Name);
#endif
return self.AssemblyQualifiedName;
}
#if !NETFX_CORE
public static Type GetTypeInfo (this Type self)
{
return self;
}
#else
public static bool IsAssignableFrom (this Type baseType, Type derivedType)
{
return baseType.GetTypeInfo().IsAssignableFrom (derivedType.GetTypeInfo());
}
public static IEnumerable<Type> GetTypes (this Assembly self)
{
return self.DefinedTypes.Select (ti => ti.BaseType);
}
public static ConstructorInfo GetConstructor (this Type self, Type[] parameterTypes)
{
foreach (ConstructorInfo constructor in self.GetTypeInfo().DeclaredConstructors)
{
ParameterInfo[] parameters = constructor.GetParameters();
if (parameters.Length != parameterTypes.Length)
continue;
bool match = true;
for (int i = 0; i < parameters.Length; i++)
{
if (parameterTypes[i] != parameters[i].ParameterType)
{
match = false;
break;
}
}
if (match)
return constructor;
}
return null;
}
#endif
private static readonly Assembly Tempest = typeof (TypeExtensions).GetTypeInfo().Assembly;
private static readonly Assembly mscorlib = typeof (string).GetTypeInfo().Assembly;
}
} | mit | C# |
bb0f07ea52e8814296aeb2283cf75674c382e402 | Delete TODO from ByteArrayHelpers (#27806) | shimingsg/corefx,Jiayili1/corefx,Jiayili1/corefx,ViktorHofer/corefx,Jiayili1/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,mmitche/corefx,ericstj/corefx,ptoonen/corefx,mmitche/corefx,ViktorHofer/corefx,mmitche/corefx,ericstj/corefx,ericstj/corefx,wtgodbe/corefx,mmitche/corefx,Jiayili1/corefx,BrennanConroy/corefx,ptoonen/corefx,shimingsg/corefx,ViktorHofer/corefx,mmitche/corefx,ptoonen/corefx,Jiayili1/corefx,BrennanConroy/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,ptoonen/corefx,wtgodbe/corefx,mmitche/corefx,ViktorHofer/corefx,BrennanConroy/corefx,ericstj/corefx,shimingsg/corefx,ptoonen/corefx,wtgodbe/corefx,shimingsg/corefx,Jiayili1/corefx,ViktorHofer/corefx,ericstj/corefx,mmitche/corefx,Jiayili1/corefx,ptoonen/corefx,wtgodbe/corefx,shimingsg/corefx,ptoonen/corefx | src/System.Net.Http/src/System/Net/Http/ByteArrayHelpers.cs | src/System.Net.Http/src/System/Net/Http/ByteArrayHelpers.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.Diagnostics;
namespace System
{
internal static class ByteArrayHelpers
{
internal static bool EqualsOrdinalAsciiIgnoreCase(string left, ReadOnlySpan<byte> right)
{
Debug.Assert(left != null, "Expected non-null string");
if (left.Length != right.Length)
{
return false;
}
for (int i = 0; i < left.Length; i++)
{
uint charA = left[i];
uint charB = right[i];
unchecked
{
// We're only interested in ASCII characters here.
if ((charA - 'a') <= ('z' - 'a'))
charA -= ('a' - 'A');
if ((charB - 'a') <= ('z' - 'a'))
charB -= ('a' - 'A');
}
if (charA != charB)
{
return false;
}
}
return true;
}
}
}
| // 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.Diagnostics;
namespace System
{
internal static class ByteArrayHelpers
{
// TODO #21395:
// Replace with the MemoryExtensions implementation of Equals once it's available
internal static bool EqualsOrdinalAsciiIgnoreCase(string left, ReadOnlySpan<byte> right)
{
Debug.Assert(left != null, "Expected non-null string");
if (left.Length != right.Length)
{
return false;
}
for (int i = 0; i < left.Length; i++)
{
uint charA = left[i];
uint charB = right[i];
unchecked
{
// We're only interested in ASCII characters here.
if ((charA - 'a') <= ('z' - 'a'))
charA -= ('a' - 'A');
if ((charB - 'a') <= ('z' - 'a'))
charB -= ('a' - 'A');
}
if (charA != charB)
{
return false;
}
}
return true;
}
}
}
| mit | C# |
cc3f85b419b109e48cc629094e78cb70463d2514 | Add Reason of Disconnection | Michitaro-Naito/GameServer | GameServer/Lobby/Lobby_Utility.cs | GameServer/Lobby/Lobby_Utility.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameServer
{
partial class Lobby
{
/// <summary>
/// Kicks Player from this server.
/// </summary>
/// <param name="userId"></param>
void Kick(string userId)
{
// Kicks from Room
_rooms.ForEach(r => r.Kick(userId));
// Kicks from Lobby
var keysToRemove = new List<string>();
_players.Where(en => en.Value.userId == userId).ToList().ForEach(en =>
{
keysToRemove.Add(en.Key);
en.Value.Client.gotDisconnectionRequest("ゲームから切断されました。別の画面を開いたり端末をスリープモードにすると発生することがあります。");
});
keysToRemove.ForEach(key =>
{
_players.Remove(key);
_playersInLobby.Remove(key);
_playersInGame.Remove(key);
});
}
void BringPlayerToRoom(Player p, int roomId, string password)
{
var room = _rooms.FirstOrDefault(r => r.roomId == roomId);
if (room == null)
{
p.GotSystemMessage("Room not found:" + roomId);
return;
}
if (p.Character == null)
{
p.GotSystemMessage("Failded to join Room. Character not selected.");
return;
}
_rooms.ForEach(r => r.Queue(new RoomCommand.RemovePlayer(){ ConnectionId = p.connectionId, Sender = GetPlayer(p.connectionId) }));
room.Queue(new RoomCommand.AddCharacter() {
ConnectionId = p.connectionId,
Sender = GetPlayer(p.connectionId),
Character = p.Character,
Password = password
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameServer
{
partial class Lobby
{
/// <summary>
/// Kicks Player from this server.
/// </summary>
/// <param name="userId"></param>
void Kick(string userId)
{
// Kicks from Room
_rooms.ForEach(r => r.Kick(userId));
// Kicks from Lobby
var keysToRemove = new List<string>();
_players.Where(en => en.Value.userId == userId).ToList().ForEach(en =>
{
keysToRemove.Add(en.Key);
en.Value.Client.gotDisconnectionRequest();
});
keysToRemove.ForEach(key =>
{
_players.Remove(key);
_playersInLobby.Remove(key);
_playersInGame.Remove(key);
});
}
void BringPlayerToRoom(Player p, int roomId, string password)
{
var room = _rooms.FirstOrDefault(r => r.roomId == roomId);
if (room == null)
{
p.GotSystemMessage("Room not found:" + roomId);
return;
}
if (p.Character == null)
{
p.GotSystemMessage("Failded to join Room. Character not selected.");
return;
}
_rooms.ForEach(r => r.Queue(new RoomCommand.RemovePlayer(){ ConnectionId = p.connectionId, Sender = GetPlayer(p.connectionId) }));
room.Queue(new RoomCommand.AddCharacter() {
ConnectionId = p.connectionId,
Sender = GetPlayer(p.connectionId),
Character = p.Character,
Password = password
});
}
}
}
| mit | C# |
428a978a852e26c7574f252c6035daadfd0a2f90 | Update Immutability | axelheer/nein-math | test/NeinMath.Tests/Immutability.cs | test/NeinMath.Tests/Immutability.cs | using System;
using Xunit;
namespace NeinMath.Tests
{
public static class Immutability
{
public static IDisposable Guard<T>(T v0)
{
return new ImmutabilityGuard<T>(v0);
}
public static IDisposable Guard<T>(T v0, T v1)
{
return new ImmutabilityGuard<T>(v0, v1);
}
public static IDisposable Guard<T>(T v0, T v1, T v2)
{
return new ImmutabilityGuard<T>(v0, v1, v2);
}
sealed class ImmutabilityGuard<T> : IDisposable
{
readonly T v0;
readonly T v1;
readonly T v2;
readonly string t0;
readonly string t1;
readonly string t2;
public ImmutabilityGuard(T v0)
: this(v0, default(T))
{
}
public ImmutabilityGuard(T v0, T v1)
: this(v0, v1, default(T))
{
}
public ImmutabilityGuard(T v0, T v1, T v2)
{
t0 = v0?.ToString();
t1 = v1?.ToString();
t2 = v2?.ToString();
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
}
public void Dispose()
{
Assert.Equal(t0, v0?.ToString());
Assert.Equal(t1, v1?.ToString());
Assert.Equal(t2, v2?.ToString());
}
}
}
}
| using System;
using Xunit;
namespace NeinMath.Tests
{
public sealed class Immutability : IDisposable
{
readonly Integer left;
readonly Integer right;
readonly Integer other;
readonly string leftValue;
readonly string rightValue;
readonly string otherValue;
Immutability(Integer value)
: this(value, default(Integer))
{
}
Immutability(Integer left, Integer right)
: this(left, right, default(Integer))
{
}
Immutability(Integer left, Integer right, Integer other)
{
leftValue = left.ToString();
rightValue = right.ToString();
otherValue = other.ToString();
this.left = left;
this.right = right;
this.other = other;
}
public static IDisposable Guard(Integer value)
{
return new Immutability(value);
}
public static IDisposable Guard(Integer left, Integer right)
{
return new Immutability(left, right);
}
public static IDisposable Guard(Integer left, Integer right, Integer other)
{
return new Immutability(left, right, other);
}
public void Dispose()
{
Assert.Equal(leftValue, left.ToString());
Assert.Equal(rightValue, right.ToString());
Assert.Equal(otherValue, other.ToString());
}
}
}
| mit | C# |
4e462cdc8683c4848b161d3986bf17fce86567da | Fix #22 | monkey3310/netcore-teamcity-api | NetCoreTeamCity/Api/TeamCity.cs | NetCoreTeamCity/Api/TeamCity.cs | using NetCoreTeamCity.Clients;
using NetCoreTeamCity.Services;
namespace NetCoreTeamCity.Api
{
public class TeamCity : ITeamCity
{
public TeamCity(string host, string userName, string password, bool usingSSL = true)
{
var connectionConfig = new TeamCityConnectionSettingsBuilder().ToHost(host).UsingSSL(usingSSL).AsUser(userName, password).Build();
var bootstrapper = new BootStrapper(connectionConfig);
Builds = bootstrapper.Get<IBuildService>();
QueuedBuilds = bootstrapper.Get<IQueuedBuildService>();
Changes = bootstrapper.Get<IChangeService>();
}
public IBuildService Builds { get; }
public IQueuedBuildService QueuedBuilds { get; }
public IChangeService Changes { get; }
}
}
| using NetCoreTeamCity.Clients;
using NetCoreTeamCity.Services;
namespace NetCoreTeamCity.Api
{
public class TeamCity : ITeamCity
{
public TeamCity(string host, string userName, string password, bool usingSSL = true)
{
var connectionConfig = new TeamCityConnectionSettingsBuilder().ToHost(host).UsingSSL().AsUser(userName, password).Build();
var bootstrapper = new BootStrapper(connectionConfig);
Builds = bootstrapper.Get<IBuildService>();
QueuedBuilds = bootstrapper.Get<IQueuedBuildService>();
Changes = bootstrapper.Get<IChangeService>();
}
public IBuildService Builds { get; }
public IQueuedBuildService QueuedBuilds { get; }
public IChangeService Changes { get; }
}
}
| mit | C# |
cb1e88d26fab2a7472ac051543540ed801adf299 | Test console Run method updated | mecitsem/hashtagbot,mecitsem/hashtagbot,mecitsem/Arf-HashtagBot,mecitsem/hashtagbot,mecitsem/Arf-HashtagBot | HashtagBot/Arf.Console/Program.cs | HashtagBot/Arf.Console/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Arf.Services;
using Microsoft.ProjectOxford.Vision.Contract;
namespace Arf.Console
{
class Program
{
public static bool IsProcessing;
public static void Main(string[] args)
{
System.Console.ForegroundColor = ConsoleColor.Yellow;
System.Console.WriteLine("Please write image Url or local path");
while (true)
{
if (IsProcessing) continue;
System.Console.ResetColor();
var imgPath = System.Console.ReadLine();
Run(imgPath);
System.Console.ForegroundColor = ConsoleColor.DarkGray;
System.Console.WriteLine("It takes a few time.Please wait!");
System.Console.ResetColor();
}
}
public static async void Run(string imgPath)
{
IsProcessing = true;
var isUpload = imgPath != null && !imgPath.StartsWith("http");
var service = new VisionService();
var analysisResult = isUpload
? await service.UploadAndDescripteImage(imgPath)
: await service.DescripteUrl(imgPath);
System.Console.ForegroundColor = ConsoleColor.DarkGreen;
System.Console.WriteLine(string.Join(" ", analysisResult.Description.Tags.Select(s => $"#{s}")));
System.Console.ResetColor();
IsProcessing = false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Arf.Services;
using Microsoft.ProjectOxford.Vision.Contract;
namespace Arf.Console
{
class Program
{
public static bool IsProcessing;
public static void Main(string[] args)
{
System.Console.ForegroundColor = ConsoleColor.Yellow;
System.Console.WriteLine("Please write image Url or local path");
while (true)
{
if (IsProcessing) continue;
System.Console.ResetColor();
var imgPath = System.Console.ReadLine();
Run(imgPath);
System.Console.ForegroundColor = ConsoleColor.DarkGray;
System.Console.WriteLine("It takes a few time.Please wait!");
System.Console.ResetColor();
}
}
public static async void Run(string imgPath)
{
IsProcessing = true;
var isUpload = imgPath != null && !imgPath.StartsWith("http");
var service = new VisionService();
var analysisResult = isUpload
? await service.UploadAndDescripteImage(imgPath)
: await service.DescripteUrl(imgPath);
System.Console.ForegroundColor = ConsoleColor.DarkGreen;
System.Console.WriteLine(string.Join(" ", analysisResult.Description.Tags.Select(s => s = "#" + s)));
System.Console.ResetColor();
IsProcessing = false;
}
}
}
| mit | C# |
2a92639712cc38230d2ee8174edfc31263f74c9d | Add layer mask support to GetEncapsBounds. | jorgenpt/unity-utilities | Plugins/GameObjectExtensions.cs | Plugins/GameObjectExtensions.cs | using UnityEngine;
using System.Linq;
namespace ExtensionMethods
{
public static class GameObjectExtensions
{
public static int RecursiveLayerMask(this GameObject go)
{
LayerMask mask = 1 << go.layer;
foreach (Transform t in go.transform)
{
mask |= t.gameObject.RecursiveLayerMask ();
}
return mask;
}
public static Bounds GetEncapsulatingBounds (this GameObject go, LayerMask mask)
{
var renderers =
from r in go.GetComponentsInChildren<Renderer> ()
where (mask & r.gameObject.layer) != 0
select r;
if (renderers.Count () == 0)
return new Bounds (Vector3.zero, Vector3.zero);
Bounds bounds = renderers.First ().bounds;
renderers = renderers.Skip (1);
foreach (var renderer in renderers)
bounds.Encapsulate (renderer.bounds);
return bounds;
}
public static Bounds GetEncapsulatingBounds (this GameObject go)
{
return go.GetEncapsulatingBounds (~0);
}
public static Bounds GetEncapsulatingLocalBounds (this GameObject go)
{
Bounds bounds = new Bounds (Vector3.zero, Vector3.zero);
MeshFilter mf = go.GetComponent<MeshFilter> ();
if (mf != null && mf.sharedMesh != null)
bounds = mf.sharedMesh.bounds;
else if (go.renderer is SkinnedMeshRenderer)
bounds = ((SkinnedMeshRenderer)go.renderer).localBounds;
foreach (MeshFilter m in go.GetComponentsInChildren<MeshFilter> ())
bounds.Encapsulate (m.sharedMesh.bounds);
foreach (SkinnedMeshRenderer m in go.GetComponentsInChildren<SkinnedMeshRenderer> ())
bounds.Encapsulate (m.localBounds);
return bounds;
}
}
}
| using UnityEngine;
namespace ExtensionMethods
{
public static class GameObjectExtensions
{
public static int RecursiveLayerMask(this GameObject go)
{
LayerMask mask = 1 << go.layer;
foreach (Transform t in go.transform)
{
mask |= t.gameObject.RecursiveLayerMask ();
}
return mask;
}
public static Bounds GetEncapsulatingBounds (this GameObject go)
{
Renderer[] renderers = go.GetComponentsInChildren<Renderer> ();
if (renderers.Length == 0)
return new Bounds (Vector3.zero, Vector3.zero);
Bounds bounds = renderers[0].bounds;
for (int i = 1; i < renderers.Length; ++i)
bounds.Encapsulate (renderers[i].bounds);
return bounds;
}
public static Bounds GetEncapsulatingLocalBounds (this GameObject go)
{
Bounds bounds = new Bounds (Vector3.zero, Vector3.zero);
MeshFilter mf = go.GetComponent<MeshFilter> ();
if (mf != null && mf.sharedMesh != null)
bounds = mf.sharedMesh.bounds;
else if (go.renderer is SkinnedMeshRenderer)
bounds = ((SkinnedMeshRenderer)go.renderer).localBounds;
foreach (MeshFilter m in go.GetComponentsInChildren<MeshFilter> ())
bounds.Encapsulate (m.sharedMesh.bounds);
foreach (SkinnedMeshRenderer m in go.GetComponentsInChildren<SkinnedMeshRenderer> ())
bounds.Encapsulate (m.localBounds);
return bounds;
}
}
}
| mit | C# |
f9492a2fe7e398366c0f697e634e01ee95e62141 | Make debugging output show up on release builds | godarklight/DarkMultiPlayer,81ninja/DarkMultiPlayer,Dan-Shields/DarkMultiPlayer,rewdmister4/rewd-mod-packs,dsonbill/DarkMultiPlayer,Kerbas-ad-astra/DarkMultiPlayer,Sanmilie/DarkMultiPlayer,RockyTV/DarkMultiPlayer,RockyTV/DarkMultiPlayer,godarklight/DarkMultiPlayer,81ninja/DarkMultiPlayer | Server/Log.cs | Server/Log.cs | using System;
namespace DarkMultiPlayerServer
{
public class DarkLog
{
public static void Debug(string message)
{
float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f;
Console.WriteLine("[" + currentTime + "] Debug: " + message);
}
public static void Normal(string message)
{
float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f;
Console.WriteLine("[" + currentTime + "] Normal: " + message);
}
}
}
| using System;
namespace DarkMultiPlayerServer
{
public class DarkLog
{
public static void Debug(string message)
{
#if DEBUG
float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f;
Console.WriteLine("[" + currentTime + "] Debug: " + message);
#endif
}
public static void Normal(string message)
{
float currentTime = Server.serverClock.ElapsedMilliseconds / 1000f;
Console.WriteLine("[" + currentTime + "] Normal: " + message);
}
}
}
| mit | C# |
bec7051da0989499aff000a8ee5bbf901f863d0f | fix QueryUtils bug | oelite/RESTme | OElite.Restme.Utils/QueryUtils.cs | OElite.Restme.Utils/QueryUtils.cs | using System.Collections.Generic;
using System.Net;
namespace OElite
{
public static class QueryUtils
{
public static Dictionary<string, string> IdentifyQueryParams(this string value, bool noQuestionMark = false)
{
Dictionary<string, string> result = new Dictionary<string, string>();
if (!noQuestionMark)
{
var paramIndex = value?.IndexOf('?');
if (paramIndex < 0) return result;
value = value.Substring(paramIndex.GetValueOrDefault() + 1);
}
var paramPairs = value.Split('&');
foreach (var pair in paramPairs)
{
var pairArray = pair.Split('=');
if (pairArray?.Length != 2) continue;
var kKey = pairArray[0].Trim();
var kValue = WebUtility.UrlDecode(pairArray[1].Trim());
//note: BUG Identified: when multiple parameters with same name appears this will throw an exception
result.Add(kKey, kValue);
}
return result;
}
public static string ParseIntoQueryString(this Dictionary<string, string> values,
bool includeQuestionMark = true, bool encode = true)
{
string result = null;
if (values?.Count > 0)
{
var index = 0;
foreach (var k in values.Keys)
{
result = index == 0
? $"{k}={(encode ? WebUtility.UrlEncode(values[k]) : values[k])}"
: result + $"&{k}={(encode ? WebUtility.UrlEncode(values[k]) : values[k])}";
index++;
}
}
if (includeQuestionMark && result.IsNotNullOrEmpty())
result = $"?{result}";
return result;
}
}
} | using System.Collections.Generic;
using System.Net;
namespace OElite
{
public static class QueryUtils
{
public static Dictionary<string, string> IdentifyQueryParams(this string value)
{
Dictionary<string, string> result = new Dictionary<string, string>();
var paramIndex = value?.IndexOf('?');
if (paramIndex < 0) return result;
value = value.Substring(paramIndex.GetValueOrDefault() + 1);
var paramPairs = value.Split('&');
foreach (var pair in paramPairs)
{
var pairArray = pair.Split('=');
if (pairArray?.Length != 2) continue;
var kKey = pairArray[0].Trim();
var kValue = WebUtility.UrlDecode(pairArray[1].Trim());
//note: BUG Identified: when multiple parameters with same name appears this will throw an exception
result.Add(kKey, kValue);
}
return result;
}
public static string ParseIntoQueryString(this Dictionary<string, string> values,
bool includeQuestionMark = true, bool encode = true)
{
string result = null;
if (values?.Count > 0)
{
var index = 0;
foreach (var k in values.Keys)
{
result = index == 0
? $"{k}={(encode ? WebUtility.UrlEncode(values[k]) : values[k])}"
: result + $"&{k}={(encode ? WebUtility.UrlEncode(values[k]) : values[k])}";
index++;
}
}
if (includeQuestionMark && result.IsNotNullOrEmpty())
result = $"?{result}";
return result;
}
}
} | mit | C# |
111eb0c139938fbf3ffbbf88254eee29d64793a1 | Remove gradient clipping background | mmoening/MatterControl,jlewin/MatterControl,jlewin/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl | PartPreviewWindow/OverflowMenu.cs | PartPreviewWindow/OverflowMenu.cs | /*
Copyright (c) 2018, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System.IO;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class OverflowMenu : PopupMenuButton
{
public OverflowMenu(IconColor iconColor = IconColor.Theme)
: base(new ImageWidget(
AggContext.StaticData.LoadIcon(Path.Combine("ViewTransformControls", "overflow.png"),
32,
32,
iconColor))
{
HAnchor = HAnchor.Left
},
ApplicationController.Instance.Theme)
{
this.ToolTipText = "More...".Localize();
}
public OverflowMenu(GuiWidget viewWidget, ThemeConfig theme)
: base(viewWidget, theme)
{
}
}
} | /*
Copyright (c) 2017, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.IO;
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class OverflowMenu : PopupMenuButton
{
private ImageBuffer gradientBackground;
public OverflowMenu(IconColor iconColor = IconColor.Theme)
: base(new ImageWidget(AggContext.StaticData.LoadIcon(Path.Combine("ViewTransformControls", "overflow.png"), 32, 32, iconColor)) { Margin = new BorderDouble(left: 5), HAnchor = HAnchor.Left }, ApplicationController.Instance.Theme)
{
this.ToolTipText = "More...".Localize();
}
public OverflowMenu(GuiWidget viewWidget, ThemeConfig theme)
: base(viewWidget, theme)
{
}
public int GradientDistance { get; set; } = 5;
public override void OnDrawBackground(Graphics2D graphics2D)
{
if (gradientBackground != null)
{
graphics2D.Render(gradientBackground, this.LocalBounds.Left, 0);
}
else
{
base.OnDrawBackground(graphics2D);
}
}
public override void OnLoad(EventArgs args)
{
base.OnLoad(args);
if (this.GradientDistance > 0)
{
gradientBackground = agg_basics.TrasparentToColorGradientX(
(int)this.LocalBounds.Width + this.GradientDistance,
(int)this.LocalBounds.Height,
this.BackgroundColor,
this.GradientDistance);
gradientBackground.SetRecieveBlender(new BlenderPreMultBGRA());
}
}
}
} | bsd-2-clause | C# |
843b268c741368779c60ec5f607ca1ffcd4f66e6 | Remove RandomTrace stuff from Main | lou1306/CIV,lou1306/CIV | CIV/Program.cs | CIV/Program.cs | using static System.Console;
using CIV.Ccs;
using CIV.Hml;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var hmlText = "[[ack]][[ack]][[ack]](<<ack>>tt and [[freeAll]]ff)";
var prova = HmlFacade.ParseAll(hmlText);
WriteLine(prova.Check(processes["Prison"]));
}
}
}
| using static System.Console;
using CIV.Ccs;
using CIV.Interfaces;
namespace CIV
{
class Program
{
static void Main(string[] args)
{
var text = System.IO.File.ReadAllText(args[0]);
var processes = CcsFacade.ParseAll(text);
var trace = CcsFacade.RandomTrace(processes["Prison"], 450);
foreach (var action in trace)
{
WriteLine(action);
}
}
}
}
| mit | C# |
70c20db82949c86f84f5d32f6c4af2282c353a59 | Update PvcSqlTests.cs | robbihun/pvc-sql | tests/Pvc.Sql.Tests/PvcSqlTests.cs | tests/Pvc.Sql.Tests/PvcSqlTests.cs | using NUnit.Framework;
using PvcPlugins;
using System;
using System.Linq;
namespace Pvc.Sql.Tests
{
[TestFixture]
public class PvcSqlTests
{
[Test]
public void CanExecuteSqlScript()
{
var pvc = new PvcCore.Pvc();
var source = pvc.Source("*.sql");
Assert.DoesNotThrow(() =>
{
source.Pipe((sources) =>
{
foreach (var src in sources)
{
Console.WriteLine(src.StreamName);
}
Assert.AreEqual(1, sources.Count());
return sources;
});
source.Pipe(new PvcSql(
connectionString: "Data Source=.;Initial Catalog=PVCSandbox;Integrated Security=True",
providerName: "MsSql"));
});
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using PvcCore;
using PvcPlugins;
namespace Pvc.Sql.Tests
{
[TestFixture]
public class PvcSqlTests
{
[Test]
public void CanExecuteSqlScript()
{
var pvc = new PvcCore.Pvc();
var source = pvc.Source("*.sql");
Assert.DoesNotThrow(() =>
{
source.Pipe((sources) =>
{
foreach (var src in sources)
{
Console.WriteLine(src.StreamName);
}
Assert.AreEqual(1, sources.Count());
return sources;
});
source.Pipe(new PvcSql(
connectionString: "Data Source=.;Initial Catalog=PVCSandbox;Integrated Security=True",
providerName: "System.Data.SqlClient"));
});
}
}
}
| apache-2.0 | C# |
7fd1652a36e20618c0904bd89f53afbd857a2dd0 | Update ApiConnection.cs | shopdoktor/shopware-csharp-api-connector,hkcomputer/shopware-csharp-api-connector | ShopwareApiTests/ApiConnection.cs | ShopwareApiTests/ApiConnection.cs | using Lenz.ShopwareApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShopwareApiTests
{
class ApiConnection
{
public static ShopwareApi getDemoApi()
{
// URL, USERNAME, API-KEY
ShopwareApi shopwareApi = new ShopwareApi("", "", "");
return shopwareApi;
}
}
}
| using Lenz.ShopwareApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShopwareApiTests
{
class ApiConnection
{
public static ShopwareApi getDemoApi()
{
// URL, USERNAME, API-KEY
ShopwareApi shopwareApi = new ShopwareApi("https://www.shopapi.de/api/", "shopdoktor", "IcDDc7diFMT1rhd3ZoDPHsB6eaAFEE10EqJk5gny");
return shopwareApi;
}
}
}
| mit | C# |
d9ca9e51170113f5ca7194cd3267851631feb91f | add reference to dll | sebastus/AzureFunctionForSplunk | shared/obRelay.csx | shared/obRelay.csx | #r "Microsoft.Azure.Relay"
#load "newEvent.csx"
#load "getEnvironmentVariable.csx"
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Relay;
public static async Task obRelay(string[] standardizedEvents, TraceWriter log)
{
string newClientContent = "[";
foreach (string item in standardizedEvents)
{
if (newClientContent.Length != 1) newClientContent += ",";
newClientContent += item;
}
newClientContent += "]";
bool Done = false;
while (!Done)
{
try
{
Done = HybridAsync(newClientContent, log).GetAwaiter().GetResult();
}
catch (EndpointNotFoundException)
{
log.Info("Waiting...");
Thread.Sleep(1000);
}
catch (RelayException)
{
log.Info("Connection forcibly closed.");
}
catch (Exception ex)
{
log.Error("Error executing function: " + ex.Message);
}
}
}
static async Task<bool> HybridAsync(string newClientContent, TraceWriter log)
{
string RelayNamespace = getEnvironmentVariable("relayNamespace") + ".servicebus.windows.net";
string ConnectionName = getEnvironmentVariable("relayPath");
string KeyName = getEnvironmentVariable("policyName");
string Key = getEnvironmentVariable("policyKey");
if (RelayNamespace.Length == 0 || ConnectionName.Length == 0 || KeyName.Length == 0 || Key.Length == 0) {
log.Error("Values must be specified for RelayNamespace, relayPath, KeyName and Key.");
return true;
}
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
// Initiate the connection
var relayConnection = await client.CreateConnectionAsync();
log.Verbose("Connection accepted.");
int bufferSize = newClientContent.Length;
log.Info($"newClientContent byte count: {bufferSize}");
var writes = Task.Run(async () => {
var writer = new StreamWriter(relayConnection, Encoding.UTF8, bufferSize) { AutoFlush = true };
await writer.WriteAsync(newClientContent);
});
// Wait for both tasks to complete
await Task.WhenAll(writes);
await relayConnection.CloseAsync(CancellationToken.None);
log.Verbose("Connection closed.");
return true;
}
| #load "newEvent.csx"
#load "getEnvironmentVariable.csx"
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Relay;
public static async Task obRelay(string[] standardizedEvents, TraceWriter log)
{
string newClientContent = "[";
foreach (string item in standardizedEvents)
{
if (newClientContent.Length != 1) newClientContent += ",";
newClientContent += item;
}
newClientContent += "]";
bool Done = false;
while (!Done)
{
try
{
Done = HybridAsync(newClientContent, log).GetAwaiter().GetResult();
}
catch (EndpointNotFoundException)
{
log.Info("Waiting...");
Thread.Sleep(1000);
}
catch (RelayException)
{
log.Info("Connection forcibly closed.");
}
catch (Exception ex)
{
log.Error("Error executing function: " + ex.Message);
}
}
}
static async Task<bool> HybridAsync(string newClientContent, TraceWriter log)
{
string RelayNamespace = getEnvironmentVariable("relayNamespace") + ".servicebus.windows.net";
string ConnectionName = getEnvironmentVariable("relayPath");
string KeyName = getEnvironmentVariable("policyName");
string Key = getEnvironmentVariable("policyKey");
if (RelayNamespace.Length == 0 || ConnectionName.Length == 0 || KeyName.Length == 0 || Key.Length == 0) {
log.Error("Values must be specified for RelayNamespace, relayPath, KeyName and Key.");
return true;
}
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
var client = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
// Initiate the connection
var relayConnection = await client.CreateConnectionAsync();
log.Verbose("Connection accepted.");
int bufferSize = newClientContent.Length;
log.Info($"newClientContent byte count: {bufferSize}");
var writes = Task.Run(async () => {
var writer = new StreamWriter(relayConnection, Encoding.UTF8, bufferSize) { AutoFlush = true };
await writer.WriteAsync(newClientContent);
});
// Wait for both tasks to complete
await Task.WhenAll(writes);
await relayConnection.CloseAsync(CancellationToken.None);
log.Verbose("Connection closed.");
return true;
}
| mit | C# |
4e87d2eedf9be13d588540cc768114a8c3a4ed7f | Update version. | JetStream96/MinMaxHeap | src/MinMaxHeap/Properties/AssemblyInfo.cs | src/MinMaxHeap/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("MinMaxHeap")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MinMaxHeap")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("ee32e144-6658-4b16-8fb5-7a3be73f78c4")]
// 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.3.0")]
[assembly: AssemblyFileVersion("1.0.3.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MinMaxHeap")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MinMaxHeap")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("ee32e144-6658-4b16-8fb5-7a3be73f78c4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| unlicense | C# |
c9766565616d90b2f4ff5b76a01c06bcae60d877 | Fix typo in example comment. | andrewdavey/postal,ajbeaven/postal,hermanho/postal,andrewdavey/postal,vip32/postal,Lybecker/postal | src/MvcSample/Views/Emails/Example.cshtml | src/MvcSample/Views/Emails/Example.cshtml | To: @Model.To
From: [email protected]
Reply-To: [email protected]
Subject: @Model.Subject
@* NOTE: There MUST be a blank line after the headers and before the content. *@
Hello,
This email was generated using Postal for asp.net mvc on @Model.Date.ToShortDateString()
Message follows:
@Model.Message
Thanks! | To: @Model.To
From: [email protected]
Reply-To: [email protected]
Subject: @Model.Subject
@* NOTE: There MUST be a blank like after the headers and before the content. *@
Hello,
This email was generated using Postal for asp.net mvc on @Model.Date.ToShortDateString()
Message follows:
@Model.Message
Thanks! | mit | C# |
b7d9074b6857300d0540d1ce381a271d0666e0ea | Update TempRepoContext.cs | Particular/SyncOMatic | src/Tests/TempRepoContext.cs | src/Tests/TempRepoContext.cs | using System;
using System.Threading.Tasks;
using Octokit;
public class TempRepoContext :
IAsyncDisposable
{
Reference tempBranchReference;
public string TempBranchName;
string tempBranchRefName;
TempRepoContext(Reference tempBranchReference, string tempBranchName, string tempBranchRefName)
{
this.tempBranchReference = tempBranchReference;
TempBranchName = tempBranchName;
this.tempBranchRefName = tempBranchRefName;
}
public static async Task<TempRepoContext> Create(string tempBranchName)
{
var newReference = new NewReference($"refs/heads/{tempBranchName}", "af72f8e44eb53d26969b1316491a294f3401f203");
await Client.DeleteBranch(tempBranchName);
var tempBranchReference = await Client.GitHubClient.Git.Reference.Create("SimonCropp", "GitHubSync.TestRepository", newReference);
return new TempRepoContext(tempBranchReference, tempBranchName, $"refs/heads/{tempBranchName}");
}
public async Task VerifyPullRequest(string name)
{
var branch = await Client.GitHubClient.Repository.Branch.Get("SimonCropp", "GitHubSync.TestRepository", name);
ObjectApprover.Verify(branch);
}
public async ValueTask DisposeAsync()
{
await Client.DeleteBranch(TempBranchName);
}
} | using System;
using System.Linq;
using System.Threading.Tasks;
using Octokit;
public class TempRepoContext :
IAsyncDisposable
{
Reference tempBranchReference;
public string TempBranchName;
string tempBranchRefName;
TempRepoContext(Reference tempBranchReference, string tempBranchName, string tempBranchRefName)
{
this.tempBranchReference = tempBranchReference;
TempBranchName = tempBranchName;
this.tempBranchRefName = tempBranchRefName;
}
public static async Task<TempRepoContext> Create(string tempBranchName)
{
var newReference = new NewReference($"refs/heads/{tempBranchName}", "af72f8e44eb53d26969b1316491a294f3401f203");
await Client.DeleteBranch(tempBranchName);
var tempBranchReference = await Client.GitHubClient.Git.Reference.Create("SimonCropp", "GitHubSync.TestRepository", newReference);
return new TempRepoContext(tempBranchReference, tempBranchName, $"refs/heads/{tempBranchName}");
}
public async Task VerifyPullRequest(string name)
{
var branch = await Client.GitHubClient.Repository.Branch.Get("SimonCropp", "GitHubSync.TestRepository", name);
ObjectApprover.Verify(branch);
}
public async ValueTask DisposeAsync()
{
await Client.DeleteBranch(TempBranchName);
}
} | mit | C# |
e649f339853762efea035ab4c4d3a58f94832352 | Add Guard.Ensure | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | src/WeihanLi.Common/Guard.cs | src/WeihanLi.Common/Guard.cs | using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace WeihanLi.Common;
public static class Guard
{
public static T NotNull<T>([NotNull] T? t,
[CallerArgumentExpression("t")]
string? paramName = default)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(t, paramName);
#else
if (t is null)
{
throw new ArgumentNullException(paramName)
}
#endif
return t;
}
public static string NotNullOrEmpty([NotNull] string? str,
[CallerArgumentExpression("str")]
string? paramName = null)
{
NotNull(str, paramName);
if (str.Length == 0)
{
throw new ArgumentException("The argument can not be Empty", paramName);
}
return str;
}
public static string NotNullOrWhiteSpace([NotNull] string? str,
[CallerArgumentExpression("str")] string? paramName = null)
{
NotNull(str, paramName);
if (string.IsNullOrWhiteSpace(str))
{
throw new ArgumentException("The argument can not be WhiteSpace", paramName);
}
return str;
}
public static ICollection<T> NotEmpty<T>([NotNull] ICollection<T> collection, [CallerArgumentExpression("collection")] string? paramName = null)
{
NotNull(collection, paramName);
if (collection.Count == 0)
{
throw new ArgumentException("The collection could not be empty", paramName);
}
return collection;
}
public static T Ensure<T>(Func<T, bool> condition, T t, [CallerArgumentExpression("t")]string? paramName = null)
{
NotNull(condition);
if (!condition(t))
{
throw new ArgumentException("The argument does not meet condition", paramName);
}
return t;
}
public static async Task<T> EnsureAsync<T>(Func<T, Task<bool>> condition, T t, [CallerArgumentExpression("t")] string? paramName = null)
{
NotNull(condition);
if (!await condition(t))
{
throw new ArgumentException("The argument does not meet condition", paramName);
}
return t;
}
#if ValueTaskSupport
public static async Task<T> EnsureAsync<T>(Func<T, ValueTask<bool>> condition, T t, [CallerArgumentExpression("t")] string? paramName = null)
{
NotNull(condition);
if (!await condition(t))
{
throw new ArgumentException("The argument does not meet condition", paramName);
}
return t;
}
#endif
}
| using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace WeihanLi.Common;
public static class Guard
{
public static T NotNull<T>([NotNull] T? t,
[CallerArgumentExpression("t")]
string? paramName = default)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(t, paramName);
#else
if (t is null)
{
throw new ArgumentNullException(paramName)
}
#endif
return t;
}
public static string NotNullOrEmpty([NotNull] string? str,
[CallerArgumentExpression("str")]
string? paramName = null)
{
NotNull(str, paramName);
if (str.Length == 0)
{
throw new ArgumentException("The argument can not be Empty", paramName);
}
return str;
}
public static string NotNullOrWhiteSpace([NotNull] string? str,
[CallerArgumentExpression("str")] string? paramName = null)
{
NotNull(str, paramName);
if (string.IsNullOrWhiteSpace(str))
{
throw new ArgumentException("The argument can not be WhiteSpace", paramName);
}
return str;
}
public static ICollection<T> NotEmpty<T>([NotNull] ICollection<T> collection, [CallerArgumentExpression("collection")] string? paramName = null)
{
NotNull(collection, paramName);
if (collection.Count == 0)
{
throw new ArgumentException("The collection could not be empty", paramName);
}
return collection;
}
}
| mit | C# |
48f97f33e745e92e8cdd50844d411f971fe26540 | Update XTemplates.cs | wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | src/Core2D/Collections/XTemplates.cs | src/Core2D/Collections/XTemplates.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.Collections.Immutable;
using Core2D.Attributes;
using Core2D.Project;
namespace Core2D.Collections
{
/// <summary>
/// Observable <see cref="XContainer"/> collection.
/// </summary>
public class XTemplates : ObservableObject
{
/// <summary>
/// Gets or sets children collection.
/// </summary>
[Content]
public ImmutableArray<XContainer> Children { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="XContainer"/> class.
/// </summary>
public XTemplates()
{
Children = ImmutableArray.Create<XContainer>();
}
/// <summary>
/// Check whether the <see cref="Children"/> property has changed from its default value.
/// </summary>
/// <returns>Returns true if the property has changed; otherwise, returns false.</returns>
public bool ShouldSerializeChildren() => Children.IsEmpty == false;
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Immutable;
using Core2D.Attributes;
using Core2D.Project;
namespace Core2D.Collections
{
/// <summary>
/// Observable <see cref="XContainer"/> collection.
/// </summary>
public class XTemplates : ObservableResource
{
/// <summary>
/// Gets or sets resource name.
/// </summary>
[Name]
public string Name { get; set; }
/// <summary>
/// Gets or sets children collection.
/// </summary>
[Content]
public ImmutableArray<XContainer> Children { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="XContainer"/> class.
/// </summary>
public XTemplates()
{
Children = ImmutableArray.Create<XContainer>();
}
/// <summary>
/// Check whether the <see cref="Name"/> property has changed from its default value.
/// </summary>
/// <returns>Returns true if the property has changed; otherwise, returns false.</returns>
public bool ShouldSerializeName() => !String.IsNullOrWhiteSpace(Name);
/// <summary>
/// Check whether the <see cref="Children"/> property has changed from its default value.
/// </summary>
/// <returns>Returns true if the property has changed; otherwise, returns false.</returns>
public bool ShouldSerializeChildren() => Children.IsEmpty == false;
}
}
| mit | C# |
ba15d915e5451db158eb93baf3f8d1ce741be7e8 | 更新.net 4.5项目的版本号 | JeffreySu/WxOpen,JeffreySu/WxOpen | src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Properties/AssemblyInfo.cs | src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Senparc.Weixin.WxOpen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Senparc.Weixin.WxOpen")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("379d8c97-4f96-45af-9f91-6bd160514495")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.4.2.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Senparc.Weixin.WxOpen")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Senparc.Weixin.WxOpen")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("379d8c97-4f96-45af-9f91-6bd160514495")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.4.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
8f6b061300faa9d67d9e841dbc0e5c7b01974923 | Fix - cambiato oggetto notifica update enti | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.SignalR/Sender/GestioneEnti/NotificationUpdateEnte.cs | src/backend/SO115App.SignalR/Sender/GestioneEnti/NotificationUpdateEnte.cs | using CQRS.Queries;
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Classi.Condivise;
using SO115App.Models.Servizi.CQRS.Commands.GestioneRubrica.Enti.UpdateEnte;
using SO115App.Models.Servizi.CQRS.Queries.GestioneRubrica;
using SO115App.Models.Servizi.Infrastruttura.GestioneRubrica.Enti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneEnti;
using SO115App.SignalR.Utility;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneEnti
{
public class NotificationUpdateEnte : INotificationUpdateEnte
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly GetGerarchiaToSend _getGerarchiaToSend;
private readonly IGetRubrica _getRurbica;
public NotificationUpdateEnte(IGetRubrica getRurbica,
IHubContext<NotificationHub> notificationHubContext, GetGerarchiaToSend getGerarchiaToSend)
{
_getRurbica = getRurbica;
_notificationHubContext = notificationHubContext;
_getGerarchiaToSend = getGerarchiaToSend;
}
public async Task SendNotification(UpdateEnteCommand command)
{
var SediDaNotificare = new List<string>();
if (command.Ente.Ricorsivo)
SediDaNotificare = _getGerarchiaToSend.Get(command.CodiceSede[0]);
else
SediDaNotificare.Add(command.CodiceSede[0]);
var count = _getRurbica.CountBylstCodiciSede(SediDaNotificare.ToArray());
var Ente = _getRurbica.Get(command.CodiceSede, command.Ente.Descrizione).Find(c => c.Cap == command.Ente.Cap);
foreach (var sede in SediDaNotificare)
{
await _notificationHubContext.Clients.Group(sede).SendAsync("NotifyUpdateEnte", new
{
Pagination = new Paginazione() { TotalItems = count }
});
await _notificationHubContext.Clients.Group(sede).SendAsync("NotifyChangeEnti", new { Data = Ente });
}
}
}
}
| using CQRS.Queries;
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Classi.Condivise;
using SO115App.Models.Servizi.CQRS.Commands.GestioneRubrica.Enti.UpdateEnte;
using SO115App.Models.Servizi.CQRS.Queries.GestioneRubrica;
using SO115App.Models.Servizi.Infrastruttura.GestioneRubrica.Enti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneEnti;
using SO115App.SignalR.Utility;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneEnti
{
public class NotificationUpdateEnte : INotificationUpdateEnte
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly GetGerarchiaToSend _getGerarchiaToSend;
private readonly IGetRubrica _getRurbica;
public NotificationUpdateEnte(IGetRubrica getRurbica,
IHubContext<NotificationHub> notificationHubContext, GetGerarchiaToSend getGerarchiaToSend)
{
_getRurbica = getRurbica;
_notificationHubContext = notificationHubContext;
_getGerarchiaToSend = getGerarchiaToSend;
}
public async Task SendNotification(UpdateEnteCommand command)
{
var SediDaNotificare = new List<string>();
if (command.Ente.Ricorsivo)
SediDaNotificare = _getGerarchiaToSend.Get(command.CodiceSede[0]);
else
SediDaNotificare.Add(command.CodiceSede[0]);
var count = _getRurbica.CountBylstCodiciSede(SediDaNotificare.ToArray());
var lstEnti = _getRurbica.Get(command.CodiceSede, null);
foreach (var sede in SediDaNotificare)
{
await _notificationHubContext.Clients.Group(sede).SendAsync("NotifyUpdateEnte", new
{
Pagination = new Paginazione() { TotalItems = count }
});
await _notificationHubContext.Clients.Group(sede).SendAsync("NotifyChangeEnti", lstEnti);
}
}
}
}
| agpl-3.0 | C# |
c087a0c038bb43bc44589be9021d2411a1937a1c | update lib version | levid-gc/IdentityServer3.Dapper | source/IdentityServer3.Dapper/Properties/AssemblyInfo.cs | source/IdentityServer3.Dapper/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("IdentityServer3.Dapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IdentityServer3.Dapper")]
[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("3965edac-c7f8-493a-a27d-8954b111b457")]
// 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.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IdentityServer3.Dapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IdentityServer3.Dapper")]
[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("3965edac-c7f8-493a-a27d-8954b111b457")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
0293494020c2890550baca1b82818b5d38e7c16a | Add new overload SetData() in IndexBuffer class. | weelihl/sharpgl | source/SharpGL/Core/SharpGL/VertexBuffers/IndexBuffer.cs | source/SharpGL/Core/SharpGL/VertexBuffers/IndexBuffer.cs | namespace SharpGL.VertexBuffers
{
public class IndexBuffer
{
public void Create(OpenGL gl)
{
// Generate the vertex array.
uint[] ids = new uint[1];
gl.GenBuffers(1, ids);
bufferObject = ids[0];
}
public void SetData(OpenGL gl, ushort[] rawData, uint drawMode)
{
gl.BufferData(OpenGL.GL_ELEMENT_ARRAY_BUFFER, rawData, drawMode);
}
public void SetData(OpenGL gl, uint[] rawData, uint drawMode)
{
gl.BufferData(OpenGL.GL_ELEMENT_ARRAY_BUFFER, rawData, drawMode);
}
public void Bind(OpenGL gl)
{
gl.BindBuffer(OpenGL.GL_ELEMENT_ARRAY_BUFFER, bufferObject);
}
public void Unbind(OpenGL gl)
{
gl.BindBuffer(OpenGL.GL_ELEMENT_ARRAY_BUFFER, 0);
}
public bool IsCreated() { return bufferObject != 0; }
/// <summary>
/// Gets the index buffer object.
/// </summary>
public uint IndexBufferObject
{
get { return bufferObject; }
}
private uint bufferObject;
}
} | namespace SharpGL.VertexBuffers
{
public class IndexBuffer
{
public void Create(OpenGL gl)
{
// Generate the vertex array.
uint[] ids = new uint[1];
gl.GenBuffers(1, ids);
bufferObject = ids[0];
}
public void SetData(OpenGL gl, ushort[] rawData, uint drawMode)
{
gl.BufferData(OpenGL.GL_ELEMENT_ARRAY_BUFFER, rawData, drawMode);
}
public void Bind(OpenGL gl)
{
gl.BindBuffer(OpenGL.GL_ELEMENT_ARRAY_BUFFER, bufferObject);
}
public void Unbind(OpenGL gl)
{
gl.BindBuffer(OpenGL.GL_ELEMENT_ARRAY_BUFFER, 0);
}
public bool IsCreated() { return bufferObject != 0; }
/// <summary>
/// Gets the index buffer object.
/// </summary>
public uint IndexBufferObject
{
get { return bufferObject; }
}
private uint bufferObject;
}
} | mit | C# |
f4e9fc6e2e1e9cde68a1433f7a59eddff9ee3c48 | Use command-line arguments | martincostello/api,martincostello/api,martincostello/api | src/API/Program.cs | src/API/Program.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="https://martincostello.com/">
// Martin Costello (c) 2016
// </copyright>
// <summary>
// Program.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MartinCostello.Api
{
using System;
using System.IO;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
/// <summary>
/// A class representing the entry-point to the application. This class cannot be inherited.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// The exit code from the application.
/// </returns>
public static int Main(string[] args)
{
try
{
var configuration = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
var builder = new WebHostBuilder()
.UseKestrel()
.UseConfiguration(configuration)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
using (CancellationTokenSource tokenSource = new CancellationTokenSource())
{
Console.CancelKeyPress += (_, e) =>
{
tokenSource.Cancel();
e.Cancel = true;
};
using (var host = builder.Build())
{
host.Run(tokenSource.Token);
}
return 0;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unhandled exception: {ex}");
return -1;
}
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="https://martincostello.com/">
// Martin Costello (c) 2016
// </copyright>
// <summary>
// Program.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MartinCostello.Api
{
using System;
using System.IO;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
/// <summary>
/// A class representing the entry-point to the application. This class cannot be inherited.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// The exit code from the application.
/// </returns>
public static int Main(string[] args)
{
try
{
// TODO Also use command-line arguments
var builder = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
using (CancellationTokenSource tokenSource = new CancellationTokenSource())
{
Console.CancelKeyPress += (_, e) =>
{
tokenSource.Cancel();
e.Cancel = true;
};
using (var host = builder.Build())
{
host.Run(tokenSource.Token);
}
return 0;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unhandled exception: {ex}");
return -1;
}
}
}
}
| mit | C# |
4f002f793bc19bcafb5298c398663e7a6bc185e3 | fix the infobox for fullscreen | Sanva/f-spot,mono/f-spot,Sanva/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot,GNOME/f-spot,nathansamson/F-Spot-Album-Exporter,Yetangitu/f-spot,mans0954/f-spot,Sanva/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,dkoeb/f-spot,Yetangitu/f-spot,dkoeb/f-spot,dkoeb/f-spot,mans0954/f-spot,dkoeb/f-spot,mono/f-spot,dkoeb/f-spot,nathansamson/F-Spot-Album-Exporter,Yetangitu/f-spot,NguyenMatthieu/f-spot,nathansamson/F-Spot-Album-Exporter,nathansamson/F-Spot-Album-Exporter,mans0954/f-spot,mono/f-spot,GNOME/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,GNOME/f-spot,mono/f-spot,GNOME/f-spot,Yetangitu/f-spot,Sanva/f-spot,Sanva/f-spot,GNOME/f-spot,Yetangitu/f-spot,mono/f-spot,mono/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot | src/InfoOverlay.cs | src/InfoOverlay.cs | /*
* Copyright 2007 Novell Inc.
*
* Author
* Larry Ewing <[email protected]>
*
* See COPYING for license information.
*
*/
using Gtk;
using FSpot.Widgets;
namespace FSpot {
public class InfoItem : InfoBox {
BrowsablePointer item;
public InfoItem (BrowsablePointer item)
{
this.item = item;
item.Changed += HandleItemChanged;
HandleItemChanged (item, null);
VersionIdChanged += HandleVersionIdChanged;
ShowTags = true;
}
private void HandleItemChanged (BrowsablePointer sender, BrowsablePointerChangedArgs args)
{
Photo = item.Current as Photo;
}
private void HandleVersionIdChanged (InfoBox box, uint version_id)
{
Photo p = item.Current as Photo;
PhotoQuery q = item.Collection as PhotoQuery;
if (p != null && q != null) {
p.DefaultVersionId = version_id;
q.Commit (item.Index);
}
}
}
public class InfoOverlay : ControlOverlay {
InfoItem box;
public InfoOverlay (Widget w, BrowsablePointer item) : base (w)
{
XAlign = 1.0;
YAlign = 0.1;
box = new InfoItem (item);
box.BorderWidth = 15;
Add (box);
box.ShowAll ();
Visibility = VisibilityType.Partial;
KeepAbove = true;
//WindowPosition = WindowPosition.Mouse;
AutoHide = false;
}
}
}
| /*
* Copyright 2007 Novell Inc.
*
* Author
* Larry Ewing <[email protected]>
*
* See COPYING for license information.
*
*/
using Gtk;
using FSpot.Widgets;
namespace FSpot {
public class InfoItem : InfoBox {
BrowsablePointer item;
public InfoItem (BrowsablePointer item)
{
this.item = item;
item.Changed += HandleItemChanged;
HandleItemChanged (item, null);
VersionIdChanged += HandleVersionIdChanged;
ShowTags = true;
}
private void HandleItemChanged (BrowsablePointer sender, BrowsablePointerChangedArgs args)
{
Photo = item.Current as Photo;
}
private void HandleVersionIdChanged (InfoBox box, uint version_id)
{
Photo p = item.Current as Photo;
PhotoQuery q = item.Collection as PhotoQuery;
if (p != null && q != null) {
p.DefaultVersionId = version_id;
q.Commit (item.Index);
}
}
}
public class InfoOverlay : ControlOverlay {
InfoItem box;
public InfoOverlay (Widget w, BrowsablePointer item) : base (w)
{
XAlign = 1.0;
YAlign = 0.1;
box = new InfoItem (item);
box.BorderWidth = 15;
Add (box);
box.Show ();
Visibility = VisibilityType.Partial;
KeepAbove = true;
//WindowPosition = WindowPosition.Mouse;
AutoHide = false;
}
}
}
| mit | C# |
18f6076fc7a6f88ddc30ed4a5eb468a2c692cb70 | Remove obsolete hack which causes this problem | Moq/moq4 | src/Moq/Linq/Mock.cs | src/Moq/Linq/Mock.cs | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Diagnostics.CodeAnalysis;
using Moq.Linq;
namespace Moq
{
public partial class Mock
{
/// <summary>
/// Creates a mock object of the indicated type.
/// </summary>
/// <typeparam name="T">The type of the mocked object.</typeparam>
/// <returns>The mocked object created.</returns>
public static T Of<T>() where T : class
{
return Mock.Of<T>(MockBehavior.Default);
}
/// <summary>
/// Creates a mock object of the indicated type.
/// </summary>
/// <param name="behavior">Behavior of the mock.</param>
/// <typeparam name="T">The type of the mocked object.</typeparam>
/// <returns>The mocked object created.</returns>
public static T Of<T>(MockBehavior behavior) where T : class
{
// This method was originally implemented as follows:
//
// return Mocks.CreateMockQuery<T>().First<T>();
//
// which involved a lot of avoidable `IQueryable` query provider overhead and lambda compilation.
// What it really boils down to is this (much faster) code:
var mock = new Mock<T>(behavior);
if (behavior != MockBehavior.Strict)
{
mock.SetupAllProperties();
}
return mock.Object;
}
/// <summary>
/// Creates a mock object of the indicated type.
/// </summary>
/// <param name="predicate">The predicate with the specification of how the mocked object should behave.</param>
/// <typeparam name="T">The type of the mocked object.</typeparam>
/// <returns>The mocked object created.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design")]
public static T Of<T>(Expression<Func<T, bool>> predicate) where T : class
{
return Mock.Of<T>(predicate, MockBehavior.Default);
}
/// <summary>
/// Creates a mock object of the indicated type.
/// </summary>
/// <param name="predicate">The predicate with the specification of how the mocked object should behave.</param>
/// <param name="behavior">Behavior of the mock.</param>
/// <typeparam name="T">The type of the mocked object.</typeparam>
/// <returns>The mocked object created.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design")]
public static T Of<T>(Expression<Func<T, bool>> predicate, MockBehavior behavior) where T : class
{
return Mocks.CreateMockQuery<T>(behavior).First(predicate);
}
}
}
| // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Diagnostics.CodeAnalysis;
using Moq.Linq;
namespace Moq
{
public partial class Mock
{
/// <summary>
/// Creates a mock object of the indicated type.
/// </summary>
/// <typeparam name="T">The type of the mocked object.</typeparam>
/// <returns>The mocked object created.</returns>
public static T Of<T>() where T : class
{
return Mock.Of<T>(MockBehavior.Default);
}
/// <summary>
/// Creates a mock object of the indicated type.
/// </summary>
/// <param name="behavior">Behavior of the mock.</param>
/// <typeparam name="T">The type of the mocked object.</typeparam>
/// <returns>The mocked object created.</returns>
public static T Of<T>(MockBehavior behavior) where T : class
{
// This method was originally implemented as follows:
//
// return Mocks.CreateMockQuery<T>().First<T>();
//
// which involved a lot of avoidable `IQueryable` query provider overhead and lambda compilation.
// What it really boils down to is this (much faster) code:
var mock = new Mock<T>(behavior);
if (behavior != MockBehavior.Strict)
{
mock.SetupAllProperties();
}
return mock.Object;
}
/// <summary>
/// Creates a mock object of the indicated type.
/// </summary>
/// <param name="predicate">The predicate with the specification of how the mocked object should behave.</param>
/// <typeparam name="T">The type of the mocked object.</typeparam>
/// <returns>The mocked object created.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design")]
public static T Of<T>(Expression<Func<T, bool>> predicate) where T : class
{
return Mock.Of<T>(predicate, MockBehavior.Default);
}
/// <summary>
/// Creates a mock object of the indicated type.
/// </summary>
/// <param name="predicate">The predicate with the specification of how the mocked object should behave.</param>
/// <param name="behavior">Behavior of the mock.</param>
/// <typeparam name="T">The type of the mocked object.</typeparam>
/// <returns>The mocked object created.</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By Design")]
public static T Of<T>(Expression<Func<T, bool>> predicate, MockBehavior behavior) where T : class
{
var mocked = Mocks.CreateMockQuery<T>(behavior).First(predicate);
// The current implementation of LINQ to Mocks creates mocks that already have recorded invocations.
// Because this interferes with `VerifyNoOtherCalls`, we recursively clear all invocations before
// anyone ever gets to see the new created mock.
//
// TODO: Make LINQ to Mocks set up mocks without causing invocations of its own, then remove this hack.
var mock = Mock.Get(mocked);
mock.Invocations.Clear();
foreach (var inner in mock.Setups.GetInnerMockSetups())
{
inner.GetInnerMock().Invocations.Clear();
}
return mocked;
}
}
}
| bsd-3-clause | C# |
f608c33e11aaf1eb68405316bfa8b4824f2b18c0 | rename mysql processor | dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP | src/DotNetCore.CAP.MySql/CAP.MySqlCapOptionsExtension.cs | src/DotNetCore.CAP.MySql/CAP.MySqlCapOptionsExtension.cs | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using DotNetCore.CAP.MySql;
using DotNetCore.CAP.Processor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
internal class MySqlCapOptionsExtension : ICapOptionsExtension
{
private readonly Action<MySqlOptions> _configure;
public MySqlCapOptionsExtension(Action<MySqlOptions> configure)
{
_configure = configure;
}
public void AddServices(IServiceCollection services)
{
services.AddSingleton<CapDatabaseStorageMarkerService>();
services.AddSingleton<IStorage, MySqlStorage>();
services.AddSingleton<IStorageConnection, MySqlStorageConnection>();
services.AddScoped<ICapPublisher, CapPublisher>();
services.AddScoped<ICallbackPublisher, CapPublisher>();
services.AddTransient<ICollectProcessor, MySqlCollectProcessor>();
AddSingletionMySqlOptions(services);
}
private void AddSingletionMySqlOptions(IServiceCollection services)
{
var mysqlOptions = new MySqlOptions();
_configure(mysqlOptions);
if (mysqlOptions.DbContextType != null)
{
services.AddSingleton(x =>
{
using (var scope = x.CreateScope())
{
var provider = scope.ServiceProvider;
var dbContext = (DbContext)provider.GetService(mysqlOptions.DbContextType);
mysqlOptions.ConnectionString = dbContext.Database.GetDbConnection().ConnectionString;
return mysqlOptions;
}
});
}
else
{
services.AddSingleton(mysqlOptions);
}
}
}
} | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using DotNetCore.CAP.MySql;
using DotNetCore.CAP.Processor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
internal class MySqlCapOptionsExtension : ICapOptionsExtension
{
private readonly Action<MySqlOptions> _configure;
public MySqlCapOptionsExtension(Action<MySqlOptions> configure)
{
_configure = configure;
}
public void AddServices(IServiceCollection services)
{
services.AddSingleton<CapDatabaseStorageMarkerService>();
services.AddSingleton<IStorage, MySqlStorage>();
services.AddSingleton<IStorageConnection, MySqlStorageConnection>();
services.AddScoped<ICapPublisher, CapPublisher>();
services.AddScoped<ICallbackPublisher, CapPublisher>();
services.AddTransient<IAdditionalProcessor, DefaultAdditionalProcessor>();
AddSingletionMySqlOptions(services);
}
private void AddSingletionMySqlOptions(IServiceCollection services)
{
var mysqlOptions = new MySqlOptions();
_configure(mysqlOptions);
if (mysqlOptions.DbContextType != null)
{
services.AddSingleton(x =>
{
using (var scope = x.CreateScope())
{
var provider = scope.ServiceProvider;
var dbContext = (DbContext)provider.GetService(mysqlOptions.DbContextType);
mysqlOptions.ConnectionString = dbContext.Database.GetDbConnection().ConnectionString;
return mysqlOptions;
}
});
}
else
{
services.AddSingleton(mysqlOptions);
}
}
}
} | mit | C# |
3c3b559542f174f28803d014c4b194c7a81a7e7e | Fix race condition | terrajobst/nquery-vnext | src/NQuery/Symbols/TableDefinition.cs | src/NQuery/Symbols/TableDefinition.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace NQuery.Symbols
{
public abstract class TableDefinition
{
private ImmutableArray<ColumnDefinition> _columns;
public ImmutableArray<ColumnDefinition> Columns
{
get
{
if (_columns.IsDefault)
ImmutableInterlocked.InterlockedInitialize(ref _columns, GetColumns().ToImmutableArray());
return _columns;
}
}
public abstract string Name { get; }
public abstract Type RowType { get; }
protected abstract IEnumerable<ColumnDefinition> GetColumns();
public abstract IEnumerable GetRows();
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace NQuery.Symbols
{
public abstract class TableDefinition
{
private ImmutableArray<ColumnDefinition> _columns;
public ImmutableArray<ColumnDefinition> Columns
{
get
{
if (_columns.IsDefault)
_columns = GetColumns().ToImmutableArray();
return _columns;
}
}
public abstract string Name { get; }
public abstract Type RowType { get; }
protected abstract IEnumerable<ColumnDefinition> GetColumns();
public abstract IEnumerable GetRows();
}
} | mit | C# |
9a00c869971474a249be43f71e9976e0de6354ec | Refactor puzzle 10 to not use LINQ | martincostello/project-euler | src/ProjectEuler/Puzzles/Puzzle010.cs | src/ProjectEuler/Puzzles/Puzzle010.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
long sum = 0;
for (int n = 2; n < max - 2; n++)
{
if (Maths.IsPrime(n))
{
sum += n;
}
}
Answer = sum;
return 0;
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
Answer = Enumerable.Range(2, max - 2)
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
return 0;
}
}
}
| apache-2.0 | C# |
f2bc81584b5fbd41679172d71b65db5bbe5eeb4e | fix error in xml documentation | uzimmermann/wpf-localization,uzimmermann/wpf-localization | src/WpfLocalization.Framework/CultureChangedEventArgs.cs | src/WpfLocalization.Framework/CultureChangedEventArgs.cs | using System;
using System.Globalization;
namespace WpfLocalization.Framework
{
/// <summary>
/// Provides data for the <see cref="ILocalizeAnApplication.CultureChanged"/> event. This class cannot be
/// inherited.
/// </summary>
public sealed class CultureChangedEventArgs : EventArgs
{
/// <summary>
/// Saves the new culture. This field is readonly.
/// </summary>
private readonly CultureInfo _newCultureInfo;
/// <summary>
/// Gets the new culture.
/// </summary>
public CultureInfo NewCultureInfo
{
get { return _newCultureInfo; }
}
/// <summary>
/// Initializes a new instance of the <see cref="CultureChangedEventArgs"/> class with the given instance of
/// <see cref="CultureInfo"/>.
/// </summary>
/// <param name="newCultureInfo">An instance of <see cref="CultureInfo"/> representing the new culture.</param>
public CultureChangedEventArgs(CultureInfo newCultureInfo)
{
_newCultureInfo = newCultureInfo;
}
/// <summary>
/// Returns a string which represents the current instance of the <see cref="CultureChangedEventArgs"/> class.
/// </summary>
/// <returns>
/// A string which represents the current instance of the <see cref="CultureChangedEventArgs"/> class.
/// </returns>
public override string ToString()
{
return string.Format("NewCultureInfo: {0}", NewCultureInfo);
}
}
} | using System;
using System.Globalization;
namespace WpfLocalization.Framework
{
/// <summary>
/// Provides data for the <see cref="ILocalizableApplication.CultureChangedEvent"/>. This class cannot be
/// inherited.
/// </summary>
public sealed class CultureChangedEventArgs : EventArgs
{
/// <summary>
/// Saves the new culture. This field is readonly.
/// </summary>
private readonly CultureInfo _newCultureInfo;
/// <summary>
/// Gets the new culture.
/// </summary>
public CultureInfo NewCultureInfo
{
get { return _newCultureInfo; }
}
/// <summary>
/// Initializes a new instance of the <see cref="CultureChangedEventArgs"/> class with the given instance of
/// <see cref="CultureInfo"/>.
/// </summary>
/// <param name="newCultureInfo">An instance of <see cref="CultureInfo"/> representing the new culture.</param>
public CultureChangedEventArgs(CultureInfo newCultureInfo)
{
_newCultureInfo = newCultureInfo;
}
/// <summary>
/// Returns a string which represents the current instance of the <see cref="CultureChangedEventArgs"/> class.
/// </summary>
/// <returns>
/// A string which represents the current instance of the <see cref="CultureChangedEventArgs"/> class.
/// </returns>
public override string ToString()
{
return string.Format("NewCultureInfo: {0}", NewCultureInfo);
}
}
} | unlicense | C# |
b7b0539c40b94a0a508ab555b42787c92ae51aac | Remove AssemblyFileVersion from CommonAssemblyInfo | kendaleiv/silverpop-dotnet-api,kendaleiv/silverpop-dotnet-api,ritterim/silverpop-dotnet-api,billboga/silverpop-dotnet-api | common/CommonAssemblyInfo.cs | common/CommonAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Silverpop API")]
[assembly: AssemblyCopyright("Copyright © 2014 Ritter Insurance Marketing")]
[assembly: AssemblyCompany("Ritter Insurance Marketing")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyVersion("0.0.1.0")]
[assembly: ComVisible(false)]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Silverpop API")]
[assembly: AssemblyCopyright("Copyright © 2014 Ritter Insurance Marketing")]
[assembly: AssemblyCompany("Ritter Insurance Marketing")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyVersion("0.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: ComVisible(false)]
| mit | C# |
6bce50430613955384d04642557609594e213eaa | fix OperationException | yezorat/BtrieveWrapper,gomafutofu/BtrieveWrapper,gomafutofu/BtrieveWrapper,yezorat/BtrieveWrapper | BtrieveWrapper/OperationException.cs | BtrieveWrapper/OperationException.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Xml.Serialization;
namespace BtrieveWrapper
{
[Serializable]
public class OperationException : Exception
{
static readonly string _statusDefinitionPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".StatusCollection.xml";
static readonly Dictionary<short, string> _dictionary = new Dictionary<short, string>();
static string GetMessage(Operation operationType, short statusCode){
var result = new StringBuilder("Status code ");
result.Append(statusCode);
result.Append(" (");
result.Append(operationType);
result.Append(") : ");
if (_dictionary.ContainsKey(statusCode)) {
result.Append(_dictionary[statusCode]);
} else {
result.Append("This code is undefined.");
}
return result.ToString();
}
static OperationException() {
try {
StatusDefinition statusDefinition;
using (var stream = new FileStream(_statusDefinitionPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
var serializer = new XmlSerializer(typeof(StatusDefinition));
statusDefinition = (StatusDefinition)serializer.Deserialize(stream);
}
foreach (var status in statusDefinition.StatusCollection) {
_dictionary[status.Code] = status.Message;
}
} catch { }
}
string _message = null;
internal OperationException(Operation operation, short statusCode, Exception innerException = null)
: base(null, innerException) {
this.Operation = operation;
this.StatusCode = statusCode;
}
public Operation Operation { get; private set; }
public short StatusCode { get; private set; }
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
base.GetObjectData(info, context);
}
public override string Message {
get {
return _message ?? (_message = GetMessage(this.Operation, this.StatusCode));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Xml.Serialization;
namespace BtrieveWrapper
{
[Serializable]
public class OperationException : Exception
{
static readonly string _statusDefinitionPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".StatusCollection.xml";
static readonly Dictionary<short, string> _dictionary = new Dictionary<short, string>();
static string GetMessage(Operation operationType, short statusCode){
var result = new StringBuilder("Status code ");
result.Append(statusCode);
result.Append(" (");
result.Append(operationType);
result.Append(") : ");
if (_dictionary.ContainsKey(statusCode)) {
result.Append(_dictionary[statusCode]);
} else {
result.Append("This code is undefined.");
}
return result.ToString();
}
static OperationException() {
try {
StatusDefinition statusDefinition;
using (var stream = new FileStream(_statusDefinitionPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
var serializer = new XmlSerializer(typeof(StatusDefinition));
statusDefinition = (StatusDefinition)serializer.Deserialize(stream);
}
foreach (var status in statusDefinition.StatusCollection) {
_dictionary[status.Code] = status.Message;
}
} catch { }
}
internal OperationException(Operation operation, short statusCode, Exception innerException = null)
: base(null, innerException) {
this.Operation = operation;
this.StatusCode = statusCode;
}
public Operation Operation { get; private set; }
public short StatusCode { get; private set; }
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
base.GetObjectData(info, context);
}
public override string Message {
get {
return GetMessage(
}
}
}
}
| mit | C# |
1a443381247492b9233ae9c01ebf1a44510359ef | Use SingleOrDefault for added safety when looking up mod acronyms | ppy/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,ppy/osu,UselessToucan/osu | osu.Game/Online/API/APIMod.cs | osu.Game/Online/API/APIMod.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 Humanizer;
using Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Online.API
{
public class APIMod : IMod
{
[JsonProperty("acronym")]
public string Acronym { get; set; }
[JsonProperty("settings")]
public Dictionary<string, object> Settings { get; set; } = new Dictionary<string, object>();
[JsonConstructor]
private APIMod()
{
}
public APIMod(Mod mod)
{
Acronym = mod.Acronym;
foreach (var (_, property) in mod.GetSettingsSourceProperties())
Settings.Add(property.Name.Underscore(), property.GetValue(mod));
}
public Mod ToMod(Ruleset ruleset)
{
Mod resultMod = ruleset.GetAllMods().SingleOrDefault(m => m.Acronym == Acronym);
if (resultMod == null)
throw new InvalidOperationException($"There is no mod in the ruleset ({ruleset.ShortName}) matching the acronym {Acronym}.");
foreach (var (_, property) in resultMod.GetSettingsSourceProperties())
{
if (!Settings.TryGetValue(property.Name.Underscore(), out object settingValue))
continue;
((IBindable)property.GetValue(resultMod)).Parse(settingValue);
}
return resultMod;
}
public bool Equals(IMod other) => Acronym == other?.Acronym;
public override string ToString()
{
if (Settings.Count > 0)
return $"{Acronym} ({string.Join(',', Settings.Select(kvp => $"{kvp.Key}:{kvp.Value}"))})";
return $"{Acronym}";
}
}
}
| // 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 Humanizer;
using Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Online.API
{
public class APIMod : IMod
{
[JsonProperty("acronym")]
public string Acronym { get; set; }
[JsonProperty("settings")]
public Dictionary<string, object> Settings { get; set; } = new Dictionary<string, object>();
[JsonConstructor]
private APIMod()
{
}
public APIMod(Mod mod)
{
Acronym = mod.Acronym;
foreach (var (_, property) in mod.GetSettingsSourceProperties())
Settings.Add(property.Name.Underscore(), property.GetValue(mod));
}
public Mod ToMod(Ruleset ruleset)
{
Mod resultMod = ruleset.GetAllMods().FirstOrDefault(m => m.Acronym == Acronym);
if (resultMod == null)
throw new InvalidOperationException($"There is no mod in the ruleset ({ruleset.ShortName}) matching the acronym {Acronym}.");
foreach (var (_, property) in resultMod.GetSettingsSourceProperties())
{
if (!Settings.TryGetValue(property.Name.Underscore(), out object settingValue))
continue;
((IBindable)property.GetValue(resultMod)).Parse(settingValue);
}
return resultMod;
}
public bool Equals(IMod other) => Acronym == other?.Acronym;
public override string ToString()
{
if (Settings.Count > 0)
return $"{Acronym} ({string.Join(',', Settings.Select(kvp => $"{kvp.Key}:{kvp.Value}"))})";
return $"{Acronym}";
}
}
}
| mit | C# |
285eeb2f0c2104349bcaa8fac81c99e6bddc3616 | change search for prime triplet loop | fredatgithub/UsefulFunctions | ConsoleAppPrimesByHundred/Program.cs | ConsoleAppPrimesByHundred/Program.cs | using FonctionsUtiles.Fred.Csharp;
using System;
using System.Collections.Generic;
using System.Numerics;
namespace ConsoleAppPrimesByHundred
{
internal class Program
{
private static void Main()
{
Action<string> display = Console.WriteLine;
display("Prime numbers by hundred:");
foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000))
{
display($"{kvp.Key} - {kvp.Value}");
}
display(string.Empty);
display("Prime numbers by thousand:");
display(string.Empty);
foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000))
{
display($"{kvp.Key} - {kvp.Value}");
}
//int count = 0;
//for (int i = 3; i <= int.MaxValue - 4; i += 2)
//{
// if (FunctionsPrimes.IsPrimeTriplet(i))
// {
// count++;
// }
// display($"Number of prime found: {count} and i: {i}");
//}
display("no triplet prime from 3 to 2147483643");
for (BigInteger i = BigInteger.Parse("2147483643"); i <= BigInteger.Parse("2147483699"); i += 2)
{
BigInteger squareRoot = BigInteger.Pow(i, (int)BigInteger.Log(i)); // wrong square root
display($"Big Integer is : {i} and square root is = {squareRoot}");
}
display("Pas de prime triplet between 2147483643 and 3147483643");
int count = 0;
List<string> result = new List<string>();
for (BigInteger i = BigInteger.Parse("3147483643"); i <= BigInteger.Parse("4147483643"); i += 2)
{
if (FunctionsPrimes.IsPrimeTriplet(i))
{
count++;
result.Add(i.ToString());
}
display($"Number of prime found: {count} and i = {i}");
}
if (result.Count > 0)
{
foreach (string number in result)
{
display($"Prime triplet found : {number}");
}
}
var timestamp = DateTime.Now.ToFileTime();
display($"time stamp using ToFileTime : {timestamp.ToString()}");
string timeStamp = GetTimestamp(DateTime.Now);
display($"time stamp yyyymmddhh : {timestamp.ToString()}");
display("Press any key to exit");
Console.ReadKey();
}
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssffff");
}
}
} | using FonctionsUtiles.Fred.Csharp;
using System;
using System.Collections.Generic;
using System.Numerics;
namespace ConsoleAppPrimesByHundred
{
internal class Program
{
private static void Main()
{
Action<string> display = Console.WriteLine;
display("Prime numbers by hundred:");
foreach (var kvp in FunctionsPrimes.NumberOfPrimesByHundred(1000))
{
display($"{kvp.Key} - {kvp.Value}");
}
display(string.Empty);
display("Prime numbers by thousand:");
display(string.Empty);
foreach (var kvp in FunctionsPrimes.NumberOfPrimesByNthHundred(9000, 1000))
{
display($"{kvp.Key} - {kvp.Value}");
}
//int count = 0;
//for (int i = 3; i <= int.MaxValue - 4; i += 2)
//{
// if (FunctionsPrimes.IsPrimeTriplet(i))
// {
// count++;
// }
// display($"Number of prime found: {count} and i: {i}");
//}
display("no triplet prime from 3 to 2147483643");
for (BigInteger i = BigInteger.Parse("2147483643"); i <= BigInteger.Parse("2147483699"); i += 2)
{
BigInteger squareRoot = BigInteger.Pow(i, (int)BigInteger.Log(i)); // wrong square root
display($"Big Integer is : {i} and square root is = {squareRoot}");
}
int count = 0;
List<string> result = new List<string>();
for (BigInteger i = BigInteger.Parse("2147483643"); i <= BigInteger.Parse("3147483643"); i += 2)
{
if (FunctionsPrimes.IsPrimeTriplet(i))
{
count++;
result.Add(i.ToString());
}
display($"Number of prime found: {count} and i = {i}");
}
if (result.Count > 0)
{
foreach (string number in result)
{
display($"Prime triplet found : {number}");
}
}
var timestamp = DateTime.Now.ToFileTime();
display($"time stamp using ToFileTime : {timestamp.ToString()}");
string timeStamp = GetTimestamp(DateTime.Now);
display($"time stamp yyyymmddhh : {timestamp.ToString()}");
display("Press any key to exit");
Console.ReadKey();
}
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssffff");
}
}
} | mit | C# |
3b84236279728aa09b1141193f700364e8f27e06 | Disable warning for MEF export field | rprouse/GitHubExtension | GitHubExtension/View/OutputWriter.cs | GitHubExtension/View/OutputWriter.cs | // **********************************************************************************
// The MIT License (MIT)
//
// Copyright (c) 2014 Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// **********************************************************************************
using System.ComponentModel.Composition;
using Alteridem.GitHub.Logging;
using Microsoft.VisualStudio.Utilities;
using Tvl.VisualStudio.OutputWindow.Interfaces;
namespace Alteridem.GitHub.Extension.View
{
public class OutputWriter : BaseOutputWriter
{
public const string GitHubOutputWindowPaneName = "GitHub";
#pragma warning disable 169 // The field 'fieldName' is never used
[Export]
[Name(GitHubOutputWindowPaneName)]
private static OutputWindowDefinition GitHubOutputWindowDefinition;
#pragma warning restore 169
/// <summary>
/// Logs the specified message.
/// </summary>
/// <param name="message">The message.</param>
protected override void WriteMessage(string message)
{
var pane = Factory.Get<IOutputWindowPane>();
if (pane != null)
pane.WriteLine(message);
}
/// <summary>
/// Shows the specified message.
/// </summary>
/// <param name="message">The message.</param>
protected override void ShowMessage(string message)
{
VisualStudioMessageBox.Show(message);
}
}
} | // **********************************************************************************
// The MIT License (MIT)
//
// Copyright (c) 2014 Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// **********************************************************************************
using System.ComponentModel.Composition;
using Alteridem.GitHub.Logging;
using Microsoft.VisualStudio.Utilities;
using Tvl.VisualStudio.OutputWindow.Interfaces;
namespace Alteridem.GitHub.Extension.View
{
public class OutputWriter : BaseOutputWriter
{
public const string GitHubOutputWindowPaneName = "GitHub";
[Export]
[Name(GitHubOutputWindowPaneName)]
private static OutputWindowDefinition GitHubOutputWindowDefinition;
/// <summary>
/// Logs the specified message.
/// </summary>
/// <param name="message">The message.</param>
protected override void WriteMessage(string message)
{
var pane = Factory.Get<IOutputWindowPane>();
if (pane != null)
pane.WriteLine(message);
}
/// <summary>
/// Shows the specified message.
/// </summary>
/// <param name="message">The message.</param>
protected override void ShowMessage(string message)
{
VisualStudioMessageBox.Show(message);
}
}
} | mit | C# |
f3b696d0c2a01bf78ead6785b699833ccfe6c5b2 | Change or add various things to the data types | Figglewatts/LBD2OBJ | LBD2OBJ/Types/TMD.cs | LBD2OBJ/Types/TMD.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LBD2OBJ.Types
{
struct TMDHEADER
{
public int ID; // should be 0x41
public uint flags; // 0 if addresses are relative from top of block, 1 if from start of file
public uint numObjects;
}
struct OBJECT
{
public uint vertTop; // pointer to start of vertices
public uint numVerts;
public uint normTop; // pointer to start of normals
public uint numNorms;
public uint primTop; // pointer to start of primitives
public uint numPrims;
public int scale; // unused
public VERTEX[] vertices;
public NORMAL[] normals;
public PRIMITIVE[] primitives;
}
struct PRIMITIVE
{
public byte mode; // b001 - poly, b010 - line, b011 - sprite
public byte flag; // rendering info
public byte ilen; // length (in words) of packet data
public byte olen; // length (in words) of 2D drawing primitives
public PRIMITIVECLASSIFICATION classification;
public PRIMITIVEDATA data;
}
struct PRIMITIVECLASSIFICATION
{
public bool gouraudShaded;
public bool quad;
public bool textureMapped;
public bool unlit; // if unlit, there are no normals
public bool gradation;
public bool twoSided;
}
struct PRIMITIVEDATA
{
public short[] triangleIndices;
public short[] normalIndices;
public UV[] uvCoords;
}
struct VERTEX
{
public short X;
public short Y;
public short Z;
}
struct NORMAL
{
public FixedPoint nX;
public FixedPoint nY;
public FixedPoint nZ;
}
struct UV
{
public byte U;
public byte V;
}
struct TMD
{
public TMDHEADER header;
public bool fixP;
public long objTop;
public OBJECT[] objTable;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LBD2OBJ.Types
{
struct TMDHEADER
{
public int ID; // should be 0x41
public uint flags; // 0 if addresses are relative from top of block, 1 if from start of file
public uint numObjects;
}
struct OBJECT
{
public uint vertTop; // pointer to start of vertices
public uint numVerts;
public uint normTop; // pointer to start of normals
public uint numNorms;
public uint primTop; // pointer to start of primitives
public uint numPrims;
public int scale; // unused
public VERTEX[] vertices;
public NORMAL[] normals;
}
struct PRIMITIVE
{
public byte mode; // b001 - poly, b010 - line, b011 - sprite
public byte flag; // rendering info
public byte ilen; // length (in words) of packet data
public byte olen; // length (in words) of 2D drawing primitives
public PRIMITIVECLASSIFICATION classification;
public PRIMITIVEDATA data;
}
struct PRIMITIVECLASSIFICATION
{
public bool gouraudShaded;
public bool quad;
public bool textureMapped;
public bool unlit;
}
struct PRIMITIVEDATA
{
public int[] triangleIndices;
public int[] normalIndices;
public UV[] uvCoords;
}
struct VERTEX
{
public short X;
public short Y;
public short Z;
}
struct NORMAL
{
public FixedPoint nX;
public FixedPoint nY;
public FixedPoint nZ;
}
struct UV
{
public short U;
public short V;
}
struct TMD
{
public TMDHEADER header;
public bool fixP;
public long objTop;
public OBJECT[] objTable;
}
}
| mit | C# |
e194a1ccbde959ff4ff052f855693d3e80d01da2 | Update IFunctional.cs | codecore/Functional,codecore/Functional | IFunctional.cs | IFunctional.cs | using System;
using System.IO;
using System.Collections.Generic;
namespace Functional.Contracts {
public delegate IEnumerable<string> GetStrings(StreamReader sr);
public interface IChain<T> {
T Item { get; }
IChain<T> Run(T t);
}
public interface IListener<T, U> {
Func<T, U> Handle { get; }
}
public interface ISomething<T> {
T Item { get; set; }
}
public interface ISomethingImmutable<T> {
T Item { get; }
}
public interface IDefault<T> {
Func<T,T> orDefault { get; }
}
public interface ICurry<T> {
Action<T> Create();
Func<T, T> Create(T t1);
Func<T, T> Create(T t1, T t2);
Func<T, T> Create(T t1, T t2, T t3);
Func<T, T> Create(T t1, T t2, T t3, T t4);
Func<T, T> Create(T t1, T t2, T t3, T t4, T t5);
Func<T, T> Create(T t1, T t2, T t3, T t4, T t5, T t6);
}
public interface ICurry1<T, U> {
Func<Func<T, U>> Create { get; }
}
public interface ICurry2<T, U> {
Func<T,Func<U, U>> Create { get; }
}
}
| using System;
using System.IO;
using System.Collections.Generic;
namespace Functional.Contracts {
public delegate IEnumerable<string> GetStrings(StreamReader sr);
public interface IListener<T, U> { U Handle(T m); }
public interface ISomething<T> {
T Item { get; set; }
}
public interface ISomethingImmutable<T> {
T Item { get; }
}
public interface IDefault<T> {
T orDefault(T t);
}
public interface ICurry1<T, U> {
Func<T, U> Create();
}
public interface ICurry2<T, U> {
Func<U, U> Create(T t);
}
}
| apache-2.0 | C# |
3194ded94c4c340cdc402dc00b4c9cd135ca74fe | remove index name on year | ekospinach/kawaldesa,ekospinach/kawaldesa,ghk/kawaldesa,ekospinach/kawaldesa,ghk/kawaldesa,ekospinach/kawaldesa,ghk/kawaldesa,ghk/kawaldesa | Models/APBN.cs | Models/APBN.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace App.Models
{
public class APBN : BaseEntity
{
public decimal DanaPerDesa { get; set; }
[Index(IsUnique=true)]
public int Year { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace App.Models
{
public class APBN : BaseEntity
{
public decimal DanaPerDesa { get; set; }
[Index("IX_Year", IsUnique=true)]
public int Year { get; set; }
}
} | mit | C# |
e7caf76ca65677a750b98c837689617026b35341 | change the version to 1.2.5 | SpectraLogic/ds3_net_sdk,SpectraLogic/ds3_net_sdk,shabtaisharon/ds3_net_sdk,shabtaisharon/ds3_net_sdk,rpmoore/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,rpmoore/ds3_net_sdk,RachelTucker/ds3_net_sdk,RachelTucker/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk | VersionInfo.cs | VersionInfo.cs | /*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* 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 System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.5.0")]
[assembly: AssemblyFileVersion("1.2.5.0")]
| /*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* 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 System.Reflection;
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.4.0")]
[assembly: AssemblyFileVersion("1.2.4.0")]
| apache-2.0 | C# |
efa8c1e30e277044e3c2ea8190bc4078fd817240 | Fix broken build | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/SFA.DAS.Commitments.Application.UnitTests/Services/EventUpgradeHandler/WhenExecute.cs | src/SFA.DAS.Commitments.Application.UnitTests/Services/EventUpgradeHandler/WhenExecute.cs | using System.Threading.Tasks;
using Moq;
using NServiceBus;
using NUnit.Framework;
namespace SFA.DAS.Commitments.Application.UnitTests.Services.EventUpgradeHandler
{
[TestFixture]
public class WhenExecute
{
private Application.Services.EventUpgradeHandler _sut;
private Mock<IEndpointInstance> _mockEndpointInstance;
[SetUp]
public void Arrange()
{
_mockEndpointInstance = new Mock<IEndpointInstance>();
_sut = new Application.Services.EventUpgradeHandler(_mockEndpointInstance.Object, Mock.Of<NLog.Logger.ILog>());
}
[Test]
public async Task ThenTheEventIsPassedToTheEndpointInstance()
{
// arrange
var testMessage = new Events.CohortApprovalRequestedByProvider(1, 2, 3);
// act
await _sut.Execute(testMessage);
// assert
_mockEndpointInstance.Verify(m => m.Publish(
It.Is<CommitmentsV2.Messages.Events.CohortApprovalRequestedByProvider>(a =>
a.AccountId.Equals(testMessage.AccountId) &&
a.ProviderId.Equals(testMessage.ProviderId) &&
a.CommitmentId.Equals(testMessage.CommitmentId))
, It.IsAny<PublishOptions>())
, Times.Once);
}
}
}
| using System.Threading.Tasks;
using Moq;
using NServiceBus;
using NUnit.Framework;
namespace SFA.DAS.Commitments.Application.UnitTests.Services.EventUpgradeHandler
{
[TestFixture]
public class WhenExecute
{
private Application.Services.EventUpgradeHandler _sut;
private Mock<IEndpointInstance> _mockEndpointInstance;
[SetUp]
public void Arrange()
{
_mockEndpointInstance = new Mock<IEndpointInstance>();
_sut = new Application.Services.EventUpgradeHandler(_mockEndpointInstance.Object);
}
[Test]
public async Task ThenTheEventIsPassedToTheEndpointInstance()
{
// arrange
var testMessage = new Events.CohortApprovalRequestedByProvider(1, 2, 3);
// act
await _sut.Execute(testMessage);
// assert
_mockEndpointInstance.Verify(m => m.Publish(
It.Is<CommitmentsV2.Messages.Events.CohortApprovalRequestedByProvider>(a =>
a.AccountId.Equals(testMessage.AccountId) &&
a.ProviderId.Equals(testMessage.ProviderId) &&
a.CommitmentId.Equals(testMessage.CommitmentId))
, It.IsAny<PublishOptions>())
, Times.Once);
}
}
}
| mit | C# |
447a48cefa592b96dbe65ddae036a0bef1dddc38 | add summary comments | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit.Providers/UnityARCameraSettings/UnityARCameraSettingsProfile.cs | Assets/MixedRealityToolkit.Providers/UnityARCameraSettings/UnityARCameraSettingsProfile.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright(c) 2019 Takahiro Miyaura
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using UnityEngine.SpatialTracking;
namespace Microsoft.MixedReality.Toolkit.CameraSystem
{
/// <summary>
/// Configuration profile for the XR Camera setttings provider.
/// </summary>
[CreateAssetMenu(menuName = "Mixed Reality Toolkit/Profiles/Unity AR Foundation Camera Settings Profile", fileName = "DefaultUnityARCameraSettingsProfile", order = 100)]
[MixedRealityServiceProfile(typeof(UnityARCameraSettings))]
public class UnityARCameraSettingsProfile : BaseCameraSettingsProfile
{
#region Tracked Pose Driver settings
[SerializeField]
[Tooltip("The portion of the device (ex: color camera) from which to read the pose.")]
private TrackedPoseDriver.TrackedPose poseSource = TrackedPoseDriver.TrackedPose.ColorCamera;
/// <summary>
/// The portion of the device (ex: color camera) from which to read the pose.
/// </summary>
public TrackedPoseDriver.TrackedPose PoseSource => poseSource;
[SerializeField]
[Tooltip("The type of tracking (position and/or rotation) to apply.")]
private TrackedPoseDriver.TrackingType trackingType = TrackedPoseDriver.TrackingType.RotationAndPosition;
/// <summary>
/// The type of tracking (position and/or rotation) to apply.
/// </summary>
public TrackedPoseDriver.TrackingType TrackingType => trackingType;
[SerializeField]
[Tooltip("Specfies when (during Update and/or just before rendering) to update the tracking of the pose.")]
private TrackedPoseDriver.UpdateType updateType = TrackedPoseDriver.UpdateType.UpdateAndBeforeRender;
/// <summary>
/// Specfies when (during Update and/or just before rendering) to update the tracking of the pose.
/// </summary>
public TrackedPoseDriver.UpdateType UpdateType => updateType;
#endregion Tracked Pose Driver settings
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright(c) 2019 Takahiro Miyaura
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using UnityEngine.SpatialTracking;
namespace Microsoft.MixedReality.Toolkit.CameraSystem
{
/// <summary>
/// Configuration profile for the XR Camera setttings provider.
/// </summary>
[CreateAssetMenu(menuName = "Mixed Reality Toolkit/Profiles/Unity AR Foundation Camera Settings Profile", fileName = "DefaultUnityARCameraSettingsProfile", order = 100)]
[MixedRealityServiceProfile(typeof(UnityARCameraSettings))]
public class UnityARCameraSettingsProfile : BaseCameraSettingsProfile
{
#region Tracked Pose Driver settings
[SerializeField]
[Tooltip("The portion of the device from which to read the pose.")]
private TrackedPoseDriver.TrackedPose poseSource = TrackedPoseDriver.TrackedPose.ColorCamera;
public TrackedPoseDriver.TrackedPose PoseSource => poseSource;
[SerializeField]
[Tooltip("The type of tracking (position and/or rotation) to apply.")]
private TrackedPoseDriver.TrackingType trackingType = TrackedPoseDriver.TrackingType.RotationAndPosition;
public TrackedPoseDriver.TrackingType TrackingType => trackingType;
[SerializeField]
[Tooltip("Specfies when (during Update and/or just before rendering) to update the tracking of the pose.")]
private TrackedPoseDriver.UpdateType updateType = TrackedPoseDriver.UpdateType.UpdateAndBeforeRender;
public TrackedPoseDriver.UpdateType UpdateType => updateType;
#endregion Tracked Pose Driver settings
}
}
| mit | C# |
1270914bb26b209bb5e653e09fdaf19f3ac0a3ec | Rename UInt to UIntField | laicasaane/VFW | Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/UInts.cs | Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/UInts.cs | using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public uint UIntField(uint value)
{
return UIntField(string.Empty, value);
}
public uint UIntField(string label, uint value)
{
return UIntField(label, value, null);
}
public uint UIntField(string label, string tooltip, uint value)
{
return UIntField(label, tooltip, value, null);
}
public uint UIntField(string label, uint value, Layout option)
{
return UIntField(label, string.Empty, value, option);
}
public uint UIntField(string label, string tooltip, uint value, Layout option)
{
return UIntField(GetContent(label, tooltip), value, option);
}
public abstract uint UIntField(GUIContent content, uint value, Layout option);
}
}
| using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public uint UInt(uint value)
{
return UInt(string.Empty, value);
}
public uint UInt(string label, uint value)
{
return UInt(label, value, null);
}
public uint UInt(string label, string tooltip, uint value)
{
return UInt(label, tooltip, value, null);
}
public uint UInt(string label, uint value, Layout option)
{
return UInt(label, string.Empty, value, option);
}
public uint UInt(string label, string tooltip, uint value, Layout option)
{
return UInt(GetContent(label, tooltip), value, option);
}
public abstract uint UInt(GUIContent content, uint value, Layout option);
}
}
| mit | C# |
ba08ad548b0e8c0d290bd63ff06fbc3df3faf6f7 | Fix some arrivals showing negative ETA minutes. | betrakiss/Tramline-5,betrakiss/Tramline-5 | src/TramlineFive/TramlineFive.Common/Converters/TimingConverter.cs | src/TramlineFive/TramlineFive.Common/Converters/TimingConverter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace TramlineFive.Common.Converters
{
public class TimingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string[] timings = (string[])value;
StringBuilder builder = new StringBuilder();
foreach (string singleTiming in timings)
{
TimeSpan timing;
if (TimeSpan.TryParse((string)singleTiming, out timing))
{
TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay;
builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes < 0 ? 0 : timeLeft.Minutes);
}
}
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return String.Empty;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace TramlineFive.Common.Converters
{
public class TimingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
string[] timings = (string[])value;
StringBuilder builder = new StringBuilder();
foreach (string singleTiming in timings)
{
TimeSpan timing;
if (TimeSpan.TryParse((string)singleTiming, out timing))
{
TimeSpan timeLeft = timing - DateTime.Now.TimeOfDay;
builder.AppendFormat("{0} ({1} мин), ", singleTiming, timeLeft.Minutes);
}
}
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return String.Empty;
}
}
}
| apache-2.0 | C# |
8d511027faeef79f4c1d3aa9cc875a000d6ba3d2 | Fix version number (alpha2) | bungeemonkee/Utilitron | Utilitron/Properties/AssemblyInfo.cs | Utilitron/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
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("Utilitron")]
[assembly: AssemblyDescription("Basic .NET utilities.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("David love")]
[assembly: AssemblyProduct("Utilitron")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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("089b3411-e1ca-4812-8daa-92d332f72408")]
// Version information for an assembly consists of the following four values.
// We will increase these values in the following way:
// Major Version : Increased when there is a release that breaks a public api
// Minor Version : Increased for each non-api-breaking release
// Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases
// Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number
[assembly: AssemblyVersion("1.0.0.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
// This version number will roughly follow semantic versioning : http://semver.org
// The first three numbers will always match the first the numbers of the version above.
[assembly: AssemblyInformationalVersion("1.0.0-alpha2")]
| using System.Reflection;
using System.Resources;
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("Utilitron")]
[assembly: AssemblyDescription("Basic .NET utilities.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("David love")]
[assembly: AssemblyProduct("Utilitron")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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("089b3411-e1ca-4812-8daa-92d332f72408")]
// Version information for an assembly consists of the following four values.
// We will increase these values in the following way:
// Major Version : Increased when there is a release that breaks a public api
// Minor Version : Increased for each non-api-breaking release
// Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases
// Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number
[assembly: AssemblyVersion("1.0.0.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
// This version number will roughly follow semantic versioning : http://semver.org
// The first three numbers will always match the first the numbers of the version above.
[assembly: AssemblyInformationalVersion("1.0.0-alpha12")]
| mit | C# |
1ce74de5f63d4d5a420e058f83d223c914a84d55 | simplify CSS in view | codingoutloud/matechtax,codingoutloud/matechtax | MATechTaxWebSite/MATechTaxWebSite/Views/Home/Index.cshtml | MATechTaxWebSite/MATechTaxWebSite/Views/Home/Index.cshtml | @{
@model IEnumerable<MATechTaxWebSite.Models.BlobSnapshot>
ViewBag.Title = "Home Page";
ViewBag.FaqUrl = System.Configuration.ConfigurationManager.AppSettings["DorFaqUrl"];
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<p>
</p>
</div>
</section>
}
<h2>DOR FAQ</h2>
<a href="@ViewBag.FaqUrl">LATEST Sofware Service Sales Tax FAQ</a>
<h3>DOR FAQ HISTORY (Partial)</h3>
<ol class="round">
@foreach (var snap in Model)
{
<li>
<h4><a href="@snap.Url">@snap.LastModified</a></h4>
</li>
}
</ol>
<article>
<p>
Use this area to provide additional information.
</p>
<p>
Use this area to provide additional information.
</p>
<p>
Use this area to provide additional information.
</p>
</article>
<section class="contact">
<header>
<h3>Email</h3>
</header>
<p>
<span><a href="mailto:[email protected]">[email protected]</a></span>
</p>
</section>
| @{
@model IEnumerable<MATechTaxWebSite.Models.BlobSnapshot>
ViewBag.Title = "Home Page";
ViewBag.FaqUrl = System.Configuration.ConfigurationManager.AppSettings["DorFaqUrl"];
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
<h2>@ViewBag.Message</h2>
</hgroup>
<p>
</p>
</div>
</section>
}
<h2>DOR FAQ</h2>
<a href="@ViewBag.FaqUrl">LATEST Sofware Service Sales Tax FAQ</a>
<h3>DOR FAQ HISTORY (Partial)</h3>
<ol class="round">
@foreach (var snap in Model)
{
<li class="one">
<h4><a href="@snap.Url">@snap.LastModified</a></h4>
</li>
}
</ol>
<article>
<p>
Use this area to provide additional information.
</p>
<p>
Use this area to provide additional information.
</p>
<p>
Use this area to provide additional information.
</p>
</article>
<section class="contact">
<header>
<h3>Email</h3>
</header>
<p>
<span><a href="mailto:[email protected]">[email protected]</a></span>
</p>
</section>
| mit | C# |
b658c5cafc542826078a7b0d474542838c2140b7 | Make claim text required (as it already required in backend) | kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net | Joinrpg/Models/AddClaimViewModel.cs | Joinrpg/Models/AddClaimViewModel.cs | using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JoinRpg.DataModel;
using JoinRpg.Web.Helpers;
using JoinRpg.Web.Models.CommonTypes;
namespace JoinRpg.Web.Models
{
public class AddClaimViewModel
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public HtmlString ClaimApplyRules { get; set; }
public int? CharacterId { get; set; }
public int? CharacterGroupId { get; set; }
[DisplayName("Заявка")]
public string TargetName { get; set; }
[Display(Name="Описание")]
public HtmlString Description { get; set; }
public bool HasApprovedClaim { get; set; }
public bool HasAnyClaim { get; set; }
public bool IsAvailable { get; set; }
[Display(Name ="Текст заявки"), Required]
public MarkdownViewModel ClaimText { get; set; }
public static AddClaimViewModel Create(Character character, User user)
{
var vm = CreateImpl(character, user);
vm.CharacterId = character.CharacterId;
return vm;
}
public static AddClaimViewModel Create(CharacterGroup group, User user)
{
var vm = CreateImpl(@group, user);
vm.CharacterGroupId = group.CharacterGroupId;
return vm;
}
private static AddClaimViewModel CreateImpl(IClaimSource obj, User user)
{
var addClaimViewModel = new AddClaimViewModel
{
ProjectId = obj.ProjectId,
ProjectName = obj.Project.ProjectName,
HasAnyClaim = user.Claims.Any(c => c.ProjectId == obj.ProjectId && c.IsActive),
HasApprovedClaim = user.Claims.Any(c => c.ProjectId == obj.ProjectId && c.IsApproved),
TargetName = obj.Name,
Description = obj.Description.ToHtmlString(),
IsAvailable = obj.IsAvailable,
ClaimApplyRules = obj.Project.Details?.ClaimApplyRules?.ToHtmlString()
};
return addClaimViewModel;
}
}
}
| using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JoinRpg.DataModel;
using JoinRpg.Web.Helpers;
using JoinRpg.Web.Models.CommonTypes;
namespace JoinRpg.Web.Models
{
public class AddClaimViewModel
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public HtmlString ClaimApplyRules { get; set; }
public int? CharacterId { get; set; }
public int? CharacterGroupId { get; set; }
[DisplayName("Заявка")]
public string TargetName { get; set; }
[Display(Name="Описание")]
public HtmlString Description { get; set; }
public bool HasApprovedClaim { get; set; }
public bool HasAnyClaim { get; set; }
public bool IsAvailable { get; set; }
[Display(Name ="Текст заявки")]
public MarkdownViewModel ClaimText { get; set; }
public static AddClaimViewModel Create(Character character, User user)
{
var vm = CreateImpl(character, user);
vm.CharacterId = character.CharacterId;
return vm;
}
public static AddClaimViewModel Create(CharacterGroup group, User user)
{
var vm = CreateImpl(@group, user);
vm.CharacterGroupId = group.CharacterGroupId;
return vm;
}
private static AddClaimViewModel CreateImpl(IClaimSource obj, User user)
{
var addClaimViewModel = new AddClaimViewModel
{
ProjectId = obj.ProjectId,
ProjectName = obj.Project.ProjectName,
HasAnyClaim = user.Claims.Any(c => c.ProjectId == obj.ProjectId && c.IsActive),
HasApprovedClaim = user.Claims.Any(c => c.ProjectId == obj.ProjectId && c.IsApproved),
TargetName = obj.Name,
Description = obj.Description.ToHtmlString(),
IsAvailable = obj.IsAvailable,
ClaimApplyRules = obj.Project.Details?.ClaimApplyRules?.ToHtmlString()
};
return addClaimViewModel;
}
}
}
| mit | C# |
9e2ff2132ad2737092a5ea8bd12bb9ec71a0a3a6 | Refactor NumeroBollo > BolloVirtuale | sirmmo/FatturaElettronicaPA,FatturaElettronicaPA/FatturaElettronicaPA | FatturaElettronicaBody/DatiGenerali/DatiBollo.cs | FatturaElettronicaBody/DatiGenerali/DatiBollo.cs | using System.Collections.Generic;
using System.Xml;
using BusinessObjects;
using BusinessObjects.Validators;
using FatturaElettronicaPA.Validators;
namespace FatturaElettronicaPA.FatturaElettronicaBody.DatiGenerali
{
/// <summary>
/// Dati relativi al bollo.
/// </summary>
public class DatiBollo : Common.BusinessObject
{
public DatiBollo() { }
public DatiBollo(XmlReader r) : base(r) { }
protected override List<Validator> CreateRules() {
var rules = base.CreateRules();
rules.Add(
new AndCompositeValidator("BolloVirtuale",
new List<Validator> {new FRequiredValidator(), new DomainValidator("Valore consentito: [SI]", new[] {"SI"}) }));
rules.Add(new FRequiredValidator("ImportoBollo"));
return rules;
}
#region Properties
/// IMPORTANT
/// Each data property must be flagged with the Order attribute or it will be ignored.
/// Also, properties must be listed with the precise order in the specification.
/// <summary>
/// Bollo virtuale.
/// </summary>
[DataProperty]
public string BolloVirtuale { get; set; }
/// <summary>
/// Importo del bollo.
/// </summary>
[DataProperty]
public decimal? ImportoBollo { get; set; }
#endregion
}
}
| using System.Collections.Generic;
using System.Xml;
using BusinessObjects;
using BusinessObjects.Validators;
using FatturaElettronicaPA.Validators;
namespace FatturaElettronicaPA.FatturaElettronicaBody.DatiGenerali
{
/// <summary>
/// Dati relativi al bollo.
/// </summary>
public class DatiBollo : Common.BusinessObject
{
public DatiBollo() { }
public DatiBollo(XmlReader r) : base(r) { }
protected override List<Validator> CreateRules() {
var rules = base.CreateRules();
rules.Add(new AndCompositeValidator("NumeroBollo", new List<Validator>{new FRequiredValidator(), new FLengthValidator(14)}));
rules.Add(new FRequiredValidator("ImportoRitenuta"));
return rules;
}
#region Properties
/// IMPORTANT
/// Each data property must be flagged with the Order attribute or it will be ignored.
/// Also, properties must be listed with the precise order in the specification.
/// <summary>
/// Numero del bollo.
/// </summary>
[DataProperty]
public string NumeroBollo { get; set; }
/// <summary>
/// Importo del bollo.
/// </summary>
[DataProperty]
public decimal? ImportoBollo { get; set; }
#endregion
}
}
| bsd-3-clause | C# |
681ea28234227d4579425b0dadecd1dd5c69b02d | fix broken xml pipeline : thrown with ExceptionHandlerFlags and other enums when combined (because [Flags] not present) | hmah/boo,BillHally/boo,rmboggs/boo,KingJiangNet/boo,KingJiangNet/boo,BillHally/boo,hmah/boo,drslump/boo,scottstephens/boo,wbardzinski/boo,bamboo/boo,bamboo/boo,hmah/boo,KidFashion/boo,wbardzinski/boo,BITechnologies/boo,scottstephens/boo,hmah/boo,rmboggs/boo,KidFashion/boo,KingJiangNet/boo,BITechnologies/boo,BitPuffin/boo,rmboggs/boo,KingJiangNet/boo,drslump/boo,rmartinho/boo,rmboggs/boo,KingJiangNet/boo,scottstephens/boo,rmartinho/boo,Unity-Technologies/boo,boo-lang/boo,boo-lang/boo,rmartinho/boo,BitPuffin/boo,BITechnologies/boo,BITechnologies/boo,rmartinho/boo,KidFashion/boo,BillHally/boo,KidFashion/boo,Unity-Technologies/boo,drslump/boo,Unity-Technologies/boo,BillHally/boo,scottstephens/boo,boo-lang/boo,bamboo/boo,bamboo/boo,KingJiangNet/boo,BITechnologies/boo,rmartinho/boo,rmboggs/boo,boo-lang/boo,BITechnologies/boo,boo-lang/boo,Unity-Technologies/boo,BITechnologies/boo,drslump/boo,bamboo/boo,rmartinho/boo,wbardzinski/boo,KidFashion/boo,wbardzinski/boo,boo-lang/boo,scottstephens/boo,rmartinho/boo,hmah/boo,Unity-Technologies/boo,KingJiangNet/boo,BitPuffin/boo,wbardzinski/boo,KidFashion/boo,BitPuffin/boo,BitPuffin/boo,BillHally/boo,bamboo/boo,scottstephens/boo,rmboggs/boo,BitPuffin/boo,Unity-Technologies/boo,boo-lang/boo,scottstephens/boo,BitPuffin/boo,hmah/boo,KingJiangNet/boo,Unity-Technologies/boo,drslump/boo,hmah/boo,wbardzinski/boo,BillHally/boo,BillHally/boo,KidFashion/boo,BitPuffin/boo,wbardzinski/boo,bamboo/boo,rmboggs/boo,boo-lang/boo,wbardzinski/boo,BITechnologies/boo,hmah/boo,rmboggs/boo,rmartinho/boo,hmah/boo,scottstephens/boo,drslump/boo,drslump/boo,Unity-Technologies/boo | scripts/Templates/Enum.cs | scripts/Templates/Enum.cs | ${header}
namespace Boo.Lang.Compiler.Ast
{
using System;
[Serializable]
<% if node.Attributes.Contains("Flags"):
%> [Flags]
<% end
%> public enum ${node.Name}
{
<%
last = node.Members[-1]
separator = ","
for field as EnumMember in node.Members:
if field.Initializer:
initializer = " = ${field.Initializer.Value}"
else:
initializer = ""
end
separator = "" if field is last
%> ${field.Name}${initializer}${separator}
<%
end
%> }
}
| ${header}
namespace Boo.Lang.Compiler.Ast
{
using System;
[Serializable]
<% if node.Name.EndsWith("Modifiers"):
%> [Flags]
<% end
%> public enum ${node.Name}
{
<%
last = node.Members[-1]
separator = ","
for field as EnumMember in node.Members:
if field.Initializer:
initializer = " = ${field.Initializer.Value}"
else:
initializer = ""
end
separator = "" if field is last
%> ${field.Name}${initializer}${separator}
<%
end
%> }
}
| bsd-3-clause | C# |
62beab8dbcfa5320b0ee08c6e8fb277cf8b9a1b0 | Rename variable. | mavasani/roslyn,cston/roslyn,jasonmalinowski/roslyn,jcouv/roslyn,tannergooding/roslyn,physhi/roslyn,dotnet/roslyn,paulvanbrenk/roslyn,nguerrera/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,brettfo/roslyn,VSadov/roslyn,sharwell/roslyn,nguerrera/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,tannergooding/roslyn,bkoelman/roslyn,sharwell/roslyn,physhi/roslyn,jcouv/roslyn,panopticoncentral/roslyn,agocke/roslyn,bkoelman/roslyn,agocke/roslyn,DustinCampbell/roslyn,stephentoub/roslyn,weltkante/roslyn,OmarTawfik/roslyn,cston/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,weltkante/roslyn,dpoeschl/roslyn,panopticoncentral/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jmarolf/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,wvdd007/roslyn,xasx/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,jamesqo/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,heejaechang/roslyn,dpoeschl/roslyn,genlu/roslyn,aelij/roslyn,paulvanbrenk/roslyn,davkean/roslyn,wvdd007/roslyn,stephentoub/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,OmarTawfik/roslyn,dpoeschl/roslyn,paulvanbrenk/roslyn,OmarTawfik/roslyn,eriawan/roslyn,brettfo/roslyn,bartdesmet/roslyn,wvdd007/roslyn,jcouv/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tannergooding/roslyn,VSadov/roslyn,jmarolf/roslyn,bkoelman/roslyn,abock/roslyn,VSadov/roslyn,diryboy/roslyn,physhi/roslyn,tmeschter/roslyn,AlekseyTs/roslyn,MichalStrehovsky/roslyn,jasonmalinowski/roslyn,swaroop-sridhar/roslyn,aelij/roslyn,jamesqo/roslyn,AmadeusW/roslyn,heejaechang/roslyn,gafter/roslyn,cston/roslyn,xasx/roslyn,genlu/roslyn,tmat/roslyn,AmadeusW/roslyn,jmarolf/roslyn,reaction1989/roslyn,tmeschter/roslyn,tmeschter/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,reaction1989/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,davkean/roslyn,jamesqo/roslyn,gafter/roslyn,mavasani/roslyn,mavasani/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,tmat/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,diryboy/roslyn,abock/roslyn,gafter/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,agocke/roslyn,brettfo/roslyn,eriawan/roslyn,xasx/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,DustinCampbell/roslyn,heejaechang/roslyn,diryboy/roslyn,AlekseyTs/roslyn,weltkante/roslyn,abock/roslyn | src/Workspaces/Core/Portable/EmbeddedLanguages/Common/EmbeddedDiagnostic.cs | src/Workspaces/Core/Portable/EmbeddedLanguages/Common/EmbeddedDiagnostic.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common
{
/// <summary>
/// Represents an error in a embedded language snippet. The error contains the message to show
/// a user as well as the span of the error. This span is in actual user character coordinates.
/// For example, if the user has the string "...\\p{0}..." then the span of the error would be
/// for the range of characters for '\\p{0}' (even though the regex engine would only see the \\
/// translated as a virtual char to the single \ character.
/// </summary>
internal struct EmbeddedDiagnostic : IEquatable<EmbeddedDiagnostic>
{
public readonly string Message;
public readonly TextSpan Span;
public EmbeddedDiagnostic(string message, TextSpan span)
{
Debug.Assert(message != null);
Message = message;
Span = span;
}
public override bool Equals(object obj)
=> obj is EmbeddedDiagnostic diagnostic && Equals(diagnostic);
public bool Equals(EmbeddedDiagnostic other)
=> Message == other.Message &&
Span.Equals(other.Span);
public override int GetHashCode()
{
unchecked
{
var hashCode = -954867195;
hashCode = hashCode * -1521134295 + base.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Message);
hashCode = hashCode * -1521134295 + EqualityComparer<TextSpan>.Default.GetHashCode(Span);
return hashCode;
}
}
public static bool operator ==(EmbeddedDiagnostic diagnostic1, EmbeddedDiagnostic diagnostic2)
=> diagnostic1.Equals(diagnostic2);
public static bool operator !=(EmbeddedDiagnostic diagnostic1, EmbeddedDiagnostic diagnostic2)
=> !(diagnostic1 == diagnostic2);
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common
{
/// <summary>
/// Represents an error in a embedded language snippet. The error contains the message to show
/// a user as well as the span of the error. This span is in actual user character coordinates.
/// For example, if the user has the string "...\\p{0}..." then the span of the error would be
/// for the range of characters for '\\p{0}' (even though the regex engine would only see the \\
/// translated as a virtual char to the single \ character.
/// </summary>
internal struct EmbeddedDiagnostic : IEquatable<EmbeddedDiagnostic>
{
public readonly string Message;
public readonly TextSpan Span;
public EmbeddedDiagnostic(string message, TextSpan span)
{
Debug.Assert(message != null);
Message = message;
Span = span;
}
public override bool Equals(object obj)
=> obj is EmbeddedDiagnostic rd && Equals(rd);
public bool Equals(EmbeddedDiagnostic other)
=> Message == other.Message &&
Span.Equals(other.Span);
public override int GetHashCode()
{
unchecked
{
var hashCode = -954867195;
hashCode = hashCode * -1521134295 + base.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Message);
hashCode = hashCode * -1521134295 + EqualityComparer<TextSpan>.Default.GetHashCode(Span);
return hashCode;
}
}
public static bool operator ==(EmbeddedDiagnostic diagnostic1, EmbeddedDiagnostic diagnostic2)
=> diagnostic1.Equals(diagnostic2);
public static bool operator !=(EmbeddedDiagnostic diagnostic1, EmbeddedDiagnostic diagnostic2)
=> !(diagnostic1 == diagnostic2);
}
}
| mit | C# |
d9071cd25cba939000782439166422486de46af2 | Update Viet Nam National Day | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date/PublicHolidays/VietnamProvider.cs | Src/Nager.Date/PublicHolidays/VietnamProvider.cs | using Nager.Date.Contract;
using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
/// <summary>
/// Vietnam
/// </summary>
public class VietnamProvider : IPublicHolidayProvider
{
/// <summary>
/// VietnamProvider
/// </summary>
public VietnamProvider()
{
}
/// <summary>
/// Get
/// </summary>
/// <param name="year">The year</param>
/// <returns></returns>
public IEnumerable<PublicHoliday> Get(int year)
{
//TODO: Add Lunar Calendar support
//Add Tết (Tết Nguyên Đán)
//Add Hung Kings Commemorations (Giỗ tổ Hùng Vương)
var countryCode = CountryCode.VN;
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "Tết dương lịch", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 4, 30, "Ngày Giải phóng miền Nam, thống nhất đất nước", "Reunification Day", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "Ngày Quốc tế lao động", "Labour Day", countryCode));
items.Add(new PublicHoliday(year, 9, 2, "Quốc khánh", "National Day", countryCode));
return items.OrderBy(o => o.Date);
}
/// <summary>
/// Get the Holiday Sources
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetSources()
{
return new string[]
{
"https://en.wikipedia.org/wiki/Public_holidays_in_Vietnam"
};
}
}
}
| using Nager.Date.Contract;
using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
/// <summary>
/// Vietnam
/// </summary>
public class VietnamProvider : IPublicHolidayProvider
{
/// <summary>
/// VietnamProvider
/// </summary>
public VietnamProvider()
{
}
/// <summary>
/// Get
/// </summary>
/// <param name="year">The year</param>
/// <returns></returns>
public IEnumerable<PublicHoliday> Get(int year)
{
//TODO: Add Lunar Calendar support
//Add Tết (Tết Nguyên Đán)
//Add Hung Kings Commemorations (Giỗ tổ Hùng Vương)
var countryCode = CountryCode.VN;
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "Tết dương lịch", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 4, 30, "Ngày Giải phóng miền Nam, thống nhất đất nước", "Reunification Day", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "Ngày Quốc tế lao động", "Labour Day", countryCode));
items.Add(new PublicHoliday(year, 10, 1, "Quốc khánh", "National Day", countryCode));
return items.OrderBy(o => o.Date);
}
/// <summary>
/// Get the Holiday Sources
/// </summary>
/// <returns></returns>
public IEnumerable<string> GetSources()
{
return new string[]
{
"https://en.wikipedia.org/wiki/Public_holidays_in_Vietnam"
};
}
}
}
| mit | C# |
85bff078eed416548f8081223713b3406bcfaa65 | Rename the property Variable to Percentage (#148) | Viincenttt/MollieApi,Viincenttt/MollieApi | Mollie.Api/Models/Settlement/SettlementPeriodCostsRate.cs | Mollie.Api/Models/Settlement/SettlementPeriodCostsRate.cs | namespace Mollie.Api.Models.Settlement
{
public class SettlementPeriodCostsRate {
/// <summary>
/// An amount object describing the fixed costs.
/// </summary>
public Amount Fixed { get; set; }
/// <summary>
/// A string describing the variable costs as a percentage.
/// </summary>
public string Percentage { get; set; }
}
}
| namespace Mollie.Api.Models.Settlement
{
public class SettlementPeriodCostsRate {
/// <summary>
/// An amount object describing the fixed costs.
/// </summary>
public Amount Fixed { get; set; }
/// <summary>
/// A string describing the variable costs as a percentage.
/// </summary>
public string Variable { get; set; }
}
} | mit | C# |
1fab7add9386ec31c9c9ef47aaf281deac8c02aa | Revert "Try fix for tracking metrics with square brackets in name" | hinteadan/Metrics.NET.GAReporting | Metrics.Reporters.GoogleAnalytics/Metrics.Reporters.GoogleAnalytics.Tracker/Model/Metric.cs | Metrics.Reporters.GoogleAnalytics/Metrics.Reporters.GoogleAnalytics.Tracker/Model/Metric.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol.Values;
namespace Metrics.Reporters.GoogleAnalytics.Tracker.Model
{
public abstract class Metric : ICanReportToGoogleAnalytics
{
public abstract string Name { get; }
public virtual ParameterTextValue HitType
{
get
{
return HitTypeValue.Event;
}
}
public virtual IEnumerable<Parameter> Parameters
{
get
{
return new Parameter[] {
Parameter.Boolean(ParameterName.HitNonInteractive, ParameterBooleanValue.True),
Parameter.Text(ParameterName.EventLabel, new EventLabelValue(this.Name))
};
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol;
using Metrics.Reporters.GoogleAnalytics.Tracker.Model.MeasurementProtocol.Values;
namespace Metrics.Reporters.GoogleAnalytics.Tracker.Model
{
public abstract class Metric : ICanReportToGoogleAnalytics
{
public abstract string Name { get; }
protected string TrackableName
{
get
{
return this.Name.Replace('[', '~').Replace(']', '~');
}
}
public virtual ParameterTextValue HitType
{
get
{
return HitTypeValue.Event;
}
}
public virtual IEnumerable<Parameter> Parameters
{
get
{
return new Parameter[] {
Parameter.Boolean(ParameterName.HitNonInteractive, ParameterBooleanValue.True),
Parameter.Text(ParameterName.EventLabel, new EventLabelValue(this.TrackableName))
};
}
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.