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 |
---|---|---|---|---|---|---|---|---|
08bee26f4434945d4fa9836afbf81ce371df9292 | Update SharedAssemblyInfo.cs | wieslawsoltes/PanAndZoom,wieslawsoltes/PanAndZoom,PanAndZoom/PanAndZoom,wieslawsoltes/MatrixPanAndZoomDemo,PanAndZoom/PanAndZoom | src/Shared/SharedAssemblyInfo.cs | src/Shared/SharedAssemblyInfo.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.Reflection;
[assembly: AssemblyCompany("Wiesław Šoltés")]
[assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
| // 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.Reflection;
[assembly: AssemblyCompany("Wiesław Šoltés")]
[assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.5.1")]
[assembly: AssemblyFileVersion("0.5.1")]
[assembly: AssemblyInformationalVersion("0.5.1")]
| mit | C# |
a9cf1d0225935a484b610d20130a88cb52f3a57c | Update EnumFlagsAttributeDrawer.cs | Tassim/UnityEnumFlags | UnityEnumFlags/Assets/Tassim/EnumFlags/Scripts/Editor/EnumFlagsAttributeDrawer.cs | UnityEnumFlags/Assets/Tassim/EnumFlags/Scripts/Editor/EnumFlagsAttributeDrawer.cs | // from http://www.sharkbombs.com/2015/02/17/unity-editor-enum-flags-as-toggle-buttons/
// Extended by Tassim
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(EnumFlagsAttribute))]
public class EnumFlagsAttributeDrawer : PropertyDrawer {
public override void OnGUI(Rect pos, SerializedProperty prop, GUIContent label) {
// -1 accounts for the Default value wich should always be 0, thus not displayed
bool[] buttons = new bool[prop.enumNames.Length - 1];
float buttonWidth = (pos.width - (label == GUIContent.none ? 0 : EditorGUIUtility.labelWidth)) / buttons.Length;
if (label != GUIContent.none) {
EditorGUI.LabelField(new Rect(pos.x, pos.y, EditorGUIUtility.labelWidth, pos.height), label);
}
// Handle button value
EditorGUI.BeginChangeCheck();
int buttonsValue = 0;
for (int i = 0; i < buttons.Length; i++) {
// Check if the button is/was pressed
if ((prop.intValue & (1 << i)) == (1 << i)) {
buttons[i] = true;
}
// Display the button
Rect buttonPos = new Rect(pos.x + (label == GUIContent.none ? 0 : EditorGUIUtility.labelWidth) + buttonWidth * i, pos.y, buttonWidth, pos.height);
buttons[i] = GUI.Toggle(buttonPos, buttons[i], prop.enumNames[i + 1], "Button");
if (buttons[i]) {
buttonsValue += 1 << i;
}
}
// This is set to true if a control changed in the previous BeginChangeCheck block
if (EditorGUI.EndChangeCheck()) {
prop.intValue = buttonsValue;
}
}
}
| // from http://www.sharkbombs.com/2015/02/17/unity-editor-enum-flags-as-toggle-buttons/
// Extended by Tassim to handle GUIContent.none // mailto : [email protected]
// Also, flags should always start with a default value of 0, this was not considered
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(EnumFlagsAttribute))]
public class EnumFlagsAttributeDrawer : PropertyDrawer {
public override void OnGUI(Rect pos, SerializedProperty prop, GUIContent label) {
// -1 accounts for the Default value wich should always be 0, thus not displayed
bool[] buttons = new bool[prop.enumNames.Length - 1];
float buttonWidth = (pos.width - (label == GUIContent.none ? 0 : EditorGUIUtility.labelWidth)) / buttons.Length;
if (label != GUIContent.none) {
EditorGUI.LabelField(new Rect(pos.x, pos.y, EditorGUIUtility.labelWidth, pos.height), label);
}
// Handle button value
EditorGUI.BeginChangeCheck();
int buttonsValue = 0;
for (int i = 0; i < buttons.Length; i++) {
// Check if the button is/was pressed
if ((prop.intValue & (1 << i)) == (1 << i)) {
buttons[i] = true;
}
// Display the button
Rect buttonPos = new Rect(pos.x + (label == GUIContent.none ? 0 : EditorGUIUtility.labelWidth) + buttonWidth * i, pos.y, buttonWidth, pos.height);
buttons[i] = GUI.Toggle(buttonPos, buttons[i], prop.enumNames[i + 1], "Button");
if (buttons[i]) {
buttonsValue += 1 << i;
}
}
// This is set to true if a control changed in the previous BeginChangeCheck block
if (EditorGUI.EndChangeCheck()) {
prop.intValue = buttonsValue;
}
}
} | mit | C# |
3096391cae011444767d602046db12ca2593126c | fix code comment | SixLabors/Fonts | src/SixLabors.Fonts/GlyphType.cs | src/SixLabors.Fonts/GlyphType.cs | // Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.Fonts
{
/// <summary>
/// Represents the various version of a glyph records.
/// </summary>
public enum GlyphType
{
/// <summary>
/// This is a fall back glyph due to a missing code point.
/// </summary>
Fallback,
/// <summary>
/// This is a standard glyph to be drawn in the style the user defines.
/// </summary>
Standard,
/// <summary>
/// This is a single layer of the multi-layer colored glyph (emoji).
/// </summary>
ColrLayer
}
}
| // Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.Fonts
{
/// <summary>
/// Represents the various version of a glyph records.
/// </summary>
public enum GlyphType
{
/// <summary>
/// This is a fall back glyph dure to missing code point
/// </summary>
Fallback,
/// <summary>
/// This is a standard glyph to be drawn in the style the user defines.
/// </summary>
Standard,
/// <summary>
/// This is a single layer of the multi-layer colored glyph (emoji)
/// </summary>
ColrLayer
}
}
| apache-2.0 | C# |
5e0ccb6c91d3e1d55968882b80d3ba0eca1971a0 | Remove unncessary test step | ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,peppy/osu,peppy/osu | osu.Game.Tournament.Tests/Components/TestSceneTournamentModDisplay.cs | osu.Game.Tournament.Tests/Components/TestSceneTournamentModDisplay.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 osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Tests.Components
{
public class TestSceneTournamentModDisplay : TournamentTestScene
{
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private RulesetStore rulesets { get; set; }
private FillFlowContainer<TournamentBeatmapPanel> fillFlow;
private BeatmapInfo beatmap;
[BackgroundDependencyLoader]
private void load()
{
var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 490154 });
req.Success += success;
api.Queue(req);
Add(fillFlow = new FillFlowContainer<TournamentBeatmapPanel>
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Full,
Spacing = new osuTK.Vector2(10)
});
}
private void success(APIBeatmap apiBeatmap)
{
beatmap = apiBeatmap.ToBeatmap(rulesets);
var mods = rulesets.GetRuleset(Ladder.Ruleset.Value.ID ?? 0).CreateInstance().GetAllMods();
foreach (var mod in mods)
{
fillFlow.Add(new TournamentBeatmapPanel(beatmap, mod.Acronym)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
}
}
}
| // 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.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets;
using osu.Game.Tournament.Components;
namespace osu.Game.Tournament.Tests.Components
{
public class TestSceneTournamentModDisplay : TournamentTestScene
{
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private RulesetStore rulesets { get; set; }
private FillFlowContainer<TournamentBeatmapPanel> fillFlow;
private BeatmapInfo beatmap;
[BackgroundDependencyLoader]
private void load()
{
var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = 490154 });
req.Success += success;
api.Queue(req);
Add(fillFlow = new FillFlowContainer<TournamentBeatmapPanel>
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Direction = FillDirection.Full,
Spacing = new osuTK.Vector2(10)
});
}
[Test]
public void TestModDisplay()
{
AddUntilStep("beatmap is available", () => beatmap != null);
AddStep("add maps with available mods for ruleset", () => displayForRuleset(Ladder.Ruleset.Value.ID ?? 0));
}
private void displayForRuleset(int rulesetId)
{
fillFlow.Clear();
var mods = rulesets.GetRuleset(rulesetId).CreateInstance().GetAllMods();
foreach (var mod in mods)
{
fillFlow.Add(new TournamentBeatmapPanel(beatmap, mod.Acronym));
}
}
private void success(APIBeatmap apiBeatmap) => beatmap = apiBeatmap.ToBeatmap(rulesets);
}
}
| mit | C# |
ebc1f7c471e9f7f6e231d2f1b79b04ceb08dd277 | Clarify that timestamps in semantics events are UTC-based | mdesalvo/RDFSharp | RDFSharp/Semantics/OWL/RDFSemanticsEvents.cs | RDFSharp/Semantics/OWL/RDFSemanticsEvents.cs | /*
Copyright 2015-2020 Marco De Salvo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Threading.Tasks;
namespace RDFSharp.Semantics.OWL
{
/// <summary>
/// RDFSemanticsEvents represents a collector for all the events generated within the "RDFSharp.Semantics" namespace
/// </summary>
public static class RDFSemanticsEvents
{
#region OnSemanticsInfo
/// <summary>
/// Event representing an information message generated within the "RDFSharp.Semantics" namespace
/// </summary>
public static event RDFSemanticsInfoEventHandler OnSemanticsInfo = delegate { };
/// <summary>
/// Delegate to handle information events generated within the "RDFSharp.Semantics" namespace
/// </summary>
public delegate void RDFSemanticsInfoEventHandler(string eventMessage);
/// <summary>
/// Internal invoker of the subscribed information event handler
/// </summary>
internal static void RaiseSemanticsInfo(string eventMessage)
=> Parallel.Invoke(() => OnSemanticsInfo(string.Concat(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), ";SEMANTICS_INFO;", eventMessage)));
#endregion
#region OnSemanticsWarning
/// <summary>
/// Event representing a warning message generated within the "RDFSharp.Semantics" namespace
/// </summary>
public static event RDFSemanticsWarningEventHandler OnSemanticsWarning = delegate { };
/// <summary>
/// Delegate to handle warning events generated within the "RDFSharp.Semantics" namespace
/// </summary>
public delegate void RDFSemanticsWarningEventHandler(string eventMessage);
/// <summary>
/// Internal invoker of the subscribed warning event handler
/// </summary>
internal static void RaiseSemanticsWarning(string eventMessage)
=> Parallel.Invoke(() => OnSemanticsWarning(string.Concat(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"), ";SEMANTICS_WARNING;", eventMessage)));
#endregion
}
} | /*
Copyright 2015-2020 Marco De Salvo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Threading.Tasks;
namespace RDFSharp.Semantics.OWL
{
/// <summary>
/// RDFSemanticsEvents represents a collector for all the events generated within the "RDFSharp.Semantics" namespace
/// </summary>
public static class RDFSemanticsEvents
{
#region OnSemanticsInfo
/// <summary>
/// Event representing an information message generated within the "RDFSharp.Semantics" namespace
/// </summary>
public static event RDFSemanticsInfoEventHandler OnSemanticsInfo = delegate { };
/// <summary>
/// Delegate to handle information events generated within the "RDFSharp.Semantics" namespace
/// </summary>
public delegate void RDFSemanticsInfoEventHandler(string eventMessage);
/// <summary>
/// Internal invoker of the subscribed information event handler
/// </summary>
internal static void RaiseSemanticsInfo(string eventMessage)
=> Parallel.Invoke(() => OnSemanticsInfo(string.Concat(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss"), ";SEMANTICS_INFO;", eventMessage)));
#endregion
#region OnSemanticsWarning
/// <summary>
/// Event representing a warning message generated within the "RDFSharp.Semantics" namespace
/// </summary>
public static event RDFSemanticsWarningEventHandler OnSemanticsWarning = delegate { };
/// <summary>
/// Delegate to handle warning events generated within the "RDFSharp.Semantics" namespace
/// </summary>
public delegate void RDFSemanticsWarningEventHandler(string eventMessage);
/// <summary>
/// Internal invoker of the subscribed warning event handler
/// </summary>
internal static void RaiseSemanticsWarning(string eventMessage)
=> Parallel.Invoke(() => OnSemanticsWarning(string.Concat(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss"), ";SEMANTICS_WARNING;", eventMessage)));
#endregion
}
} | apache-2.0 | C# |
0ef7ee8d7b4cbf437d8839d176b18bf279391188 | Add GetProperty method to TestHelpers | Shaddix/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet | Tests/IntegrationTests.Shared/TestHelpers.cs | Tests/IntegrationTests.Shared/TestHelpers.cs | /* Copyright 2015 Realm Inc - All Rights Reserved
* Proprietary and Confidential
*/
using System.IO;
using Realms;
#if __IOS__
using Foundation;
#endif
namespace IntegrationTests
{
public static class TestHelpers
{
public static object GetPropertyValue(object o, string propName)
{
return o.GetType().GetProperty(propName).GetValue(o, null);
}
public static void SetPropertyValue(object o, string propName, object propertyValue)
{
o.GetType().GetProperty(propName).SetValue(o, propertyValue);
}
public static T GetPropertyValue<T>(this object obj, string propertyName)
{
return (T) GetPropertyValue(obj, propertyName);
}
public static void CopyBundledDatabaseToDocuments(string realmName, string destPath=null, bool overwrite=true)
{
string sourceDir = "";
#if __IOS__
sourceDir = NSBundle.MainBundle.BundlePath;
#endif
//TODO add cases for Android and Windows setting sourcedir for bundled files
destPath = RealmConfiguration.PathToRealm(destPath); // any relative subdir or filename works
File.Copy(Path.Combine(sourceDir, realmName), destPath, overwrite);
}
}
}
| /* Copyright 2015 Realm Inc - All Rights Reserved
* Proprietary and Confidential
*/
using System;
using System.Reflection;
using System.IO;
using Realms;
#if __IOS__
using Foundation;
#endif
namespace IntegrationTests
{
public static class TestHelpers
{
private static PropertyInfo GetPropertyInfo(Type type, string propertyName)
{
PropertyInfo propInfo = null;
do
{
propInfo = type.GetTypeInfo().GetDeclaredProperty(propertyName);
type = type.GetTypeInfo().BaseType;
}
while (propInfo == null && type != null);
return propInfo;
}
public static T GetPropertyValue<T>(this object obj, string propertyName)
{
var propInfo = GetPropertyInfo(obj.GetType(), propertyName);
return (T)propInfo.GetValue(obj, null);
}
public static void CopyBundledDatabaseToDocuments(string realmName, string destPath=null, bool overwrite=true)
{
string sourceDir = "";
#if __IOS__
sourceDir = NSBundle.MainBundle.BundlePath;
#endif
//TODO add cases for Android and Windows setting sourcedir for bundled files
destPath = RealmConfiguration.PathToRealm(destPath); // any relative subdir or filename works
File.Copy(Path.Combine(sourceDir, realmName), destPath, overwrite);
}
}
}
| apache-2.0 | C# |
ff5881d33a94412f6c89d3653ffb27fae1005d13 | Fix Dependencies | revaturelabs/revashare-svc-webapi | revashare-svc-webapi/revashare-svc-webapi.Logic/Mappers/UserMapper.cs | revashare-svc-webapi/revashare-svc-webapi.Logic/Mappers/UserMapper.cs | using revashare_svc_webapi.Logic.Interfaces;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace revashare_svc_webapi.Logic.Mappers
{
public class UserMapper
{
public static UserDTO mapToUserDTO(UserDAO b)
{
var a = new UserDTO();
if(b.Apartment!=null)
{
a.Apartment =ApartmentMapper.mapToApartmentDTO(b.Apartment);
}
a.Email = b.Email;
a.Name = b.Name;
a.PhoneNumber = b.PhoneNumber;
a.Roles = new List<RoleDTO>();
if(b.Roles!=null)
{
foreach (var item in b.Roles)
{
a.Roles.Add(RoleMapper.mapToRoleDTO(item));
}
}
a.UserName = b.UserName;
return a;
}
public static UserDAO mapToUserDAO(UserDTO b)
{
var a = new UserDAO();
if(b.Apartment!=null)
{
a.Apartment = ApartmentMapper.mapToApartmentDAO(b.Apartment);
}
a.Email = b.Email;
a.Name = b.Name;
a.PhoneNumber = b.PhoneNumber;
a.Roles = new RoleDAO[3];
if (b.Roles != null)
{
for (int i = 0; i < b.Roles.Count; i++)
{
a.Roles[i] = RoleMapper.mapToRoleDAO(b.Roles[i]);
}
}
a.UserName = b.UserName;
return a;
}
}
}
| using revashare_svc_webapi.Logic.Interfaces;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace revashare_svc_webapi.Logic.Mappers
{
public class UserMapper
{
public static UserDTO mapToUserDTO(UserDAO b)
{
var a = new UserDTO();
if(b.Apartment!=null)
{
a.Apartment =ApartmentMapper.mapToApartmentDTO(b.Apartment);
}
a.Email = b.Email;
a.Name = b.Name;
a.PhoneNumber = b.PhoneNumber;
a.Roles = new List<RoleDTO>();
if(b.Roles!=null)
{
foreach (var item in b.Roles)
{
a.Roles.Add(RoleMapper.mapToRoleDTO(item));
}
}
a.UserName = b.UserName;
return a;
}
public static UserDAO mapToUserDAO(UserDTO b)
{
var a = new UserDAO();
if(b.Apartment!=null)
{
a.Apartment = ApartmentMapper.mapToApartmentDAO(b.Apartment);
}
a.Email = b.Email;
a.Name = b.Name;
a.PhoneNumber = b.PhoneNumber;
a.Roles = new RoleDAO[3];
if (b.Roles != null)
{
for (int i = 0; i < b.Roles.Count; i++)
{
a.Roles[i] = RoleMapper.mapToRoleDAO(b.Roles[i]);
}
}
return a;
}
}
}
| mit | C# |
08bf787c09618d3e126ec9bf60290b1561c27062 | Fix error route | SaarCohen/live.asp.net,rmarinho/live.asp.net,M-Zuber/live.asp.net,iaingalloway/live.asp.net,aspnet/live.asp.net,reactiveui/website,hanu412/live.asp.net,TimMurphy/live.asp.net,peterblazejewicz/live.asp.net,rmarinho/live.asp.net,reactiveui/website,TimMurphy/live.asp.net,iaingalloway/live.asp.net,reactiveui/website,sejka/live.asp.net,yongyi781/live.asp.net,SaarCohen/live.asp.net,pakrym/kudutest,M-Zuber/live.asp.net,dotnetdude/live.asp.net,dotnetdude/live.asp.net,peterblazejewicz/live.asp.net,aspnet/live.asp.net,Janisku7/live.asp.net,hanu412/live.asp.net,jmatthiesen/VSTACOLive,matsprea/live.asp.net,aspnet/live.asp.net,pakrym/kudutest,reactiveui/website,sejka/live.asp.net,yongyi781/live.asp.net,matsprea/live.asp.net,jmatthiesen/VSTACOLive,Janisku7/live.asp.net | src/live.asp.net/Controllers/HomeController.cs | src/live.asp.net/Controllers/HomeController.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using live.asp.net.Models;
using live.asp.net.Services;
using live.asp.net.ViewModels;
using Microsoft.AspNet.Mvc;
namespace live.asp.net.Controllers
{
public class HomeController : Controller
{
private readonly ILiveShowDetailsService _liveShowDetails;
private readonly IShowsService _showsService;
public HomeController(IShowsService showsService, ILiveShowDetailsService liveShowDetails)
{
_showsService = showsService;
_liveShowDetails = liveShowDetails;
}
[Route("/")]
public async Task<IActionResult> Index(bool? disableCache)
{
var liveShowDetails = await _liveShowDetails.LoadAsync();
var showList = await _showsService.GetRecordedShowsAsync(User, disableCache ?? false);
return View(new HomeViewModel
{
AdminMessage = liveShowDetails?.AdminMessage,
NextShowDateUtc = liveShowDetails?.NextShowDateUtc,
LiveShowEmbedUrl = liveShowDetails?.LiveShowEmbedUrl,
PreviousShows = showList.Shows,
MoreShowsUrl = showList.MoreShowsUrl
});
}
[HttpGet("/ical")]
[Produces("text/calendar")]
public async Task<LiveShowDetails> GetiCal()
{
var liveShowDetails = await _liveShowDetails.LoadAsync();
return liveShowDetails;
}
[Route("/error")]
public IActionResult Error()
{
return View();
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using live.asp.net.Models;
using live.asp.net.Services;
using live.asp.net.ViewModels;
using Microsoft.AspNet.Mvc;
namespace live.asp.net.Controllers
{
public class HomeController : Controller
{
private readonly ILiveShowDetailsService _liveShowDetails;
private readonly IShowsService _showsService;
public HomeController(IShowsService showsService, ILiveShowDetailsService liveShowDetails)
{
_showsService = showsService;
_liveShowDetails = liveShowDetails;
}
[Route("/")]
public async Task<IActionResult> Index(bool? disableCache)
{
var liveShowDetails = await _liveShowDetails.LoadAsync();
var showList = await _showsService.GetRecordedShowsAsync(User, disableCache ?? false);
return View(new HomeViewModel
{
AdminMessage = liveShowDetails?.AdminMessage,
NextShowDateUtc = liveShowDetails?.NextShowDateUtc,
LiveShowEmbedUrl = liveShowDetails?.LiveShowEmbedUrl,
PreviousShows = showList.Shows,
MoreShowsUrl = showList.MoreShowsUrl
});
}
[HttpGet("/ical")]
[Produces("text/calendar")]
public async Task<LiveShowDetails> GetiCal()
{
var liveShowDetails = await _liveShowDetails.LoadAsync();
return liveShowDetails;
}
[HttpGet("error")]
public IActionResult Error()
{
return View();
}
}
}
| mit | C# |
a80a75ca4c17079097493a6fbda83bfcfd0ca4aa | Fix possible NRE in deckstring deck obj | HearthSim/HearthDb | HearthDb/Deckstrings/Deck.cs | HearthDb/Deckstrings/Deck.cs | using System.Collections.Generic;
using System.Linq;
using HearthDb.Enums;
namespace HearthDb.Deckstrings
{
public class Deck
{
/// <summary>
/// DbfId of the hero. Required.
/// This can be a specific hero for a class, i.e. Medivh over Jaina.
/// </summary>
public int HeroDbfId { get; set; }
/// <summary>
/// Dictionary of (DbfId, Count) for each card.
/// Needs to be a total of 30 cards to be accepted by Hearthstone.
/// </summary>
public Dictionary<int, int> CardDbfIds { get; set; } = new Dictionary<int, int>();
/// <summary>
/// Format of the deck. Required.
/// </summary>
public FormatType Format { get; set; }
/// <summary>
/// Year of the deck format. Optional.
/// </summary>
public ZodiacYear ZodiacYear { get; set; }
/// <summary>
/// Name of the deck. Optional.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Hearthstones internal ID of the deck. Optional.
/// </summary>
public long DeckId { get; set; }
/// <summary>
/// Gets the card object for the given HeroDbfId
/// </summary>
public Card GetHero() => Cards.GetFromDbfId(HeroDbfId, false);
/// <summary>
/// Converts (DbfId, Count) dictionary to (CardObject, Count).
/// </summary>
public Dictionary<Card, int> GetCards() => CardDbfIds
.Select(x => new { Card = Cards.GetFromDbfId(x.Key), Count = x.Value })
.Where(x => x.Card != null).ToDictionary(x => x.Card, x => x.Count);
}
}
| using System.Collections.Generic;
using System.Linq;
using HearthDb.Enums;
namespace HearthDb.Deckstrings
{
public class Deck
{
/// <summary>
/// DbfId of the hero. Required.
/// This can be a specific hero for a class, i.e. Medivh over Jaina.
/// </summary>
public int HeroDbfId { get; set; }
/// <summary>
/// Dictionary of (DbfId, Count) for each card.
/// Needs to be a total of 30 cards to be accepted by Hearthstone.
/// </summary>
public Dictionary<int, int> CardDbfIds { get; set; } = new Dictionary<int, int>();
/// <summary>
/// Format of the deck. Required.
/// </summary>
public FormatType Format { get; set; }
/// <summary>
/// Year of the deck format. Optional.
/// </summary>
public ZodiacYear ZodiacYear { get; set; }
/// <summary>
/// Name of the deck. Optional.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Hearthstones internal ID of the deck. Optional.
/// </summary>
public long DeckId { get; set; }
/// <summary>
/// Gets the card object for the given HeroDbfId
/// </summary>
public Card GetHero() => Cards.GetFromDbfId(HeroDbfId, false);
/// <summary>
/// Converts (DbfId, Count) dictionary to (CardObject, Count).
/// </summary>
public Dictionary<Card, int> GetCards() => CardDbfIds.ToDictionary(x => Cards.GetFromDbfId(x.Key), x => x.Value);
}
} | mit | C# |
5c6cb2bf57c0fc5c49e26183360175a06f86b80b | fix resolve SqlConnectionsFactory | litichevskiydv/Byndyusoft.Dotnet.Core.Infrastructure,Byndyusoft/Byndyusoft.Dotnet.Core.Infrastructure,litichevskiydv/Byndyusoft.Dotnet.Core.Infrastructure,litichevskiydv/Byndyusoft.Dotnet.Core.Infrastructure,Byndyusoft/Byndyusoft.Dotnet.Core.Infrastructure,Byndyusoft/Byndyusoft.Dotnet.Core.Infrastructure | src/Infrastructure/Dapper/ConnectionsFactory/SqlConnectionsFactory.cs | src/Infrastructure/Dapper/ConnectionsFactory/SqlConnectionsFactory.cs | namespace Byndyusoft.Dotnet.Core.Infrastructure.Dapper.ConnectionsFactory
{
using System;
using System.Data;
using Microsoft.Extensions.Options;
public class SqlConnectionsFactory<T> : IDbConnectionsFactory where T : IDbConnection
{
protected readonly SqlConnectionsFactoryOptions _options;
public SqlConnectionsFactory(IOptions<SqlConnectionsFactoryOptions> options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
if (string.IsNullOrWhiteSpace(options.Value.SqlServer))
throw new ArgumentNullException(nameof(SqlConnectionsFactoryOptions.SqlServer));
_options = options.Value;
}
public IDbConnection Create()
{
var sqlConnection = NewSqlConnection();
sqlConnection.Open();
return sqlConnection;
}
protected virtual IDbConnection NewSqlConnection()
{
return (T) Activator.CreateInstance(typeof(T), _options.SqlServer);
}
}
} | namespace Byndyusoft.Dotnet.Core.Infrastructure.Dapper.ConnectionsFactory
{
using System;
using System.Data;
using Microsoft.Extensions.Options;
public class SqlConnectionsFactory<T> : IDbConnectionsFactory where T : IDbConnection
{
protected readonly SqlConnectionsFactoryOptions _options;
protected SqlConnectionsFactory(IOptions<SqlConnectionsFactoryOptions> options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
if (string.IsNullOrWhiteSpace(options.Value.SqlServer))
throw new ArgumentNullException(nameof(SqlConnectionsFactoryOptions.SqlServer));
_options = options.Value;
}
public IDbConnection Create()
{
var sqlConnection = NewSqlConnection();
sqlConnection.Open();
return sqlConnection;
}
protected virtual IDbConnection NewSqlConnection()
{
return (T) Activator.CreateInstance(typeof(T), _options.SqlServer);
}
}
} | mit | C# |
045c6e940dfefe3333da89615e4ded9c3d70d585 | Add filter property to most anticipated shows request. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Shows/Common/TraktShowsMostAnticipatedRequest.cs | Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Shows/Common/TraktShowsMostAnticipatedRequest.cs | namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base;
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedShow>, TraktMostAnticipatedShow>
{
internal TraktShowsMostAnticipatedRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/anticipated{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
internal TraktShowFilter Filter { get; set; }
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
| namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common
{
using Base.Get;
using Objects.Basic;
using Objects.Get.Shows.Common;
internal class TraktShowsMostAnticipatedRequest : TraktGetRequest<TraktPaginationListResult<TraktMostAnticipatedShow>, TraktMostAnticipatedShow>
{
internal TraktShowsMostAnticipatedRequest(TraktClient client) : base(client) { }
protected override string UriTemplate => "shows/anticipated{?extended,page,limit}";
protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired;
protected override bool SupportsPagination => true;
protected override bool IsListResult => true;
}
}
| mit | C# |
f507c057675309033091069d8afbf3ba9831b18f | Fix DoContAbs -> DoCont in conditionally compiled code. | jacqueline-homan/Hopac,Hopac/Hopac,Hopac/Hopac,panesofglass/Hopac,panesofglass/Hopac,jacqueline-homan/Hopac | Libs/Hopac.Core/Flow/Cont.cs | Libs/Hopac.Core/Flow/Cont.cs | // Copyright (C) by Housemarque, Inc.
namespace Hopac.Core {
using Microsoft.FSharp.Core;
using Hopac.Core;
using System;
using System.Runtime.CompilerServices;
/// <summary>Represents a continuation of a parallel job.</summary>
internal abstract class Cont<T> : Work {
internal T Value;
internal virtual Pick GetPick(ref int me) {
return null;
}
/// Use DoCont when NOT invoking continuation from a Job or Alt.
internal abstract void DoCont(ref Worker wr, T value);
}
internal static class Cont {
/// Use Cont.Do when invoking continuation from a Job or Alt.
[MethodImpl(AggressiveInlining.Flag)]
internal static void Do<T>(Cont<T> tK, ref Worker wr, T value) {
#if TRAMPOLINE
unsafe {
byte stack;
void *ptr = &stack;
if (ptr < wr.StackLimit) {
tK.Value = value;
tK.Next = wr.WorkStack;
wr.WorkStack = tK;
} else {
tK.DoCont(ref wr, value);
}
}
#else
tK.DoCont(ref wr, value);
#endif
}
}
internal sealed class FailCont<T> : Cont<T> {
private readonly Handler hr;
private readonly Exception e;
[MethodImpl(AggressiveInlining.Flag)]
internal FailCont(Handler hr, Exception e) {
this.hr = hr;
this.e = e;
}
internal override void DoHandle(ref Worker wr, Exception e) {
Handler.DoHandle(this.hr, ref wr, e);
}
internal override void DoWork(ref Worker wr) {
Handler.DoHandle(this.hr, ref wr, this.e);
}
internal override void DoCont(ref Worker wr, T value) {
Handler.DoHandle(this.hr, ref wr, this.e);
}
}
internal abstract class Cont_State<T, S> : Cont<T> {
internal S State;
[MethodImpl(AggressiveInlining.Flag)]
internal Cont_State() { }
[MethodImpl(AggressiveInlining.Flag)]
internal Cont_State(S s) { State = s; }
}
internal abstract class Cont_State<T, S1, S2> : Cont<T> {
internal S1 State1;
internal S2 State2;
[MethodImpl(AggressiveInlining.Flag)]
internal Cont_State() { }
[MethodImpl(AggressiveInlining.Flag)]
internal Cont_State(S1 s1, S2 s2) { State1 = s1; State2 = s2; }
}
}
| // Copyright (C) by Housemarque, Inc.
namespace Hopac.Core {
using Microsoft.FSharp.Core;
using Hopac.Core;
using System;
using System.Runtime.CompilerServices;
/// <summary>Represents a continuation of a parallel job.</summary>
internal abstract class Cont<T> : Work {
internal T Value;
internal virtual Pick GetPick(ref int me) {
return null;
}
/// Use DoCont when NOT invoking continuation from a Job or Alt.
internal abstract void DoCont(ref Worker wr, T value);
}
internal static class Cont {
/// Use Cont.Do when invoking continuation from a Job or Alt.
[MethodImpl(AggressiveInlining.Flag)]
internal static void Do<T>(Cont<T> tK, ref Worker wr, T value) {
#if TRAMPOLINE
unsafe {
byte stack;
void *ptr = &stack;
if (ptr < wr.StackLimit) {
tK.Value = value;
tK.Next = wr.WorkStack;
wr.WorkStack = tK;
} else {
tK.DoCont(ref wr, value);
}
}
#else
tK.DoContAbs(ref wr, value);
#endif
}
}
internal sealed class FailCont<T> : Cont<T> {
private readonly Handler hr;
private readonly Exception e;
[MethodImpl(AggressiveInlining.Flag)]
internal FailCont(Handler hr, Exception e) {
this.hr = hr;
this.e = e;
}
internal override void DoHandle(ref Worker wr, Exception e) {
Handler.DoHandle(this.hr, ref wr, e);
}
internal override void DoWork(ref Worker wr) {
Handler.DoHandle(this.hr, ref wr, this.e);
}
internal override void DoCont(ref Worker wr, T value) {
Handler.DoHandle(this.hr, ref wr, this.e);
}
}
internal abstract class Cont_State<T, S> : Cont<T> {
internal S State;
[MethodImpl(AggressiveInlining.Flag)]
internal Cont_State() { }
[MethodImpl(AggressiveInlining.Flag)]
internal Cont_State(S s) { State = s; }
}
internal abstract class Cont_State<T, S1, S2> : Cont<T> {
internal S1 State1;
internal S2 State2;
[MethodImpl(AggressiveInlining.Flag)]
internal Cont_State() { }
[MethodImpl(AggressiveInlining.Flag)]
internal Cont_State(S1 s1, S2 s2) { State1 = s1; State2 = s2; }
}
}
| mit | C# |
7bf2df363287b1a77d8eef250bcedcca35a065fb | disable again, will fix in a branch | elastacloud/parquet-dotnet | src/Parquet.Test/CompressionTest.cs | src/Parquet.Test/CompressionTest.cs | using Parquet.Data;
using System.IO;
using Xunit;
namespace Parquet.Test
{
public class CompressionTest : TestBase
{
[Theory]
[InlineData(CompressionMethod.None)]
[InlineData(CompressionMethod.Gzip)]
[InlineData(CompressionMethod.Snappy)]
public void All_compression_methods_supported(CompressionMethod compressionMethod)
{
//v2
var ms = new MemoryStream();
DataSet ds1 = new DataSet(new DataField<int>("id"));
DataSet ds2;
ds1.Add(5);
//write
using (var writer = new ParquetWriter(ms))
{
writer.Write(ds1, CompressionMethod.Gzip);
}
//read back
using (var reader = new ParquetReader(ms))
{
ms.Position = 0;
ds2 = reader.Read();
}
Assert.Equal(5, ds2[0].GetInt(0));
//v3
/*const int value = 5;
object actual = WriteReadSingle(new DataField<int>("id"), value, compressionMethod);
Assert.Equal(5, (int)actual);*/
}
}
}
| using Parquet.Data;
using System.IO;
using Xunit;
namespace Parquet.Test
{
public class CompressionTest : TestBase
{
[Theory]
[InlineData(CompressionMethod.None)]
[InlineData(CompressionMethod.Gzip)]
[InlineData(CompressionMethod.Snappy)]
public void All_compression_methods_supported(CompressionMethod compressionMethod)
{
//v2
var ms = new MemoryStream();
DataSet ds1 = new DataSet(new DataField<int>("id"));
DataSet ds2;
ds1.Add(5);
//write
using (var writer = new ParquetWriter(ms))
{
writer.Write(ds1, CompressionMethod.Gzip);
}
//read back
using (var reader = new ParquetReader(ms))
{
ms.Position = 0;
ds2 = reader.Read();
}
Assert.Equal(5, ds2[0].GetInt(0));
//v3
const int value = 5;
object actual = WriteReadSingle(new DataField<int>("id"), value, compressionMethod);
Assert.Equal(5, (int)actual);
}
}
}
| mit | C# |
e596a4746395e1c4c8b4c9e5d49787f285b2d5fe | Update AreaTests.cs | willrawls/xlg,willrawls/xlg | MetX/MetX.Tests/AreaTests.cs | MetX/MetX.Tests/AreaTests.cs | using MetX.Five;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MetX.Tests
{
[TestClass]
public class AreaTests
{
[TestMethod]
public void New_TemplateInstruction_TableQuestionMark()
{
var processingAlreadyBeganPreviously = false;
var area = new Area("Template", "~~Template: Table ?", ref processingAlreadyBeganPreviously);
Assert.AreEqual(InstructionType.Template, area.InstructionType);
Assert.AreEqual(2, area.Arguments.Count);
Assert.AreEqual(TemplateType.Table, area.TemplateType);
Assert.AreEqual("?", area.Target);
}
}
}
| using MetX.Five;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MetX.Tests
{
[TestClass]
public class AreaTests
{
[TestMethod]
public void Test()
{
//TestCop
Assert.Fail("WriteMe");
}
[TestMethod]
public void New_TemplateInstruction_TableQuestionMark()
{
var processingAlreadyBeganPreviously = false;
var area = new Area("Template", "~~Template: Table ?", ref processingAlreadyBeganPreviously);
Assert.AreEqual(InstructionType.Template, area.InstructionType);
Assert.AreEqual(2, area.Arguments.Count);
Assert.AreEqual(TemplateType.Table, area.TemplateType);
Assert.AreEqual("?", area.Target);
}
}
}
| mit | C# |
315b7b32a2416f16384c5a531b8358f3cd259704 | Active column should be Accepted. | henkmollema/StudentFollowingSystem,henkmollema/StudentFollowingSystem | src/StudentFollowingSystem/Data/Repositories/AppointmentRepository.cs | src/StudentFollowingSystem/Data/Repositories/AppointmentRepository.cs | using StudentFollowingSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;
namespace StudentFollowingSystem.Data.Repositories
{
public class AppointmentRepository : RepositoryBase<Appointment>
{
public List<Appointment> GetAppointmentsByCounseler(int counselerId, DateTime toDate, DateTime nowDate)
{
using (var con = ConnectionFactory.GetOpenConnection())
{
string sql = @"
select * from Appointments a
inner join Students s on a.StudentId = s.Id
where a.Accepted = 1 and a.CounselerId = @counselerId and a.DateTime < @toDate and a.DateTime >= @nowDate
order by a.DateTime";
return con.Query<Appointment, Student, Appointment>(sql, (a, s) =>
{
a.Student = s;
return a;
},
new { counselerId = counselerId, toDate = toDate, nowDate = nowDate })
.ToList();
}
}
}
} | using StudentFollowingSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Dapper;
namespace StudentFollowingSystem.Data.Repositories
{
public class AppointmentRepository : RepositoryBase<Appointment>
{
public List<Appointment> GetAppointmentsByCounseler(int counselerId, DateTime toDate, DateTime nowDate)
{
using (var con = ConnectionFactory.GetOpenConnection())
{
string sql = @"
select * from Appointments a
inner join Students s on a.StudentId = s.Id
where a.Active = 1 and a.CounselerId = @counselerId and a.DateTime < @toDate and a.DateTime >= @nowDate
order by a.DateTime";
return con.Query<Appointment, Student, Appointment>(sql, (a, s) =>
{
a.Student = s;
return a;
},
new { counselerId = counselerId, toDate = toDate, nowDate = nowDate })
.ToList();
}
}
}
} | mit | C# |
f3f9b12270b9244e5d560b61708dcf10594537b9 | Add dots to experiment names so they can be enabled as feature flags. | brettfo/roslyn,reaction1989/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,bartdesmet/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,brettfo/roslyn,diryboy/roslyn,jmarolf/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,jmarolf/roslyn,gafter/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,genlu/roslyn,stephentoub/roslyn,stephentoub/roslyn,genlu/roslyn,agocke/roslyn,panopticoncentral/roslyn,physhi/roslyn,physhi/roslyn,agocke/roslyn,tannergooding/roslyn,gafter/roslyn,AmadeusW/roslyn,mavasani/roslyn,tmat/roslyn,jasonmalinowski/roslyn,tmat/roslyn,physhi/roslyn,reaction1989/roslyn,eriawan/roslyn,bartdesmet/roslyn,eriawan/roslyn,reaction1989/roslyn,sharwell/roslyn,stephentoub/roslyn,AmadeusW/roslyn,aelij/roslyn,eriawan/roslyn,jmarolf/roslyn,abock/roslyn,davkean/roslyn,abock/roslyn,KevinRansom/roslyn,wvdd007/roslyn,wvdd007/roslyn,mavasani/roslyn,heejaechang/roslyn,genlu/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,aelij/roslyn,abock/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,dotnet/roslyn,tannergooding/roslyn,KevinRansom/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,agocke/roslyn,heejaechang/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,aelij/roslyn,davkean/roslyn,heejaechang/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,diryboy/roslyn,tmat/roslyn | src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs | src/Workspaces/Core/Portable/Experiments/IExperimentationService.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.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
public const string RoslynInlineRenameFile = "Roslyn.FileRename";
// Syntactic LSP experiment treatments.
public const string SyntacticExp_LiveShareTagger_Remote = "Roslyn.LspTagger";
public const string SyntacticExp_LiveShareTagger_TextMate = "Roslyn.TextMateTagger";
}
}
| // 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.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
public bool ReturnValue = false;
[ImportingConstructor]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => ReturnValue;
}
internal static class WellKnownExperimentNames
{
public const string RoslynOOP64bit = nameof(RoslynOOP64bit);
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string NativeEditorConfigSupport = "Roslyn.NativeEditorConfigSupport";
public const string RoslynInlineRenameFile = "Roslyn.FileRename";
// Syntactic LSP experiment treatments.
public const string SyntacticExp_LiveShareTagger_Remote = "RoslynLsp_Tagger";
public const string SyntacticExp_LiveShareTagger_TextMate = "RoslynTextMate_Tagger";
}
}
| mit | C# |
8e35e1a1e9dfa210e5f11864311a815e6d24b6de | add invalid constructor | geeklearningio/gl-dotnet-domain | src/GeekLearning.Domain.Primitives/Explanations/Invalid.cs | src/GeekLearning.Domain.Primitives/Explanations/Invalid.cs | namespace GeekLearning.Domain.Explanations
{
using System.Collections.Generic;
using System.Linq;
public class Invalid : Explanation
{
public Invalid(string message, IEnumerable<Explanation> details)
: base(message, details)
{
}
public Invalid(string message, string innerMessage, IEnumerable<Explanation> details)
: base(message, innerMessage, details)
{
}
public Invalid(string message, string innerMessage, IEnumerable<Explanation> details, object data)
: base(message, innerMessage, details, data)
{
}
public Invalid(string message, string internalMessage)
: base(message, internalMessage)
{
}
public Invalid(string message)
: this(message, Enumerable.Empty<Explanation>())
{
}
public Invalid()
: this("Object was invalid", Enumerable.Empty<Explanation>())
{
}
public Invalid(object key)
: this($"Object with '{ key.ToString() }' was invalid.", Enumerable.Empty<Explanation>())
{
}
public Invalid(object key, IEnumerable<Explanation> details)
: this($"Object with '{ key.ToString() }' was invalid.", details)
{
}
}
}
| namespace GeekLearning.Domain.Explanations
{
using System.Collections.Generic;
using System.Linq;
public class Invalid : Explanation
{
public Invalid(string message, IEnumerable<Explanation> details)
: base(message, details)
{
}
public Invalid(string message, string innerMessage, IEnumerable<Explanation> details)
: base(message, details)
{
}
public Invalid(string message, string internalMessage)
: base(message, internalMessage)
{
}
public Invalid(string message)
: this(message, Enumerable.Empty<Explanation>())
{
}
public Invalid()
: this("Object was invalid", Enumerable.Empty<Explanation>())
{
}
public Invalid(object key)
: this($"Object with '{ key.ToString() }' was invalid.", Enumerable.Empty<Explanation>())
{
}
public Invalid(object key, IEnumerable<Explanation> details)
: this($"Object with '{ key.ToString() }' was invalid.", details)
{
}
}
}
| mit | C# |
6fa21b93d34cf9716b733f12b43e19f299eb166f | update test | wangkanai/Detection | src/Responsive/test/ResponsiveCollectionExtensionsTests.cs | src/Responsive/test/ResponsiveCollectionExtensionsTests.cs | // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Wangkanai.Responsive.Test
{
public class ResponsiveCollectionExtensionsTests
{
[Fact]
public void AddResponsive_Services()
{
var service = new ServiceCollection();
var builder = service.AddResponsive();
Assert.Equal(16, builder.Services.Count);
Assert.Same(service, builder.Services);
}
[Fact]
public void AddResponsive_Null_ArgumentNullException()
{
Assert.Throws<AddResponsiveArgumentNullException>(CreateResponsiveNullService);
}
[Fact]
public void AddResponsive_Option_Builder_Service()
{
var service = new ServiceCollection();
var builder = service.AddResponsive(options =>
{
options.View.DefaultTablet = Detection.DeviceType.Desktop;
});
Assert.Equal(16, builder.Services.Count);
Assert.Same(service, builder.Services);
}
[Fact]
public void AddResponsive_Options_Null_ArgumentNullException()
{
Assert.Throws<AddResponsiveArgumentNullException>(CreateResponsiveNullService);
}
private Func<object> CreateResponsiveNullService = () => ((IServiceCollection)null).AddResponsive();
}
}
| // Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Wangkanai.Responsive.Test
{
public class ResponsiveCollectionExtensionsTests
{
[Fact]
public void AddResponsive_Services()
{
var service = new ServiceCollection();
var builder = service.AddResponsive();
Assert.Equal(12, builder.Services.Count);
Assert.Same(service, builder.Services);
}
[Fact]
public void AddResponsive_Null_ArgumentNullException()
{
Func<object> CreateNullService = () =>
{
return ((IServiceCollection)null).AddResponsive();
};
Assert.Throws<AddResponsiveArgumentNullException>(CreateNullService);
}
[Fact]
public void AddResponsive_Option_Builder_Service()
{
var service = new ServiceCollection();
var builder = service.AddResponsive(options =>
{
options.View.DefaultTablet = Detection.DeviceType.Desktop;
});
Assert.Equal(12, builder.Services.Count);
Assert.Same(service, builder.Services);
}
[Fact]
public void AddResponsive_Options_Null_ArgumentNullException()
{
Func<object> CreateNullService = () =>
{
return ((IServiceCollection)null).AddResponsive(options => { });
};
Assert.Throws<AddResponsiveArgumentNullException>(CreateNullService);
}
}
}
| apache-2.0 | C# |
1f935cacf452b3a9f212551082d4a14e4a286972 | Add spotlighted beatmaps filter to beatmap listing | peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu | osu.Game/Overlays/BeatmapListing/SearchGeneral.cs | osu.Game/Overlays/BeatmapListing/SearchGeneral.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.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.BeatmapListing
{
public enum SearchGeneral
{
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralRecommended))]
[Description("Recommended difficulty")]
Recommended,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralConverts))]
[Description("Include converted beatmaps")]
Converts,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFollows))]
[Description("Subscribed mappers")]
Follows,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralSpotlights))]
Spotlights,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFeaturedArtists))]
[Description("Featured artists")]
FeaturedArtists
}
}
| // 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.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.BeatmapListing
{
public enum SearchGeneral
{
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralRecommended))]
[Description("Recommended difficulty")]
Recommended,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralConverts))]
[Description("Include converted beatmaps")]
Converts,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFollows))]
[Description("Subscribed mappers")]
Follows,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.GeneralFeaturedArtists))]
[Description("Featured artists")]
FeaturedArtists
}
}
| mit | C# |
5b83aeace17d9caf4e6119d74271b023f920e38d | update DomainBuilderFactory registration | HatfieldConsultants/Hatfield.EnviroData.WQDataProfile | Source/Hatfield.EnviroData.DataProfile.WQ.Data/DomainBuilderFactory.cs | Source/Hatfield.EnviroData.DataProfile.WQ.Data/DomainBuilderFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hatfield.EnviroData.DataProfile.WQ.Builders;
using Hatfield.EnviroData.DataProfile.WQ.Models;
namespace Hatfield.EnviroData.DataProfile.WQ
{
public class DomainBuilderFactory
{
private DomainBuilderFactory() { }
static readonly Dictionary<Type, Func<IDomainBuilder>> _dict
= new Dictionary<Type, Func<IDomainBuilder>>();
public static IDomainBuilder Create(Type type)
{
Func<IDomainBuilder> constructor = null;
if (_dict.TryGetValue(type, out constructor))
return constructor();
throw new ArgumentException("No type registered for this type");
}
public static void Register(Type type, Func<IDomainBuilder> ctor)
{
_dict.Add(type, ctor);
}
public static void DefaultSetUp()
{
DomainBuilderFactory.Register(typeof(Site), () => new SiteDomainBuilder());
DomainBuilderFactory.Register(typeof(WaterQualityObservation), () => new WaterQualityObservationBuilder());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hatfield.EnviroData.DataProfile.WQ.Builders;
using Hatfield.EnviroData.DataProfile.WQ.Models;
namespace Hatfield.EnviroData.DataProfile.WQ
{
public class DomainBuilderFactory
{
private DomainBuilderFactory() { }
static readonly Dictionary<Type, Func<IDomainBuilder>> _dict
= new Dictionary<Type, Func<IDomainBuilder>>();
public static IDomainBuilder Create(Type type)
{
Func<IDomainBuilder> constructor = null;
if (_dict.TryGetValue(type, out constructor))
return constructor();
throw new ArgumentException("No type registered for this type");
}
public static void Register(Type type, Func<IDomainBuilder> ctor)
{
_dict.Add(type, ctor);
}
public static void DefaultSetUp()
{
DomainBuilderFactory.Register(typeof(Site), () => new SiteDomainBuilder());
}
}
}
| mpl-2.0 | C# |
7bbcf75cf7fb86ee29a0a5a589e374c6ac098d1f | Fix authority URL in the quickstart guide 1 (#4552) | IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4 | samples/Quickstarts/1_ClientCredentials/src/Api/Startup.cs | samples/Quickstarts/1_ClientCredentials/src/Api/Startup.cs | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Api
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5001";
options.RequireHttpsMetadata = false;
options.Audience = "api1";
});
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace Api
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.Audience = "api1";
});
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
} | apache-2.0 | C# |
df174354b1f42eff39caf80c19b0ee9c50064cba | Update ArcDrawNode.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Modules/Renderer/SkiaSharp/Nodes/ArcDrawNode.cs | src/Core2D/Modules/Renderer/SkiaSharp/Nodes/ArcDrawNode.cs | #nullable enable
using Core2D.Model.Renderer;
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Shapes;
using Core2D.ViewModels.Style;
using SkiaSharp;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes;
internal class ArcDrawNode : DrawNode, IArcDrawNode
{
public ArcShapeViewModel Arc { get; set; }
public SKPath? Geometry { get; set; }
public ArcDrawNode(ArcShapeViewModel arc, ShapeStyleViewModel? style)
{
Style = style;
Arc = arc;
UpdateGeometry();
}
public sealed override void UpdateGeometry()
{
ScaleThickness = Arc.State.HasFlag(ShapeStateFlags.Thickness);
ScaleSize = Arc.State.HasFlag(ShapeStateFlags.Size);
Geometry = PathGeometryConverter.ToSKPath(Arc);
if (Geometry is { })
{
Center = new SKPoint(Geometry.Bounds.MidX, Geometry.Bounds.MidY);
}
else
{
Center = SKPoint.Empty;
}
}
public override void OnDraw(object? dc, double zoom)
{
if (dc is not SKCanvas canvas)
{
return;
}
if (Arc.IsFilled)
{
canvas.DrawPath(Geometry, Fill);
}
if (Arc.IsStroked)
{
canvas.DrawPath(Geometry, Stroke);
}
}
}
| #nullable enable
using Core2D.Model.Renderer;
using Core2D.Model.Renderer.Nodes;
using Core2D.ViewModels.Shapes;
using Core2D.ViewModels.Style;
using SkiaSharp;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes;
internal class ArcDrawNode : DrawNode, IArcDrawNode
{
public ArcShapeViewModel Arc { get; set; }
public SKPath? Geometry { get; set; }
public ArcDrawNode(ArcShapeViewModel arc, ShapeStyleViewModel style)
{
Style = style;
Arc = arc;
UpdateGeometry();
}
public sealed override void UpdateGeometry()
{
ScaleThickness = Arc.State.HasFlag(ShapeStateFlags.Thickness);
ScaleSize = Arc.State.HasFlag(ShapeStateFlags.Size);
Geometry = PathGeometryConverter.ToSKPath(Arc);
if (Geometry is { })
{
Center = new SKPoint(Geometry.Bounds.MidX, Geometry.Bounds.MidY);
}
else
{
Center = SKPoint.Empty;
}
}
public override void OnDraw(object? dc, double zoom)
{
if (dc is not SKCanvas canvas)
{
return;
}
if (Arc.IsFilled)
{
canvas.DrawPath(Geometry, Fill);
}
if (Arc.IsStroked)
{
canvas.DrawPath(Geometry, Stroke);
}
}
}
| mit | C# |
11f481147d6f4f75bb2fe7591871e42493ec680c | update AssemblyInfo.cs | ost-onion/SolutionParser | src/Onion.SolutionParser.Parser/Properties/AssemblyInfo.cs | src/Onion.SolutionParser.Parser/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("Onion.SolutionParser.Parser")]
[assembly: AssemblyDescription("An elegant parser for Visual Studio solution files")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Open Systems Technologies")]
[assembly: AssemblyProduct("Onion.SolutionParser.Parser")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("14e07209-277c-4a9e-952a-0efc8d0d54fa")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("Onion.SolutionParser.Parser")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Onion.SolutionParser.Parser")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("14e07209-277c-4a9e-952a-0efc8d0d54fa")]
// 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")]
| mit | C# |
b89ce8b7262c600345d6fbe6f05f7116159220ae | Update SecureSocketOptions.cs | serilog/serilog-sinks-email | src/Serilog.Sinks.Email/Sinks/Email/SecureSocketOptions.cs | src/Serilog.Sinks.Email/Sinks/Email/SecureSocketOptions.cs | //
// SecureSocketOptions.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2021 .NET Foundation and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if MAIL_KIT
namespace Serilog.Sinks.Email
{
/// <summary>Secure socket options.</summary>
/// <remarks>
/// Provides a way of specifying the SSL and/or TLS encryption that
/// should be used for a connection.
/// </remarks>
public enum SecureSocketOptions
{
/// <summary>
/// No SSL or TLS encryption should be used.
/// </summary>
None = 0,
/// <summary>
/// Allow the implementation to decide which SSL or TLS options to use (default).
/// If the server does not support SSL or TLS, then the connection will continue
/// without any encryption.
/// </summary>
Auto = 1,
/// <summary>
/// The connection should use SSL or TLS encryption immediately.
/// </summary>
SslOnConnect = 2,
/// <summary>
/// Elevates the connection to use TLS encryption immediately after reading the greeting
/// and capabilities of the server.
/// </summary>
StartTls = 3,
/// <summary>
/// Elevates the connection to use TLS encryption immediately after reading the greeting
/// and capabilities of the server, but only if the server supports the STARTTLS
/// extension.
/// </summary>
StartTlsWhenAvailable = 4
}
}
#endif
| #if MAIL_KIT
namespace Serilog.Sinks.Email
{
/// <summary>Secure socket options.</summary>
/// <remarks>
/// Provides a way of specifying the SSL and/or TLS encryption that
/// should be used for a connection.
/// </remarks>
public enum SecureSocketOptions
{
/// <summary>
/// No SSL or TLS encryption should be used.
/// </summary>
None = 0,
/// <summary>
/// Allow the MailKit.IMailService to decide which SSL or TLS options to use (default).
/// If the server does not support SSL or TLS, then the connection will continue
/// without any encryption.
/// </summary>
Auto = 1,
/// <summary>
/// The connection should use SSL or TLS encryption immediately.
/// </summary>
SslOnConnect = 2,
/// <summary>
/// Elevates the connection to use TLS encryption immediately after reading the greeting
/// and capabilities of the server. If the server does not support the STARTTLS extension,
/// then the connection will fail and a System.NotSupportedException will be thrown.
/// </summary>
StartTls = 3,
/// <summary>
/// Elevates the connection to use TLS encryption immediately after reading the greeting
/// and capabilities of the server, but only if the server supports the STARTTLS
/// extension.
/// </summary>
StartTlsWhenAvailable = 4
}
}
#endif
| apache-2.0 | C# |
eab692e414b35c55607b9c674457cfe97f6b4127 | Revert "Added xaml modification" | blstream/AugmentedSzczecin_WP,blstream/AugmentedSzczecin_WP,blstream/AugmentedSzczecin_WP | AugmentedSzczecin/AugmentedSzczecin/Services/DataService.cs | AugmentedSzczecin/AugmentedSzczecin/Services/DataService.cs | using AugmentedSzczecin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Runtime.Serialization.Json;
using System.IO;
namespace AugmentedSzczecin.Services
{
public class DataService
{
private static string _page = "https://patronatwp.azure-mobile.net/tables/Place";
public async Task<ObservableCollection<Place>> RunAsync()
{
ObservableCollection<Place> model = null;
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(_page);
response.EnsureSuccessStatusCode();
string jsonString = await response.Content.ReadAsStringAsync();
//ALTERNATIVE SOLUTION
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObservableCollection<Place>));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
model = (ObservableCollection<Place>)ser.ReadObject(stream);
//ORIGINAL SOLUTION - nulls
//model = JsonConvert.DeserializeObject<ObservableCollection<Place>>(jsonString);
//string x = "[{ \"id\": \"112C8C46-C35B-4A41-A213-C627CFF9351F\", \"Name\": \"WI ZUT\", \"Address\": \"ul. Żołnierska 49\", \"Latitude\": 47.6785619, \"Longitude\": -122.1311156, \"HasWifi\": true }, { \"id\": \"112C8C46-C35B-4A41-A213-C627CFF9351F\", \"Name\": \"WI ZUT\", \"Address\": \"ul. Żołnierska 49\", \"Latitude\": 47.6785619, \"Longitude\": -122.1311156, \"HasWifi\": true }]";
//model = JsonConvert.DeserializeObject<ObservableCollection<Place>>(x);
return model;
}
}
}
| using AugmentedSzczecin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Json;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Runtime.Serialization.Json;
using System.IO;
namespace AugmentedSzczecin.Services
{
public class DataService
{
private static string _page = "https://patronatwp.azure-mobile.net/tables/Place";
public async Task<ObservableCollection<Place>> RunAsync()
{
ObservableCollection<Place> model = new ObservableCollection<Place>();
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(_page);
response.EnsureSuccessStatusCode();
string jsonString = await response.Content.ReadAsStringAsync();
//ALTERNATIVE SOLUTION
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ObservableCollection<Place>));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
model = (ObservableCollection<Place>)ser.ReadObject(stream);
//ORIGINAL SOLUTION - nulls
//model = JsonConvert.DeserializeObject<ObservableCollection<Place>>(jsonString);
//string x = "[{ \"id\": \"112C8C46-C35B-4A41-A213-C627CFF9351F\", \"Name\": \"WI ZUT\", \"Address\": \"ul. Żołnierska 49\", \"Latitude\": 47.6785619, \"Longitude\": -122.1311156, \"HasWifi\": true }, { \"id\": \"112C8C46-C35B-4A41-A213-C627CFF9351F\", \"Name\": \"WI ZUT\", \"Address\": \"ul. Żołnierska 49\", \"Latitude\": 47.6785619, \"Longitude\": -122.1311156, \"HasWifi\": true }]";
//model = JsonConvert.DeserializeObject<ObservableCollection<Place>>(x);
return model;
}
}
}
| apache-2.0 | C# |
4e041112b401e56d14220fa4df9fa94ea8b11c7e | Update LayerDragAndDropListBox.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D | Core2D.Wpf/Controls/Custom/Lists/LayerDragAndDropListBox.cs | Core2D.Wpf/Controls/Custom/Lists/LayerDragAndDropListBox.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Windows.Controls;
namespace Core2D.Wpf.Controls.Custom.Lists
{
/// <summary>
/// The <see cref="ListBox"/> control for <see cref="Layer"/> items with drag and drop support.
/// </summary>
public class LayerDragAndDropListBox : DragAndDropListBox<Layer>
{
/// <summary>
/// Initializes a new instance of the <see cref="LayerDragAndDropListBox"/> class.
/// </summary>
public LayerDragAndDropListBox()
: base()
{
this.Initialized += (s, e) => base.Initialize();
}
/// <summary>
/// Updates DataContext binding to ImmutableArray collection property.
/// </summary>
/// <param name="array">The updated immutable array.</param>
public override void UpdateDataContext(ImmutableArray<Layer> array)
{
var editor = (Core2D.Editor)this.Tag;
var container = editor.Project.CurrentContainer;
var previous = container.Layers;
var next = array;
editor.Project?.History?.Snapshot(previous, next, (p) => container.Layers = p);
container.Layers = next;
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Immutable;
using System.Windows.Controls;
namespace Core2D.Wpf.Controls.Custom.Lists
{
/// <summary>
/// The <see cref="ListBox"/> control for <see cref="Layer"/> items with drag and drop support.
/// </summary>
public class LayerDragAndDropListBox : DragAndDropListBox<Layer>
{
/// <summary>
/// Initializes a new instance of the <see cref="LayerDragAndDropListBox"/> class.
/// </summary>
public LayerDragAndDropListBox()
: base()
{
this.Initialized += (s, e) => base.Initialize();
}
/// <summary>
/// Updates DataContext binding to ImmutableArray collection property.
/// </summary>
/// <param name="array">The updated immutable array.</param>
public override void UpdateDataContext(ImmutableArray<Layer> array)
{
var editor = (Core2D.Editor)this.Tag;
var container = editor.Project.CurrentContainer;
var previous = container.Layers;
var next = array;
editor.project?.History?.Snapshot(previous, next, (p) => container.Layers = p);
container.Layers = next;
}
}
}
| mit | C# |
272a11962b1a9826ac172645e5833302ea36ca73 | Add TODO instead of exception for HairRenderer | ethanmoffat/EndlessClient | EndlessClient/Rendering/CharacterProperties/HairRenderer.cs | EndlessClient/Rendering/CharacterProperties/HairRenderer.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 EOLib.Data.BLL;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace EndlessClient.Rendering.CharacterProperties
{
public class HairRenderer : ICharacterPropertyRenderer
{
private readonly SpriteBatch _spriteBatch;
private readonly ICharacterRenderProperties _renderProperties;
private readonly Texture2D _hairTexture;
public HairRenderer(SpriteBatch spriteBatch, ICharacterRenderProperties renderProperties, Texture2D hairTexture)
{
_spriteBatch = spriteBatch;
_renderProperties = renderProperties;
_hairTexture = hairTexture;
}
public void Render(Rectangle parentCharacterDrawArea)
{
//todo:!!!!!!!! how did i forget to implement this?
//throw new System.NotImplementedException();
}
}
}
| // 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 EOLib.Data.BLL;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace EndlessClient.Rendering.CharacterProperties
{
public class HairRenderer : ICharacterPropertyRenderer
{
private readonly SpriteBatch _spriteBatch;
private readonly ICharacterRenderProperties _renderProperties;
private readonly Texture2D _hairTexture;
public HairRenderer(SpriteBatch spriteBatch, ICharacterRenderProperties renderProperties, Texture2D hairTexture)
{
_spriteBatch = spriteBatch;
_renderProperties = renderProperties;
_hairTexture = hairTexture;
}
public void Render(Rectangle parentCharacterDrawArea)
{
throw new System.NotImplementedException();
}
}
}
| mit | C# |
7e3d471d3d2b7d3d614a8c338767309c4f569eb8 | Fix compiler test fixture setup | tgjones/mincamlsharp | src/MinCamlSharp.Tests/CompilerTests.cs | src/MinCamlSharp.Tests/CompilerTests.cs | using System.Diagnostics;
using System.IO;
using NUnit.Framework;
namespace MinCamlSharp.Tests
{
[TestFixture]
public class CompilerTests
{
[TestFixtureSetUp]
public void PrepareBinariesDirectory()
{
if (Directory.Exists("Binaries"))
Directory.Delete("Binaries", true);
Directory.CreateDirectory("Binaries");
}
private static string[] SourceFiles
{
get { return Directory.GetFiles("Assets", "*.ml"); }
}
[TestCaseSource("SourceFiles")]
public void CanCompileApplication(string sourceFile)
{
// Arrange / Act.
var outputFileName = Compile(sourceFile);
// Assert.
Assert.That(File.Exists(outputFileName), Is.True);
}
[TestCaseSource("SourceFiles")]
[Ignore("Not ready for this yet")]
public void CanRunApplication(string sourceFile)
{
// Arrange.
var outputFilePath = Compile(sourceFile);
string referenceFileName = Path.ChangeExtension(sourceFile, ".ref");
if (File.Exists(referenceFileName))
Assert.Fail("Could not complete test: no reference file provided.");
var referenceFileContents = File.ReadAllText(referenceFileName);
// Act.
string actualOutput = null;
var process = new Process
{
StartInfo =
{
FileName = outputFilePath,
UseShellExecute = false,
RedirectStandardOutput = true
}
};
process.OutputDataReceived += (sender, args) => actualOutput = args.Data;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
// Assert.
Assert.That(actualOutput, Is.EqualTo(referenceFileContents));
}
private string Compile(string sourceFile)
{
// Arrange.
var compiler = new Compiler();
string outputFilePath = Path.Combine("Binaries", Path.GetFileNameWithoutExtension(sourceFile) + ".exe");
var options = new CompilerOptions
{
SourceFile = sourceFile,
OutputAssemblyName = "Test",
OutputFilePath = outputFilePath
};
// Act.
var result = compiler.Compile(options);
// Assert.
Assert.That(result, Is.True);
return outputFilePath;
}
}
} | using System.Diagnostics;
using System.IO;
using NUnit.Framework;
namespace MinCamlSharp.Tests
{
[TestFixture]
public class CompilerTests
{
[TestFixtureSetUp]
public void PrepareBinariesDirectory()
{
if (Directory.Exists("Binaries"))
Directory.Delete("Binaries");
Directory.CreateDirectory("Binaries");
}
private static string[] SourceFiles
{
get { return Directory.GetFiles("Assets", "*.ml"); }
}
[TestCaseSource("SourceFiles")]
public void CanCompileApplication(string sourceFile)
{
// Arrange / Act.
var outputFileName = Compile(sourceFile);
// Assert.
Assert.That(File.Exists(outputFileName), Is.True);
}
[TestCaseSource("SourceFiles")]
[Ignore("Not ready for this yet")]
public void CanRunApplication(string sourceFile)
{
// Arrange.
var outputFilePath = Compile(sourceFile);
string referenceFileName = Path.ChangeExtension(sourceFile, ".ref");
if (File.Exists(referenceFileName))
Assert.Fail("Could not complete test: no reference file provided.");
var referenceFileContents = File.ReadAllText(referenceFileName);
// Act.
string actualOutput = null;
var process = new Process
{
StartInfo =
{
FileName = outputFilePath,
UseShellExecute = false,
RedirectStandardOutput = true
}
};
process.OutputDataReceived += (sender, args) => actualOutput = args.Data;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
// Assert.
Assert.That(actualOutput, Is.EqualTo(referenceFileContents));
}
private string Compile(string sourceFile)
{
// Arrange.
var compiler = new Compiler();
string outputFilePath = Path.Combine("Binaries", Path.GetFileNameWithoutExtension(sourceFile) + ".exe");
var options = new CompilerOptions
{
SourceFile = sourceFile,
OutputAssemblyName = "Test",
OutputFilePath = outputFilePath
};
// Act.
var result = compiler.Compile(options);
// Assert.
Assert.That(result, Is.True);
return outputFilePath;
}
}
} | bsd-3-clause | C# |
003add6a7b4baad7205a1bfadfe0ecf2d1f54ade | Remove extra empty line. | ErikSchierboom/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,sharwell/roslyn,wvdd007/roslyn,heejaechang/roslyn,aelij/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,brettfo/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,aelij/roslyn,dotnet/roslyn,tmat/roslyn,gafter/roslyn,genlu/roslyn,genlu/roslyn,mavasani/roslyn,AmadeusW/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,davkean/roslyn,stephentoub/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,jmarolf/roslyn,sharwell/roslyn,gafter/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,eriawan/roslyn,aelij/roslyn,genlu/roslyn,tmat/roslyn,tannergooding/roslyn,stephentoub/roslyn,bartdesmet/roslyn,physhi/roslyn,jasonmalinowski/roslyn,physhi/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,davkean/roslyn,gafter/roslyn,eriawan/roslyn,tannergooding/roslyn,jmarolf/roslyn,bartdesmet/roslyn,mavasani/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,davkean/roslyn,brettfo/roslyn,dotnet/roslyn,dotnet/roslyn,stephentoub/roslyn,wvdd007/roslyn,heejaechang/roslyn,tmat/roslyn,diryboy/roslyn,diryboy/roslyn,jmarolf/roslyn,diryboy/roslyn | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.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.
#nullable enable
using System;
using System.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
internal interface IPersistentStorageLocationService : IWorkspaceService
{
bool IsSupported(Workspace workspace);
string? TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultPersistentStorageLocationService()
{
}
public virtual bool IsSupported(Workspace workspace) => false;
protected virtual string GetCacheDirectory()
{
// Store in the LocalApplicationData/Roslyn/hash folder (%appdatalocal%/... on Windows,
// ~/.local/share/... on unix). This will place the folder in a location we can trust
// to be able to get back to consistently as long as we're working with the same
// solution and the same workspace kind.
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
return Path.Combine(appDataFolder, "Microsoft", "VisualStudio", "Roslyn", "Cache");
}
public string? TryGetStorageLocation(Solution solution)
{
if (!IsSupported(solution.Workspace))
return null;
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
var cacheDirectory = GetCacheDirectory();
var kind = StripInvalidPathChars(solution.Workspace.Kind ?? "");
var hash = StripInvalidPathChars(Checksum.Create(solution.FilePath).ToString());
return Path.Combine(cacheDirectory, kind, hash);
static string StripInvalidPathChars(string val)
{
var invalidPathChars = Path.GetInvalidPathChars();
val = new string(val.Where(c => !invalidPathChars.Contains(c)).ToArray());
return string.IsNullOrWhiteSpace(val) ? "None" : val;
}
}
}
}
| // 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.
#nullable enable
using System;
using System.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
internal interface IPersistentStorageLocationService : IWorkspaceService
{
bool IsSupported(Workspace workspace);
string? TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultPersistentStorageLocationService()
{
}
public virtual bool IsSupported(Workspace workspace) => false;
protected virtual string GetCacheDirectory()
{
// Store in the LocalApplicationData/Roslyn/hash folder (%appdatalocal%/... on Windows,
// ~/.local/share/... on unix). This will place the folder in a location we can trust
// to be able to get back to consistently as long as we're working with the same
// solution and the same workspace kind.
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
return Path.Combine(appDataFolder, "Microsoft", "VisualStudio", "Roslyn", "Cache");
}
public string? TryGetStorageLocation(Solution solution)
{
if (!IsSupported(solution.Workspace))
return null;
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
var cacheDirectory = GetCacheDirectory();
var kind = StripInvalidPathChars(solution.Workspace.Kind ?? "");
var hash = StripInvalidPathChars(Checksum.Create(solution.FilePath).ToString());
return Path.Combine(cacheDirectory, kind, hash);
static string StripInvalidPathChars(string val)
{
var invalidPathChars = Path.GetInvalidPathChars();
val = new string(val.Where(c => !invalidPathChars.Contains(c)).ToArray());
return string.IsNullOrWhiteSpace(val) ? "None" : val;
}
}
}
}
| mit | C# |
aa8dd5947ab17d5fe9505c69fb7b245fcd7d94d7 | Call the correct implementation if IMessageHandler.ProcessMessage method | Shuttle/Shuttle.Esb,Shuttle/shuttle-esb-core | Shuttle.Esb/MessageHandling/DefaultMessageHandlerInvoker.cs | Shuttle.Esb/MessageHandling/DefaultMessageHandlerInvoker.cs | using System;
using System.Linq;
using Shuttle.Core.Infrastructure;
namespace Shuttle.Esb
{
public class DefaultMessageHandlerInvoker : IMessageHandlerInvoker
{
public MessageHandlerInvokeResult Invoke(IPipelineEvent pipelineEvent)
{
Guard.AgainstNull(pipelineEvent, "pipelineEvent");
var state = pipelineEvent.Pipeline.State;
var bus = state.GetServiceBus();
var message = state.GetMessage();
var handler = bus.Configuration.MessageHandlerFactory.GetHandler(message);
if (handler == null)
{
return MessageHandlerInvokeResult.InvokeFailure();
}
try
{
var transportMessage = state.GetTransportMessage();
var messageType = message.GetType();
var interfaceType = typeof(IMessageHandler<>).MakeGenericType(messageType);
var method = handler.GetType().GetInterfaceMap(interfaceType).TargetMethods.SingleOrDefault();
if (method == null)
{
throw new ProcessMessageMethodMissingException(string.Format(
EsbResources.ProcessMessageMethodMissingException,
handler.GetType().FullName,
messageType.FullName));
}
var contextType = typeof(HandlerContext<>).MakeGenericType(messageType);
var handlerContext = Activator.CreateInstance(contextType, bus, transportMessage, message, state.GetActiveState());
method.Invoke(handler, new[] {handlerContext});
}
finally
{
bus.Configuration.MessageHandlerFactory.ReleaseHandler(handler);
}
return MessageHandlerInvokeResult.InvokedHandler(handler);
}
}
} | using System;
using Shuttle.Core.Infrastructure;
namespace Shuttle.Esb
{
public class DefaultMessageHandlerInvoker : IMessageHandlerInvoker
{
public MessageHandlerInvokeResult Invoke(IPipelineEvent pipelineEvent)
{
Guard.AgainstNull(pipelineEvent, "pipelineEvent");
var state = pipelineEvent.Pipeline.State;
var bus = state.GetServiceBus();
var message = state.GetMessage();
var handler = bus.Configuration.MessageHandlerFactory.GetHandler(message);
if (handler == null)
{
return MessageHandlerInvokeResult.InvokeFailure();
}
try
{
var transportMessage = state.GetTransportMessage();
var messageType = message.GetType();
var contextType = typeof (HandlerContext<>).MakeGenericType(messageType);
var method = handler.GetType().GetMethod("ProcessMessage", new[] {contextType});
if (method == null)
{
throw new ProcessMessageMethodMissingException(string.Format(
EsbResources.ProcessMessageMethodMissingException,
handler.GetType().FullName,
messageType.FullName));
}
var handlerContext = Activator.CreateInstance(contextType, bus, transportMessage, message, state.GetActiveState());
method.Invoke(handler, new[] {handlerContext});
}
finally
{
bus.Configuration.MessageHandlerFactory.ReleaseHandler(handler);
}
return MessageHandlerInvokeResult.InvokedHandler(handler);
}
}
} | bsd-3-clause | C# |
238dd85a2bff24c4947aeba524c2da09d4e1e2fa | repair stream dispose defect | riganti/dotvvm,riganti/dotvvm,kiraacorsac/dotvvm,darilek/dotvvm,riganti/dotvvm,darilek/dotvvm,kiraacorsac/dotvvm,kiraacorsac/dotvvm,darilek/dotvvm,riganti/dotvvm | src/DotVVM.Framework.Hosting.AspNetCore/Hosting/DotvvmHttpResponse.cs | src/DotVVM.Framework.Hosting.AspNetCore/Hosting/DotvvmHttpResponse.cs | using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
namespace DotVVM.Framework.Hosting
{
public class DotvvmHttpResponse : IHttpResponse
{
public HttpResponse OriginalResponse { get; }
public IHttpContext Context { get; }
public DotvvmHttpResponse(HttpResponse originalResponse, IHttpContext context, IHeaderCollection headers)
{
Context = context;
OriginalResponse = originalResponse;
Headers = headers;
}
public IHeaderCollection Headers { get; set; }
public int StatusCode
{
get { return OriginalResponse.StatusCode; }
set { OriginalResponse.StatusCode = value; }
}
public string ContentType
{
get { return OriginalResponse.ContentType; }
set { OriginalResponse.ContentType = value; }
}
public Stream Body
{
get { return OriginalResponse.Body; }
set { OriginalResponse.Body = value; }
}
public void Write(string text)
{
var writer = new StreamWriter(OriginalResponse.Body) { AutoFlush = true};
writer.Write(text);
}
public void Write(byte[] data)
{
OriginalResponse.Body.Write(data, 0, data.Length);
}
public void Write(byte[] data, int offset, int count)
{
OriginalResponse.Body.Write(data, offset, count);
}
public Task WriteAsync(string text)
{
return OriginalResponse.WriteAsync(text);
}
public Task WriteAsync(string text, CancellationToken token)
{
return OriginalResponse.WriteAsync(text, token);
}
}
} | using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
namespace DotVVM.Framework.Hosting
{
public class DotvvmHttpResponse : IHttpResponse
{
public HttpResponse OriginalResponse { get; }
public IHttpContext Context { get; }
public DotvvmHttpResponse(HttpResponse originalResponse, IHttpContext context, IHeaderCollection headers)
{
Context = context;
OriginalResponse = originalResponse;
Headers = headers;
}
public IHeaderCollection Headers { get; set; }
public int StatusCode
{
get { return OriginalResponse.StatusCode; }
set { OriginalResponse.StatusCode = value; }
}
public string ContentType
{
get { return OriginalResponse.ContentType; }
set { OriginalResponse.ContentType = value; }
}
public Stream Body
{
get { return OriginalResponse.Body; }
set { OriginalResponse.Body = value; }
}
public void Write(string text)
{
using (var writer = new StreamWriter(OriginalResponse.Body))
{
writer.Write(text);
}
}
public void Write(byte[] data)
{
OriginalResponse.Body.Write(data, 0, data.Length);
}
public void Write(byte[] data, int offset, int count)
{
OriginalResponse.Body.Write(data, offset, count);
}
public Task WriteAsync(string text)
{
return OriginalResponse.WriteAsync(text);
}
public Task WriteAsync(string text, CancellationToken token)
{
return OriginalResponse.WriteAsync(text, token);
}
}
} | apache-2.0 | C# |
fc08118a59c0ca382462a9dc52c13e27bdbb440c | Update LoggerConfigurationXamarinExtensions.cs (#18) | serilog/serilog-sinks-xamarin | src/Serilog.Sinks.Xamarin.iOS/LoggerConfigurationXamarinExtensions.cs | src/Serilog.Sinks.Xamarin.iOS/LoggerConfigurationXamarinExtensions.cs | // Copyright 2016 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Serilog.Configuration;
using Serilog.Events;
using Serilog.Formatting.Display;
using Serilog.Sinks.Xamarin;
namespace Serilog
{
/// <summary>
/// Adds WriteTo.NSLog() to the logger configuration.
/// </summary>
public static class LoggerConfigurationXamarinExtensions
{
const string DefaultNSLogOutputTemplate = "[{Level}] {Message:l}{NewLine:l}{Exception:l}";
/// <summary>
/// Adds a sink that writes log events to Apple Unified Logging.
/// </summary>
/// <param name="sinkConfiguration">The configuration being modified.</param>
/// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
/// <param name="outputTemplate">Template for the output events</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <exception cref="ArgumentNullException">A required parameter is null.</exception>
public static LoggerConfiguration NSLog(this LoggerSinkConfiguration sinkConfiguration,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultNSLogOutputTemplate,
IFormatProvider formatProvider = null) {
if (sinkConfiguration == null)
throw new ArgumentNullException ("sinkConfiguration");
if (outputTemplate == null)
throw new ArgumentNullException ("outputTemplate");
var formatter = new MessageTemplateTextFormatter (outputTemplate, formatProvider);
return sinkConfiguration.Sink (new NSLogSink (formatter), restrictedToMinimumLevel);
}
}
}
| // Copyright 2016 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Serilog.Configuration;
using Serilog.Events;
using Serilog.Formatting.Display;
using Serilog.Sinks.Xamarin;
namespace Serilog
{
/// <summary>
/// Adds WriteTo.NSLog() to the logger configuration.
/// </summary>
public static class LoggerConfigurationXamarinExtensions
{
const string DefaultNSLogOutputTemplate = "[{Level}] {Message:l}{NewLine:l}{Exception:l}";
/// <summary>
/// Adds a sink that writes log events to a Azure DocumentDB table in the provided endpoint.
/// </summary>
/// <param name="sinkConfiguration">The configuration being modified.</param>
/// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
/// <param name="outputTemplate">Template for the output events</param>
/// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
/// <exception cref="ArgumentNullException">A required parameter is null.</exception>
public static LoggerConfiguration NSLog(this LoggerSinkConfiguration sinkConfiguration,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultNSLogOutputTemplate,
IFormatProvider formatProvider = null) {
if (sinkConfiguration == null)
throw new ArgumentNullException ("sinkConfiguration");
if (outputTemplate == null)
throw new ArgumentNullException ("outputTemplate");
var formatter = new MessageTemplateTextFormatter (outputTemplate, formatProvider);
return sinkConfiguration.Sink (new NSLogSink (formatter), restrictedToMinimumLevel);
}
}
}
| apache-2.0 | C# |
bca183fead2f931a713173c36985a537d3108fd4 | Fix bug #1222: Repair MyClaimTagHelper | leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net | src/JoinRpg.Portal/TagHelpers/MyClaimTagHelper.cs | src/JoinRpg.Portal/TagHelpers/MyClaimTagHelper.cs | using JoinRpg.Web.Models;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace JoinRpg.Portal.TagHelpers
{
[HtmlTargetElement("my-claim-link")]
public class MyClaimTagHelper : AnchorTagHelper
{
[HtmlAttributeName("asp-for")]
public IProjectIdAware For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
Controller = "Claim";
Action = "MyClaim";
RouteValues.Add("ProjectId", For.ProjectId.ToString());
base.Process(context, output);
output.TagName = "a";
}
public MyClaimTagHelper(IHtmlGenerator generator) : base(generator)
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JoinRpg.Web.Models;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.Runtime.TagHelpers;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace JoinRpg.Portal.TagHelpers
{
// You may need to install the Microsoft.AspNetCore.Razor.Runtime package into your project
[HtmlTargetElement("my-claim-link")]
public class MyClaimTagHelper : AnchorTagHelper
{
[HtmlAttributeName("asp-for")]
public IProjectIdAware For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes.Remove(output.Attributes.Single(a => a.Name == "asp-for"));
Controller = "Claim";
Action = "MyClaim";
RouteValues.Add("ProjectId", For.ProjectId.ToString());
base.Process(context, output);
}
public MyClaimTagHelper(IHtmlGenerator generator) : base(generator)
{
}
}
}
| mit | C# |
052ec905dfd503440389303950151e55fad64175 | Fix YukariCake grab transition | NitorInc/NitoriWare,NitorInc/NitoriWare,uulltt/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,plrusek/NitoriWare | Assets/Resources/Microgames/YukariCake/Scripts/YukariCakeController.cs | Assets/Resources/Microgames/YukariCake/Scripts/YukariCakeController.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YukariCakeController : MonoBehaviour {
// Properties
public YukariCakeReimu Enemy;
public List<AudioSource> AudioSources;
public Animator YukariAnimator;
public AudioSource YukariSource;
public AudioClip YukariSoundSnatch, YukariCakeDimension, YukariSoundVictory, YukariSoundFail;
public GameObject YukariFailSprites;
// Game Variables
public bool IsVulnerable = false;
// Use this for initialization
void Start () {
foreach (var a in AudioSources)
a.pitch = Time.timeScale;
}
// Update is called once per frame
void Update () {
if(YukariAnimator.GetCurrentAnimatorStateInfo(0).IsName("YukariCakeYukariSnatch"))
{
if (Enemy.IsAlert && IsVulnerable)
SetGameFailure();
}
if(!MicrogameController.instance.getVictoryDetermined())
{
if(Input.GetKeyDown(KeyCode.Space))
{
// Here comes the snatch sequence. Better not get caught.
YukariAnimator.SetBool("snatch", true);
//YukariAnimator.Play("YukariCakeYukariSnatch");
}
}
}
public void SetGameVictory()
{
PlayVictoryAnimation();
MicrogameController.instance.setVictory(true, true);
Enemy.Stop();
}
public void SetGameFailure()
{
PlayFailureAnimation();
MicrogameController.instance.setVictory(false, true);
Enemy.Stop();
}
public void PlayVictoryAnimation()
{
YukariAnimator.Play("YukariCakeYukariVictory");
}
public void PlayFailureAnimation()
{
PlayFailureSound();
YukariAnimator.enabled = false;
YukariFailSprites.SetActive(true);
Enemy.PlayFailureAnimation();
}
public void PlayDimensionSound()
{
YukariSource.PlayOneShot(YukariCakeDimension);
}
public void PlaySnatchSound()
{
YukariSource.PlayOneShot(YukariSoundSnatch);
}
public void PlayVictorySound()
{
YukariSource.PlayOneShot(YukariSoundVictory);
//Debug.Log("Woo!");
}
public void PlayFailureSound()
{
YukariSource.PlayOneShot(YukariSoundFail);
//Debug.Log(":(");
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YukariCakeController : MonoBehaviour {
// Properties
public YukariCakeReimu Enemy;
public List<AudioSource> AudioSources;
public Animator YukariAnimator;
public AudioSource YukariSource;
public AudioClip YukariSoundSnatch, YukariCakeDimension, YukariSoundVictory, YukariSoundFail;
public GameObject YukariFailSprites;
// Game Variables
public bool IsVulnerable = false;
// Use this for initialization
void Start () {
foreach (var a in AudioSources)
a.pitch = Time.timeScale;
}
// Update is called once per frame
void Update () {
if(YukariAnimator.GetCurrentAnimatorStateInfo(0).IsName("YukariCakeYukariSnatch"))
{
if (Enemy.IsAlert && IsVulnerable)
SetGameFailure();
}
if(!MicrogameController.instance.getVictoryDetermined())
{
if(Input.GetKeyDown(KeyCode.Space))
{
// Here comes the snatch sequence. Better not get caught.
YukariAnimator.SetBool("Snatch", true);
YukariAnimator.Play("YukariCakeYukariSnatch");
}
}
}
public void SetGameVictory()
{
PlayVictoryAnimation();
MicrogameController.instance.setVictory(true, true);
Enemy.Stop();
}
public void SetGameFailure()
{
PlayFailureAnimation();
MicrogameController.instance.setVictory(false, true);
Enemy.Stop();
}
public void PlayVictoryAnimation()
{
YukariAnimator.Play("YukariCakeYukariVictory");
}
public void PlayFailureAnimation()
{
PlayFailureSound();
YukariAnimator.enabled = false;
YukariFailSprites.SetActive(true);
Enemy.PlayFailureAnimation();
}
public void PlayDimensionSound()
{
YukariSource.PlayOneShot(YukariCakeDimension);
}
public void PlaySnatchSound()
{
YukariSource.PlayOneShot(YukariSoundSnatch);
}
public void PlayVictorySound()
{
YukariSource.PlayOneShot(YukariSoundVictory);
//Debug.Log("Woo!");
}
public void PlayFailureSound()
{
YukariSource.PlayOneShot(YukariSoundFail);
//Debug.Log(":(");
}
}
| mit | C# |
883617e961975687b2ba5508424fb92817beda4e | Use a section for ElasticSearch. | ExRam/ExRam.Gremlinq | src/ExRam.Gremlinq.Providers.Neptune.AspNet/GremlinqSetupExtensions.cs | src/ExRam.Gremlinq.Providers.Neptune.AspNet/GremlinqSetupExtensions.cs | using System;
using ExRam.Gremlinq.Providers.Neptune;
using Microsoft.Extensions.Configuration;
namespace ExRam.Gremlinq.Core.AspNet
{
public static class GremlinqSetupExtensions
{
public static GremlinqSetup UseNeptune(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
{
return setup
.UseProvider(
"Neptune",
(e, f) => e.UseNeptune(f),
(configurator, configuration) =>
{
if (configuration.GetSection("ElasticSearch") is { } elasticSearchSection)
{
if (bool.TryParse(elasticSearchSection["Enabled"], out var isEnabled) && isEnabled && configuration["EndPoint"] is { } endPoint)
{
var indexConfiguration = Enum.TryParse<NeptuneElasticSearchIndexConfiguration>(configuration["IndexConfiguration"], true, out var outVar)
? outVar
: NeptuneElasticSearchIndexConfiguration.Standard;
configurator = configurator
.UseElasticSearch(new Uri(endPoint), indexConfiguration);
}
}
return configurator;
},
extraConfiguration);
}
public static GremlinqSetup UseNeptune<TVertex, TEdge>(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
{
return setup
.UseNeptune(extraConfiguration)
.ConfigureEnvironment(env => env
.UseModel(GraphModel
.FromBaseTypes<TVertex, TEdge>(lookup => lookup
.IncludeAssembliesOfBaseTypes())));
}
}
}
| using System;
using ExRam.Gremlinq.Providers.Neptune;
using Microsoft.Extensions.Configuration;
namespace ExRam.Gremlinq.Core.AspNet
{
public static class GremlinqSetupExtensions
{
public static GremlinqSetup UseNeptune(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
{
return setup
.UseProvider(
"Neptune",
(e, f) => e.UseNeptune(f),
(configurator, configuration) =>
{
if (configuration["ElasticSearchEndPoint"] is { } endPoint)
{
var indexConfiguration = Enum.TryParse<NeptuneElasticSearchIndexConfiguration>(configuration["IndexConfiguration"], true, out var outVar)
? outVar
: NeptuneElasticSearchIndexConfiguration.Standard;
configurator = configurator
.UseElasticSearch(new Uri(endPoint), indexConfiguration);
}
return configurator;
},
extraConfiguration);
}
public static GremlinqSetup UseNeptune<TVertex, TEdge>(this GremlinqSetup setup, Func<INeptuneConfigurator, IConfiguration, INeptuneConfigurator>? extraConfiguration = null)
{
return setup
.UseNeptune(extraConfiguration)
.ConfigureEnvironment(env => env
.UseModel(GraphModel
.FromBaseTypes<TVertex, TEdge>(lookup => lookup
.IncludeAssembliesOfBaseTypes())));
}
}
}
| mit | C# |
9cffbd171b3f1fdd61de251685984c885e5efadb | Fix Elm extensions | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Diagnostics.Elm/ElmServiceCollectionExtensions.cs | src/Microsoft.AspNet.Diagnostics.Elm/ElmServiceCollectionExtensions.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Diagnostics.Elm;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection
{
public static class ElmServiceCollectionExtensions
{
/// <summary>
/// Registers an <see cref="ElmStore"/> and configures default <see cref="ElmOptions"/>.
/// </summary>
public static IServiceCollection AddElm([NotNull] this IServiceCollection services)
{
services.AddOptions();
services.AddSingleton<ElmStore>();
return services;
}
/// <summary>
/// Configures a set of <see cref="ElmOptions"/> for the application.
/// </summary>
/// <param name="services">The services available in the application.</param>
/// <param name="configureOptions">The <see cref="ElmOptions"/> which need to be configured.</param>
public static void ConfigureElm(
[NotNull] this IServiceCollection services,
[NotNull] Action<ElmOptions> configureOptions)
{
services.Configure(configureOptions);
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Diagnostics.Elm;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection
{
public static class ElmServiceCollectionExtensions
{
/// <summary>
/// Registers an <see cref="ElmStore"/> and configures <see cref="ElmOptions"/>.
/// </summary>
public static IServiceCollection AddElm([NotNull] this IServiceCollection services)
{
return services.AddElm(configureOptions: null);
}
/// <summary>
/// Registers an <see cref="ElmStore"/> and configures <see cref="ElmOptions"/>.
/// </summary>
public static IServiceCollection AddElm([NotNull] this IServiceCollection services, Action<ElmOptions> configureOptions)
{
services.AddSingleton<ElmStore>(); // registering the service so it can be injected into constructors
if (configureOptions != null)
{
services.Configure(configureOptions);
}
return services;
}
}
} | apache-2.0 | C# |
3962a42f0343d69cef11a2c6a1ce47dd29bdcfe3 | change for easier read | ProfessionalCSharp/ProfessionalCSharp7,ProfessionalCSharp/ProfessionalCSharp7,ProfessionalCSharp/ProfessionalCSharp7,ProfessionalCSharp/ProfessionalCSharp7 | ReflectionAndDynamic/DynamicSamples/DynamicSample/WroxDynamicObject.cs | ReflectionAndDynamic/DynamicSamples/DynamicSample/WroxDynamicObject.cs | using System;
using System.Collections.Generic;
using System.Dynamic;
namespace DynamicSample
{
public class WroxDynamicObject : DynamicObject
{
private Dictionary<string, object> _dynamicData = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
bool success = false;
result = null;
if (_dynamicData.ContainsKey(binder.Name))
{
result = _dynamicData[binder.Name];
success = true;
}
else
{
result = "Property Not Found!";
}
return success;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_dynamicData[binder.Name] = value;
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
dynamic method = _dynamicData[binder.Name];
result = method((DateTime)args[0]);
return result != null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Dynamic;
namespace DynamicSample
{
public class WroxDynamicObject : DynamicObject
{
private Dictionary<string, object> _dynamicData = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
bool success = false;
result = null;
if (success = _dynamicData.ContainsKey(binder.Name))
{
result = _dynamicData[binder.Name];
}
else
{
result = "Property Not Found!";
}
return success;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_dynamicData[binder.Name] = value;
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
dynamic method = _dynamicData[binder.Name];
result = method((DateTime)args[0]);
return result != null;
}
}
}
| mit | C# |
0e9df92a170e8eaa579e6c673e50c486ed821e03 | Update EntityQueryRepository.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Data/EntityFrameworkCore/EntityQueryRepository.cs | TIKSN.Framework.Core/Data/EntityFrameworkCore/EntityQueryRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityQueryRepository<TContext, TEntity, TIdentity> : EntityRepository<TContext, TEntity>,
IQueryRepository<TEntity, TIdentity>, IStreamRepository<TEntity>
where TContext : DbContext
where TEntity : class, IEntity<TIdentity>, new()
where TIdentity : IEquatable<TIdentity>
{
public EntityQueryRepository(TContext dbContext) : base(dbContext)
{
}
protected IQueryable<TEntity> Entities => this.dbContext.Set<TEntity>().AsNoTracking();
public Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken) =>
this.Entities.AnyAsync(a => a.ID.Equals(id), cancellationToken);
public Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken) =>
this.Entities.SingleAsync(entity => entity.ID.Equals(id), cancellationToken);
public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken) =>
this.Entities.SingleOrDefaultAsync(entity => entity.ID.Equals(id), cancellationToken);
public async Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids,
CancellationToken cancellationToken)
{
if (ids == null)
{
throw new ArgumentNullException(nameof(ids));
}
return await this.Entities.Where(entity => ids.Contains(entity.ID)).ToListAsync(cancellationToken).ConfigureAwait(false);
}
public async IAsyncEnumerable<TEntity> StreamAllAsync(CancellationToken cancellationToken)
{
await foreach (var entity in this.Entities.AsAsyncEnumerable().WithCancellation(cancellationToken))
{
yield return entity;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace TIKSN.Data.EntityFrameworkCore
{
public class EntityQueryRepository<TContext, TEntity, TIdentity> : EntityRepository<TContext, TEntity>,
IQueryRepository<TEntity, TIdentity>, IStreamRepository<TEntity>
where TContext : DbContext
where TEntity : class, IEntity<TIdentity>, new()
where TIdentity : IEquatable<TIdentity>
{
public EntityQueryRepository(TContext dbContext) : base(dbContext)
{
}
protected IQueryable<TEntity> Entities => this.dbContext.Set<TEntity>().AsNoTracking();
public Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken) =>
this.Entities.AnyAsync(a => a.ID.Equals(id), cancellationToken);
public Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken) =>
this.Entities.SingleAsync(entity => entity.ID.Equals(id), cancellationToken);
public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken) =>
this.Entities.SingleOrDefaultAsync(entity => entity.ID.Equals(id), cancellationToken);
public async Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids,
CancellationToken cancellationToken)
{
if (ids == null)
{
throw new ArgumentNullException(nameof(ids));
}
return await this.Entities.Where(entity => ids.Contains(entity.ID)).ToListAsync(cancellationToken);
}
public async IAsyncEnumerable<TEntity> StreamAllAsync(CancellationToken cancellationToken)
{
await foreach (var entity in this.Entities.AsAsyncEnumerable().WithCancellation(cancellationToken))
{
yield return entity;
}
}
}
}
| mit | C# |
3a63cc70e0cfd3a3c26dcf7f0f949da7b8470df4 | fix top nav dropdown | AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us | src/mikeandwan.us/Views/Shared/Components/AccountStatus/Default.cshtml | src/mikeandwan.us/Views/Shared/Components/AccountStatus/Default.cshtml | @using MawMvcApp.ViewComponents
@model AccountStatusViewModel
<ul class="navbar-nav">
@if(Model.IsAuthenticated) {
<li class="nav-item" class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#"><svg-icon icon="Person" class="icon"></svg-icon></a>
<ul class="dropdown-menu">
<li class="dropdown-item"><a asp-controller="account" asp-action="changepassword">change password</a></li>
<li class="dropdown-item"><a asp-controller="account" asp-action="editprofile">edit profile</a></li>
<li class="dropdown-item"><a asp-controller="account" asp-action="logout">logout</a></li>
</ul>
</li>
}
else {
<li class="nav-item"><a asp-controller="account" asp-action="login" class="nav-link px-3"><svg-icon icon="Person" class="icon"></svg-icon></a></li>
}
<li class="nav-item"><a asp-controller="about" asp-action="contact" class="nav-link px-3"><svg-icon icon="Envelope" class="icon"></svg-icon></a></li>
</ul>
| @using MawMvcApp.ViewComponents
@model AccountStatusViewModel
<ul class="navbar-nav">
@if(Model.IsAuthenticated) {
<li class="nav-item" class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><svg-icon icon="Person" class="icon"></svg-icon><svg-icon icon="CaretDown" class="icon caret"></svg-icon></a>
<ul class="dropdown-menu">
<li><a asp-controller="account" asp-action="changepassword">change password</a></li>
<li><a asp-controller="account" asp-action="editprofile">edit profile</a></li>
<li><a asp-controller="account" asp-action="logout">logout</a></li>
</ul>
</li>
}
else {
<li class="nav-item"><a asp-controller="account" asp-action="login" class="nav-link px-3"><svg-icon icon="Person" class="icon"></svg-icon></a></li>
}
<li class="nav-item"><a asp-controller="about" asp-action="contact" class="nav-link px-3"><svg-icon icon="Envelope" class="icon"></svg-icon></a></li>
</ul>
| mit | C# |
882d33397c9d21bfe43b62b80c1cc0e185ffbcfc | Fix logic error | hey-red/Mime | src/Mime/Magic.cs | src/Mime/Magic.cs | using System;
using System.Runtime.InteropServices;
namespace HeyRed.MimeGuesser
{
public class Magic : IDisposable
{
private IntPtr _magic;
public Magic(MagicOpenFlags flags, string dbPath = null)
{
_magic = MagicNative.magic_open(flags);
if (_magic == IntPtr.Zero)
{
throw new MagicException("Cannot create magic cookie.");
}
if (MagicNative.magic_load(_magic, dbPath) != 0)
{
throw new MagicException(GetLastError());
}
}
public string Read(string filePath)
{
var str = Marshal.PtrToStringAnsi(MagicNative.magic_file(_magic, filePath));
if (str == null)
{
throw new MagicException(GetLastError());
}
return str;
}
public string Read(byte[] buffer)
{
var str = Marshal.PtrToStringAnsi(MagicNative.magic_buffer(_magic, buffer, buffer.Length));
if (str == null)
{
throw new MagicException(GetLastError());
}
return str;
}
private string GetLastError()
{
var err = Marshal.PtrToStringAnsi(MagicNative.magic_error(_magic));
return char.ToUpper(err[0]) + err.Substring(1);
}
#region IDisposable support
~Magic()
{
Dispose();
}
public void Dispose()
{
if (_magic != IntPtr.Zero)
{
MagicNative.magic_close(_magic);
_magic = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
#endregion
}
}
| using System;
using System.Runtime.InteropServices;
namespace HeyRed.MimeGuesser
{
public class Magic : IDisposable
{
private IntPtr _magic;
public Magic(MagicOpenFlags flags, string dbPath = null)
{
_magic = MagicNative.magic_open(flags);
if (_magic == IntPtr.Zero)
{
throw new MagicException("Cannot create magic cookie.");
}
if (MagicNative.magic_load(_magic, dbPath) == -1 &&
dbPath != null)
{
throw new MagicException(GetLastError());
}
}
public string Read(string filePath)
{
var str = Marshal.PtrToStringAnsi(MagicNative.magic_file(_magic, filePath));
if (str == null)
{
throw new MagicException(GetLastError());
}
return str;
}
public string Read(byte[] buffer)
{
var str = Marshal.PtrToStringAnsi(MagicNative.magic_buffer(_magic, buffer, buffer.Length));
if (str == null)
{
throw new MagicException(GetLastError());
}
return str;
}
private string GetLastError()
{
var err = Marshal.PtrToStringAnsi(MagicNative.magic_error(_magic));
return char.ToUpper(err[0]) + err.Substring(1);
}
#region IDisposable support
~Magic()
{
Dispose();
}
public void Dispose()
{
if (_magic != IntPtr.Zero)
{
MagicNative.magic_close(_magic);
_magic = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
#endregion
}
}
| mit | C# |
5a828d0609b7229c70b774598b1f112512cac1ba | Bump Cake.Recipe from 2.1.0 to 2.2.0 | abeggchr/cake-gradle,abeggchr/cake-gradle | recipe.cake | recipe.cake | #l nuget:?package=Cake.Recipe&version=2.2.0
Environment.SetVariableNames();
BuildParameters.SetParameters(
context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "Cake.Gradle",
repositoryOwner: "cake-contrib",
shouldRunCodecov: true,
shouldRunDotNetCorePack: true,
shouldUseDeterministicBuilds: true);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context);
Build.RunDotNetCore();
| #l nuget:?package=Cake.Recipe&version=2.1.0
Environment.SetVariableNames();
BuildParameters.SetParameters(
context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "Cake.Gradle",
repositoryOwner: "cake-contrib",
shouldRunCodecov: true,
shouldRunDotNetCorePack: true,
shouldUseDeterministicBuilds: true);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context);
Build.RunDotNetCore();
| mit | C# |
72de465c34ea710b383c5d959397a50b1c6ee5ac | Update QuoteRepository.cs | Blacnova/NadekoBot,gfrewqpoiu/NadekoBot,shikhir-arora/NadekoBot,powered-by-moe/MikuBot,WoodenGlaze/NadekoBot,Nielk1/NadekoBot,Taknok/NadekoBot,Midnight-Myth/Mitternacht-NEW,ShadowNoire/NadekoBot,PravEF/EFNadekoBot,halitalf/NadekoMods,miraai/NadekoBot,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,ScarletKuro/NadekoBot,Midnight-Myth/Mitternacht-NEW,Youngsie1997/NadekoBot | src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs | src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs | using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
lowertext = text.ToLowerInvariant();
uppertext = text.ToUpperInvariant();
return _set.Where(q => q.Text.Contains(text) || q.Text.Contains(lowertext) || q.Text.Contains(uppertext) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
| using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
lowertext = text.ToLowerInvariant();
return _set.Where(q => q.Text.Contains(text) || q.Text.Contains(lowertext) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
| mit | C# |
8d2867a2f969282bfd2a32c4b82a13594989b334 | Remove get all with dynamic clause. SHould be handeled by user in own class. Otherwise forced to use FastCRUD | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/RepositoryGetAll.cs | src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/RepositoryGetAll.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public abstract partial class Repository<TSession, TEntity, TPk>
where TEntity : class, IEntity<TPk>
where TSession : ISession
{
public IEnumerable<TEntity> GetAll(ISession session = null)
{
return GetAllAsync(session).Result;
}
public async Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null)
{
if (session != null)
{
return await session.FindAsync<TEntity>();
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync<TEntity>();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper.FastCrud;
using Dapper.FastCrud.Configuration.StatementOptions.Builders;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public abstract partial class Repository<TSession, TEntity, TPk>
where TEntity : class, IEntity<TPk>
where TSession : ISession
{
public IEnumerable<TEntity> GetAll(ISession session = null)
{
return GetAllAsync(session).Result;
}
public async Task<IEnumerable<TEntity>> GetAllAsync(ISession session = null)
{
if (session != null)
{
return await session.FindAsync<TEntity>();
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync<TEntity>();
}
}
protected async Task<IEnumerable<TEntity>> GetAllAsync(ISession session, Action<IRangedBatchSelectSqlSqlStatementOptionsOptionsBuilder<TEntity>> statement)
{
if (session != null)
{
return await session.FindAsync(statement);
}
using (var uow = Factory.CreateSession<TSession>())
{
return await uow.FindAsync(statement);
}
}
}
}
| mit | C# |
bf0cbf182fe5d6505a8bea0254fa0f27b54585cb | rework of ValueSyntax | hahoyer/reni.cs,hahoyer/reni.cs,hahoyer/reni.cs | src/reni2/TokenClasses/Function.cs | src/reni2/TokenClasses/Function.cs | using hw.Parser;
using Reni.Parser;
namespace Reni.TokenClasses
{
[BelongsTo(typeof(MainTokenFactory))]
[Variant(false, false)]
[Variant(true, false)]
[Variant(false, true)]
sealed class Function : TokenClass, IValueProvider
{
readonly bool IsImplicit;
readonly bool IsMetaFunction;
public Function(bool isImplicit, bool isMetaFunction)
{
IsImplicit = isImplicit;
IsMetaFunction = isMetaFunction;
}
public override string Id => TokenId(IsImplicit, IsMetaFunction);
Result<ValueSyntax> IValueProvider.Get(BinaryTree binaryTree, ISyntaxScope scope)
=>
FunctionSyntax.Create(binaryTree.Left, IsImplicit, IsMetaFunction, binaryTree.Right, binaryTree
, scope);
public static string TokenId(bool isImplicit = false, bool isMetaFunction = false)
=> "/" + (isImplicit? "!" : "") + "\\" + (isMetaFunction? "/\\" : "");
}
} | using hw.Parser;
using Reni.Parser;
namespace Reni.TokenClasses
{
[BelongsTo(typeof(MainTokenFactory))]
[Variant(false, false)]
[Variant(true, false)]
[Variant(false, true)]
sealed class Function : TokenClass, IValueProvider
{
public static string TokenId(bool isImplicit = false, bool isMetaFunction = false)
=> "/" + (isImplicit ? "!" : "") + "\\" + (isMetaFunction ? "/\\" : "");
public override string Id => TokenId(_isImplicit, _isMetaFunction);
readonly bool _isImplicit;
readonly bool _isMetaFunction;
public Function(bool isImplicit, bool isMetaFunction)
{
_isImplicit = isImplicit;
_isMetaFunction = isMetaFunction;
}
Result<ValueSyntax> IValueProvider.Get(BinaryTree binaryTree, ISyntaxScope scope)
=>
FunctionSyntax.Create(binaryTree.Left, _isImplicit, _isMetaFunction, binaryTree.Right, binaryTree, scope);
}
} | mit | C# |
0bc2bff05b1119c937ba8afc5e754d69129fa950 | bump ver | AntonyCorbett/OnlyT,AntonyCorbett/OnlyT | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.63")] | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.62")] | mit | C# |
ec647141aa72f7d876770dd8d6b2c5e6d78b520e | work backup | asmrobot/ZTImage | src/ZTImage.HttpParser/HttpFrame.cs | src/ZTImage.HttpParser/HttpFrame.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZTImage.HttpParser
{
public class HttpFrame
{
public HttpFrame():this(http_parser_type.HTTP_BOTH)
{
}
public HttpFrame(http_parser_type parserType)
{
this.type = parserType;
Init();
}
private void Init()
{
this.state = (this.type == http_parser_type.HTTP_REQUEST ? state.s_start_req : (this.type == http_parser_type.HTTP_RESPONSE ? state.s_start_res : state.s_start_req_or_res));
this.http_errno = http_errno.HPE_OK;
}
/// <summary>
/// 重置复用
/// </summary>
public void Reset()
{
}
public http_parser_type type;//enum http_parser_type : 2bits
public flags flags; // F_* values from 'flags' enum; semi-public :8bits
internal state state; //enum state from http_parser.c :7 bits
internal header_states header_state; // enum header_state from http_parser.c :7bits
internal byte index;//index into current matcher :7bits
internal bool lenient_http_headers = false;//http header 宽容模式 1bits
public UInt32 nread; /* # bytes read in various scenarios */
public UInt64 content_length; /* # bytes in body (0 if no Content-Length header) */
/** READ-ONLY **/
public byte http_major;
public byte http_minor;
public UInt16 status_code; /* responses only :2bytes*/
public http_method method; /* requests only :8bits*/
public http_errno http_errno; //7 bits
/* 1 = Upgrade header was present and the parser has exited because of that.
* 0 = No upgrade header present.
* Should be checked when http_parser_execute() returns in addition to
* error checking.
*/
public bool upgrade; //1bits
/** PUBLIC **/
public ArraySegment<byte> data; /* A pointer to get hook to the "connection" or "socket" object */
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZTImage.HttpParser
{
public class HttpFrame
{
public HttpFrame():this(http_parser_type.HTTP_BOTH)
{
}
public HttpFrame(http_parser_type parserType)
{
this.type = parserType;
Init();
}
private void Init()
{
this.state = (this.type == http_parser_type.HTTP_REQUEST ? state.s_start_req : (this.type == http_parser_type.HTTP_RESPONSE ? state.s_start_res : state.s_start_req_or_res));
this.http_errno = http_errno.HPE_OK;
}
public http_parser_type type;//enum http_parser_type : 2bits
public flags flags; // F_* values from 'flags' enum; semi-public :8bits
internal state state; //enum state from http_parser.c :7 bits
internal header_states header_state; // enum header_state from http_parser.c :7bits
internal byte index;//index into current matcher :7bits
internal bool lenient_http_headers = false;//http header 宽容模式 1bits
public UInt32 nread; /* # bytes read in various scenarios */
public UInt64 content_length; /* # bytes in body (0 if no Content-Length header) */
/** READ-ONLY **/
public byte http_major;
public byte http_minor;
public UInt16 status_code; /* responses only :2bytes*/
public http_method method; /* requests only :8bits*/
public http_errno http_errno; //7 bits
/* 1 = Upgrade header was present and the parser has exited because of that.
* 0 = No upgrade header present.
* Should be checked when http_parser_execute() returns in addition to
* error checking.
*/
public bool upgrade; //1bits
/** PUBLIC **/
public ArraySegment<byte> data; /* A pointer to get hook to the "connection" or "socket" object */
}
}
| apache-2.0 | C# |
d44040d800f638ff4b53aa4d4f979d040c319588 | Add more arango specific attributes. | yojimbo87/ArangoDB-NET,kangkot/ArangoDB-NET | src/Arango/Arango.Client/API/Documents/ArangoProperty.cs | src/Arango/Arango.Client/API/Documents/ArangoProperty.cs | using System;
namespace Arango.Client
{
[AttributeUsage(AttributeTargets.Property)]
public class ArangoProperty : Attribute
{
public bool Serializable { get; set; }
public bool Identity { get; set; }
public bool Key { get; set; }
public bool Revision { get; set; }
public bool From { get; set; }
public bool To { get; set; }
public string Alias { get; set; }
public ArangoProperty()
{
Serializable = true;
Identity = false;
Key = false;
Revision = false;
From = false;
To = false;
}
}
}
| using System;
namespace Arango.Client
{
[AttributeUsage(AttributeTargets.Property)]
public class ArangoProperty : Attribute
{
public string Alias { get; set; }
public bool Serializable { get; set; }
public ArangoProperty()
{
Serializable = true;
}
}
}
| mit | C# |
5a882e0ca6aff5e8c91193f8def7dbdeda0bccee | Add support for `submit` option on Dispute update (#1562) | stripe/stripe-dotnet,richardlawley/stripe.net | src/Stripe.net/Services/Disputes/DisputeUpdateOptions.cs | src/Stripe.net/Services/Disputes/DisputeUpdateOptions.cs | namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class DisputeUpdateOptions : BaseOptions
{
/// <summary>
/// Evidence to upload, to respond to a dispute. Updating any field in the hash will submit
/// all fields in the hash for review. The combined character count of all fields is
/// limited to 150,000.
/// </summary>
[JsonProperty("evidence")]
public DisputeEvidenceOptions Evidence { get; set; }
/// <summary>
/// A set of key/value pairs that you can attach to a charge object. It can be useful for
/// storing additional information about the customer in a structured format. It's often a
/// good idea to store an email address in metadata for tracking later.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// Whether to immediately submit evidence to the bank. If <code>false</code>, evidence is
/// staged on the dispute. Staged evidence is visible in the API and Dashboard, and can be
/// submitted to the bank by making another request with this attribute set to
/// <code>true</code> (the default).
/// </summary>
[JsonProperty("submit")]
public bool? Submit { get; set; }
}
}
| namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class DisputeUpdateOptions : BaseOptions
{
[JsonProperty("evidence")]
public DisputeEvidenceOptions Evidence { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
}
}
| apache-2.0 | C# |
a63ea96a3cb5ecc9fbf83f0f0de68a0c8b485a5e | Fix broken TemplateHost sample | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/Framework/Framework/Compilation/DataContextPropertyAssigningVisitor.cs | src/Framework/Framework/Compilation/DataContextPropertyAssigningVisitor.cs | using System;
using System.Collections.Generic;
using System.Text;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Controls.Infrastructure;
using DotVVM.Framework.Utils;
namespace DotVVM.Framework.Compilation
{
/// <summary>
/// Assigns <see cref="Internal.DataContextTypeProperty" /> to all controls that have different datacontext that their parent
/// </summary>
public class DataContextPropertyAssigningVisitor: ResolvedControlTreeVisitor
{
public override void VisitControl(ResolvedControl control)
{
if (control.DataContextTypeStack != control.Parent?.As<ResolvedControl>()?.DataContextTypeStack || control.Parent is ResolvedTreeRoot)
{
var c = control.Metadata.Type;
// RawLiteral (and similar) don't need datacontext type, it only slows down compilation
if (c != typeof(RawLiteral) && c != typeof(GlobalizeResource) && c != typeof(RequiredResource))
{
control.SetProperty(new ResolvedPropertyValue(Internal.DataContextTypeProperty, control.DataContextTypeStack));
}
}
base.VisitControl(control);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Controls.Infrastructure;
using DotVVM.Framework.Utils;
namespace DotVVM.Framework.Compilation
{
/// <summary>
/// Assigns <see cref="Internal.DataContextTypeProperty" /> to all controls that have different datacontext that their parent
/// </summary>
public class DataContextPropertyAssigningVisitor: ResolvedControlTreeVisitor
{
public override void VisitControl(ResolvedControl control)
{
if (control.DataContextTypeStack != control.Parent?.As<ResolvedControl>()?.DataContextTypeStack || control.Parent is ResolvedTreeRoot)
{
// RawLiteral don't need datacontext type, it only slows down compilation
if (control.Metadata.Type != typeof(RawLiteral))
{
control.SetProperty(new ResolvedPropertyValue(Internal.DataContextTypeProperty, control.DataContextTypeStack));
}
}
base.VisitControl(control);
}
}
}
| apache-2.0 | C# |
c4b8dd456dce6a62fa96c7643f4e664a055f4c81 | update persisted grant mapper | IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework | src/IdentityServer4.EntityFramework/Mappers/PersistedGrantMapperProfile.cs | src/IdentityServer4.EntityFramework/Mappers/PersistedGrantMapperProfile.cs | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using AutoMapper;
namespace IdentityServer4.EntityFramework.Mappers
{
/// <summary>
/// Defines entity/model mapping for persisted grants.
/// </summary>
/// <seealso cref="AutoMapper.Profile" />
public class PersistedGrantMapperProfile:Profile
{
/// <summary>
/// <see cref="PersistedGrantMapperProfile">
/// </see>
/// </summary>
public PersistedGrantMapperProfile()
{
CreateMap<Entities.PersistedGrant, Models.PersistedGrant>(MemberList.Destination)
.ReverseMap();
}
}
}
| // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using AutoMapper;
namespace IdentityServer4.EntityFramework.Mappers
{
/// <summary>
/// Defines entity/model mapping for persisted grants.
/// </summary>
/// <seealso cref="AutoMapper.Profile" />
public class PersistedGrantMapperProfile:Profile
{
/// <summary>
/// <see cref="PersistedGrantMapperProfile">
/// </see>
/// </summary>
public PersistedGrantMapperProfile()
{
// entity to model
CreateMap<Entities.PersistedGrant, Models.PersistedGrant>(MemberList.Destination);
// model to entity
CreateMap<Models.PersistedGrant, Entities.PersistedGrant>(MemberList.Source);
}
}
}
| apache-2.0 | C# |
94f5477d5e939be65c178e06e512f1a1ce361b3d | Fix #351 : SiteName defined in setup is not used | yiji/Orchard2,stevetayloruk/Orchard2,jtkech/Orchard2,lukaskabrt/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,lukaskabrt/Orchard2,yiji/Orchard2,xkproject/Orchard2,xkproject/Orchard2,lukaskabrt/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,jtkech/Orchard2,lukaskabrt/Orchard2,petedavis/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,jtkech/Orchard2,yiji/Orchard2,jtkech/Orchard2 | src/Orchard.Cms.Web/Modules/Orchard.Settings/Services/SetupEventHandler.cs | src/Orchard.Cms.Web/Modules/Orchard.Settings/Services/SetupEventHandler.cs | using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orchard.Events;
namespace Orchard.Settings.Services
{
public interface ISetupEventHandler : IEventHandler
{
Task Setup(string siteName, string userName);
}
/// <summary>
/// During setup, registers the Super User.
/// </summary>
public class SetupEventHandler : ISetupEventHandler
{
private readonly IServiceProvider _serviceProvider;
public SetupEventHandler(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task Setup(string siteName, string userName)
{
var siteService = _serviceProvider.GetRequiredService<ISiteService>();
// Updating site settings
var siteSettings = await siteService.GetSiteSettingsAsync();
siteSettings.SiteName = siteName;
siteSettings.SuperUser = userName;
await siteService.UpdateSiteSettingsAsync(siteSettings);
// TODO: Add Encryption Settings in
}
}
}
| using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orchard.Events;
namespace Orchard.Settings.Services
{
public interface ISetupEventHandler : IEventHandler
{
Task Setup(string userName);
}
/// <summary>
/// During setup, registers the Super User.
/// </summary>
public class SetupEventHandler : ISetupEventHandler
{
private readonly IServiceProvider _serviceProvider;
public SetupEventHandler(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task Setup(string userName)
{
var siteService = _serviceProvider.GetRequiredService<ISiteService>();
// Updating site settings
var siteSettings = await siteService.GetSiteSettingsAsync();
siteSettings.SuperUser = userName;
await siteService.UpdateSiteSettingsAsync(siteSettings);
// TODO: Add Encryption Settings in
}
}
}
| bsd-3-clause | C# |
e61b2064cb2e629ac192379fbcfaa71ade20f9e6 | Fix route name clash | Generic-Voting-Application/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,stevenhillcox/voting-application,stevenhillcox/voting-application,tpkelly/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application | VotingApplication/VotingApplication.Web.Api/App_Start/WebApiConfig.cs | VotingApplication/VotingApplication.Web.Api/App_Start/WebApiConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using System.Net.Http.Headers;
namespace VotingApplication.Web.Api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name:"UserVoteApiRoute",
routeTemplate: "api/user/{userId}/vote/{voteId}",
defaults: new { controller = "UserVote", voteId = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "UserSessionVoteApiRoute",
routeTemplate: "api/user/{userId}/session/{sessionId}/vote/{voteId}",
defaults: new { controller = "UserSessionVote", voteId = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using System.Net.Http.Headers;
namespace VotingApplication.Web.Api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name:"UserVoteApiRoute",
routeTemplate: "api/user/{userId}/vote/{voteId}",
defaults: new { controller = "UserVote", voteId = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "UserVoteApiRoute",
routeTemplate: "api/user/{userId}/session/{sessionId}/vote/{voteId}",
defaults: new { controller = "UserSessionVote", voteId = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
}
| apache-2.0 | C# |
e2984c319851683bf0ae7f150e6b55dcd3e99556 | Update SettingsServiceTests.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core.Tests/Settings/SettingsServiceTests.cs | TIKSN.Framework.Core.Tests/Settings/SettingsServiceTests.cs | using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TIKSN.DependencyInjection;
using TIKSN.FileSystem;
namespace TIKSN.Settings.Tests
{
public partial class SettingsServiceTests
{
partial void SetupDenepdencies()
{
this.services.AddFrameworkPlatform();
this.services.AddSingleton<ISettingsService, FileSettingsService>();
this.services.AddSingleton(new KnownFoldersConfiguration(this.GetType().Assembly,
KnownFolderVersionConsideration.None));
var configurationRoot = new ConfigurationBuilder()
.AddInMemoryCollection()
.Build();
configurationRoot["RelativePath"] = "settings.db";
this.services.ConfigurePartial<FileSettingsServiceOptions, FileSettingsServiceOptionsValidator>(
configurationRoot);
}
}
}
| using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TIKSN.DependencyInjection;
using TIKSN.FileSystem;
namespace TIKSN.Settings.Tests
{
public partial class SettingsServiceTests
{
partial void SetupDenepdencies()
{
services.AddFrameworkPlatform();
services.AddSingleton<ISettingsService, FileSettingsService>();
services.AddSingleton(new KnownFoldersConfiguration(GetType().Assembly, KnownFolderVersionConsideration.None));
var configurationRoot = new ConfigurationBuilder()
.AddInMemoryCollection()
.Build();
configurationRoot["RelativePath"] = "settings.db";
services.ConfigurePartial<FileSettingsServiceOptions, FileSettingsServiceOptionsValidator>(configurationRoot);
}
}
} | mit | C# |
12769f90a759df5ba2b091e868a25fa5fc104deb | Add missing effect types to generic effect enum | CoraleStudios/Colore | src/Colore/Effects/Generic/Effect.cs | src/Colore/Effects/Generic/Effect.cs | // ---------------------------------------------------------------------------------------
// <copyright file="Effect.cs" company="Corale">
// Copyright © 2015-2018 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Colore.Effects.Generic
{
using System.ComponentModel;
using System.Runtime.Serialization;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// Generic device effects.
/// </summary>
/// <remarks>Not all devices are compatible with every effect type.</remarks>
[JsonConverter(typeof(StringEnumConverter))]
public enum Effect
{
/// <summary>
/// No effect.
/// </summary>
[PublicAPI]
[EnumMember(Value = "CHROMA_NONE")]
None = 0,
/// <summary>
/// Static color effect.
/// </summary>
[PublicAPI]
[EnumMember(Value = "CHROMA_STATIC")]
Static = 6,
/// <summary>
/// Custom effect.
/// </summary>
[PublicAPI]
[EnumMember(Value = "CHROMA_CUSTOM")]
Custom = 7,
/// <summary>
/// Reserved effect.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[EnumMember(Value = "CHROMA_RESERVED")]
//// ReSharper disable once UnusedMember.Global
Reserved = 8,
/// <summary>
/// Invalid effect.
/// </summary>
[PublicAPI]
[EnumMember(Value = "CHROMA_INVALID")]
Invalid = 9
}
}
| // ---------------------------------------------------------------------------------------
// <copyright file="Effect.cs" company="Corale">
// Copyright © 2015-2018 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Colore.Effects.Generic
{
using System.ComponentModel;
using System.Runtime.Serialization;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// Generic device effects.
/// </summary>
/// <remarks>Not all devices are compatible with every effect type.</remarks>
[JsonConverter(typeof(StringEnumConverter))]
public enum Effect
{
/// <summary>
/// No effect.
/// </summary>
[PublicAPI]
[EnumMember(Value = "CHROMA_NONE")]
None = 0,
/// <summary>
/// Reserved effect.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
[EnumMember(Value = "CHROMA_RESERVED")]
//// ReSharper disable once UnusedMember.Global
Reserved = 8,
/// <summary>
/// Invalid effect.
/// </summary>
[PublicAPI]
[EnumMember(Value = "CHROMA_INVALID")]
Invalid = 9
}
}
| mit | C# |
93397873bb34e70f8d7e8e7564ca9aebee0d4eb3 | make non-ASCII names show in sources | gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop | src/BloomExe/Collection/ShortcutMaker.cs | src/BloomExe/Collection/ShortcutMaker.cs | using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
#if !__MonoCS__
using IWshRuntimeLibrary;
#endif
using File = System.IO.File;
namespace Bloom.Collection
{
static class ShortcutMaker
{
#if !__MonoCS__
const int MAX_PATH = 255;
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern int GetShortPathName([MarshalAs(UnmanagedType.LPTStr)] string path,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath, int shortPathLength);
#endif
public static void CreateDirectoryShortcut(string targetPath, string whereToPutItPath)
{
var name = Path.GetFileName(targetPath);
var linkPath = Path.Combine(whereToPutItPath, name) + ".lnk";
var shortLinkPath = "";
if(File.Exists(linkPath))
File.Delete(linkPath);
#if !__MonoCS__
var wshShell = new WshShellClass();
var shortcut = (IWshShortcut)wshShell.CreateShortcut(linkPath);
try
{
shortcut.TargetPath = targetPath;
}
catch (Exception)
{
if (targetPath == Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(targetPath))) throw;
// this exception was caused by non-ascii characters in the path, use 8.3 names instead
var shortTargetPath = new StringBuilder(MAX_PATH);
GetShortPathName(targetPath, shortTargetPath, MAX_PATH);
var shortWhereToPutPath = new StringBuilder(MAX_PATH);
GetShortPathName(whereToPutItPath, shortWhereToPutPath, MAX_PATH);
name = Path.GetFileName(shortTargetPath.ToString());
shortLinkPath = Path.Combine(shortWhereToPutPath.ToString(), name) + ".lnk";
if (File.Exists(shortLinkPath))
File.Delete(shortLinkPath);
shortcut = (IWshShortcut)wshShell.CreateShortcut(shortLinkPath);
shortcut.TargetPath = shortTargetPath.ToString();
}
shortcut.Save();
// now rename the link to the correct name if needed
if (!string.IsNullOrEmpty(shortLinkPath))
File.Move(shortLinkPath, linkPath);
#else
// It's tempting to use symbolic links instead which would work much nicer - iff
// the UnixSymbolicLinkInfo class wouldn't cause us to crash...
// var name = Path.GetFileName(targetPath);
// string linkPath = Path.Combine(whereToPutItPath, name);
// var shortcut = new Mono.Unix.UnixSymbolicLinkInfo(linkPath);
// if (shortcut.Exists)
// shortcut.Delete();
//
// var target = new Mono.Unix.UnixSymbolicLinkInfo(targetPath);
// target.CreateSymbolicLink(linkPath);
File.WriteAllText(linkPath, targetPath);
#endif
}
}
}
| using System;
using System.IO;
#if !__MonoCS__
using IWshRuntimeLibrary;
#endif
using File = System.IO.File;
namespace Bloom.Collection
{
class ShortcutMaker
{
public static void CreateDirectoryShortcut(string targetPath, string whereToPutItPath)
{
var name = Path.GetFileName(targetPath);
string linkPath = Path.Combine(whereToPutItPath, name) + ".lnk";
if(File.Exists(linkPath))
File.Delete(linkPath);
#if !__MonoCS__
var WshShell = new WshShellClass();
var shortcut = (IWshShortcut)WshShell.CreateShortcut(linkPath);
try
{
shortcut.TargetPath = targetPath;
//shortcut.Description = "Launch My Application";
//shortcut.IconLocation = Application.StartupPath + @"\app.ico";
}
catch (Exception error)
{
if (targetPath !=System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(targetPath)))
throw new ApplicationException("Unfortunately, windows had trouble making a shortcut to remember this project, because of a problem with non-ASCII characters. Sorry!");
throw error;
}
shortcut.Save();
#else
// It's tempting to use symbolic links instead which would work much nicer - iff
// the UnixSymbolicLinkInfo class wouldn't cause us to crash...
// var name = Path.GetFileName(targetPath);
// string linkPath = Path.Combine(whereToPutItPath, name);
// var shortcut = new Mono.Unix.UnixSymbolicLinkInfo(linkPath);
// if (shortcut.Exists)
// shortcut.Delete();
//
// var target = new Mono.Unix.UnixSymbolicLinkInfo(targetPath);
// target.CreateSymbolicLink(linkPath);
File.WriteAllText(linkPath, targetPath);
#endif
}
}
}
| mit | C# |
145075b13942a8987dbfdb0cfa633df0dabc1560 | 修改 Detail view (加入Rating欄位). | NemoChenTW/MvcMovie,NemoChenTW/MvcMovie,NemoChenTW/MvcMovie | src/MvcMovie/Views/Movies/Details.cshtml | src/MvcMovie/Views/Movies/Details.cshtml | @model MvcMovie.Models.Movie
@{
ViewData["Title"] = "Details";
}
<h2>Details</h2>
<div>
<h4>Movie</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Genre)
</dt>
<dd>
@Html.DisplayFor(model => model.Genre)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Price)
</dt>
<dd>
@Html.DisplayFor(model => model.Price)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ReleaseDate)
</dt>
<dd>
@Html.DisplayFor(model => model.ReleaseDate)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Rating)
</dt>
<dd>
@Html.DisplayFor(model => model.Rating)
</dd>
</dl>
</div>
<p>
<a asp-action="Edit" asp-route-id="@Model.ID">Edit</a> |
<a asp-action="Index">Back to List</a>
</p>
| @model MvcMovie.Models.Movie
@{
ViewData["Title"] = "Details";
}
<h2>Details</h2>
<div>
<h4>Movie</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Genre)
</dt>
<dd>
@Html.DisplayFor(model => model.Genre)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Price)
</dt>
<dd>
@Html.DisplayFor(model => model.Price)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ReleaseDate)
</dt>
<dd>
@Html.DisplayFor(model => model.ReleaseDate)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
</dl>
</div>
<p>
<a asp-action="Edit" asp-route-id="@Model.ID">Edit</a> |
<a asp-action="Index">Back to List</a>
</p>
| apache-2.0 | C# |
60d584827db1a0b3bbfd29be365ca2a811f65f0c | fix peek min | justcoding121/Algorithm-Sandbox,justcoding121/Advanced-Algorithms | Advanced.Algorithms/DataStructures/Queues/PriorityQueue/MinPriorityQueue.cs | Advanced.Algorithms/DataStructures/Queues/PriorityQueue/MinPriorityQueue.cs | using System;
using System.Collections;
using System.Collections.Generic;
namespace Advanced.Algorithms.DataStructures
{
/// A priority queue implementation using min heap,
/// assuming that lower values have a higher priority.
public class MinPriorityQueue<T> : IEnumerable<T> where T : IComparable
{
private readonly BMinHeap<T> minHeap = new BMinHeap<T>();
/// <summary>
/// Time complexity:O(log(n)).
/// </summary>
public void Enqueue(T item)
{
minHeap.Insert(item);
}
/// <summary>
/// Time complexity:O(log(n)).
/// </summary>
public T Dequeue()
{
return minHeap.ExtractMin();
}
/// <summary>
/// Time complexity:O(1).
/// </summary>
/// <returns></returns>
public T Peek()
{
return minHeap.PeekMin();
}
public IEnumerator<T> GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return minHeap.GetEnumerator();
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
namespace Advanced.Algorithms.DataStructures
{
/// A priority queue implementation using min heap,
/// assuming that lower values have a higher priority.
public class MinPriorityQueue<T> : IEnumerable<T> where T : IComparable
{
private readonly BMinHeap<T> minHeap = new BMinHeap<T>();
/// <summary>
/// Time complexity:O(log(n)).
/// </summary>
public void Enqueue(T item)
{
minHeap.Insert(item);
}
/// <summary>
/// Time complexity:O(log(n)).
/// </summary>
public T Dequeue()
{
return minHeap.ExtractMin();
}
/// <summary>
/// Time complexity:O(1).
/// </summary>
/// <returns></returns>
public T Peek()
{
return maxHeap.PeekMax();
}
public IEnumerator<T> GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return minHeap.GetEnumerator();
}
}
}
| mit | C# |
6518b89659d7a97b2aa172dea891520daaf6a151 | update vs to release | Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal | Master/Appleseed/Projects/PortableAreas/Password/Properties/AssemblyInfo.cs | Master/Appleseed/Projects/PortableAreas/Password/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("Password")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Password")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-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("1bbaa317-aebe-425c-8db3-a1aee724365d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.131.463")]
[assembly: AssemblyFileVersion("1.4.131.463")]
| 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("Password")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Password")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-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("1bbaa317-aebe-425c-8db3-a1aee724365d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.98.383")]
[assembly: AssemblyFileVersion("1.4.98.383")]
| apache-2.0 | C# |
3536cf5aade8a67bb610d29586a53b963be96a66 | Fix #5183 - update docs of CreateWriter | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Mvc.Abstractions/Formatters/OutputFormatterWriteContext.cs | src/Microsoft.AspNetCore.Mvc.Abstractions/Formatters/OutputFormatterWriteContext.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
/// <summary>
/// A context object for <see cref="IOutputFormatter.WriteAsync(OutputFormatterWriteContext)"/>.
/// </summary>
public class OutputFormatterWriteContext : OutputFormatterCanWriteContext
{
/// <summary>
/// Creates a new <see cref="OutputFormatterWriteContext"/>.
/// </summary>
/// <param name="httpContext">The <see cref="Http.HttpContext"/> for the current request.</param>
/// <param name="writerFactory">The delegate used to create a <see cref="TextWriter"/> for writing the response.</param>
/// <param name="objectType">The <see cref="Type"/> of the object to write to the response.</param>
/// <param name="object">The object to write to the response.</param>
public OutputFormatterWriteContext(HttpContext httpContext, Func<Stream, Encoding, TextWriter> writerFactory, Type objectType, object @object)
: base(httpContext)
{
if (writerFactory == null)
{
throw new ArgumentNullException(nameof(writerFactory));
}
WriterFactory = writerFactory;
ObjectType = objectType;
Object = @object;
}
/// <summary>
/// <para>
/// Gets or sets a delegate used to create a <see cref="TextWriter"/> for writing text to the response.
/// </para>
/// <para>
/// Write to <see cref="HttpResponse.Body"/> directly to write binary data to the response.
/// </para>
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="TextWriter"/> created by this delegate will encode text and write to the
/// <see cref="HttpResponse.Body"/> stream. Call this delegate to create a <see cref="TextWriter"/>
/// for writing text output to the response stream.
/// </para>
/// <para>
/// To implement a formatter that writes binary data to the response stream, do not use the
/// <see cref="WriterFactory"/> delegate, and use <see cref="HttpResponse.Body"/> instead.
/// </para>
/// </remarks>
public virtual Func<Stream, Encoding, TextWriter> WriterFactory { get; protected set; }
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
/// <summary>
/// A context object for <see cref="IOutputFormatter.WriteAsync(OutputFormatterWriteContext)"/>.
/// </summary>
public class OutputFormatterWriteContext : OutputFormatterCanWriteContext
{
/// <summary>
/// Creates a new <see cref="OutputFormatterWriteContext"/>.
/// </summary>
/// <param name="httpContext">The <see cref="Http.HttpContext"/> for the current request.</param>
/// <param name="writerFactory">The delegate used to create a <see cref="TextWriter"/> for writing the response.</param>
/// <param name="objectType">The <see cref="Type"/> of the object to write to the response.</param>
/// <param name="object">The object to write to the response.</param>
public OutputFormatterWriteContext(HttpContext httpContext, Func<Stream, Encoding, TextWriter> writerFactory, Type objectType, object @object)
: base(httpContext)
{
if (writerFactory == null)
{
throw new ArgumentNullException(nameof(writerFactory));
}
WriterFactory = writerFactory;
ObjectType = objectType;
Object = @object;
}
/// <summary>
/// Gets or sets a delegate used to create a <see cref="TextWriter"/> for writing the response.
/// </summary>
public virtual Func<Stream, Encoding, TextWriter> WriterFactory { get; protected set; }
}
}
| apache-2.0 | C# |
79bab5f08ec671417e2d6ba5254c02a6c21071c0 | Address feedback | eriawan/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,diryboy/roslyn,bartdesmet/roslyn,eriawan/roslyn,dotnet/roslyn,weltkante/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,wvdd007/roslyn,wvdd007/roslyn,bartdesmet/roslyn,mavasani/roslyn,mavasani/roslyn,dotnet/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,sharwell/roslyn,sharwell/roslyn,eriawan/roslyn,physhi/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,diryboy/roslyn,KevinRansom/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn | src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.cs | src/Analyzers/CSharp/Analyzers/ConvertTypeofToNameof/CSharpConvertTypeOfToNameOfDiagnosticAnalyzer.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 Microsoft.CodeAnalysis.ConvertTypeOfToNameOf;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf
{
/// <summary>
/// Finds code like typeof(someType).Name and determines whether it can be changed to nameof(someType), if yes then it offers a diagnostic
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpConvertTypeOfToNameOfDiagnosticAnalyzer : AbstractConvertTypeOfToNameOfDiagnosticAnalyzer
{
private static readonly string s_title = CSharpAnalyzersResources.typeof_can_be_converted__to_nameof;
public CSharpConvertTypeOfToNameOfDiagnosticAnalyzer() : base(s_title, LanguageNames.CSharp)
{
}
protected override bool IsValidTypeofAction(OperationAnalysisContext context)
{
var node = context.Operation.Syntax;
var syntaxTree = node.SyntaxTree;
// nameof was added in CSharp 6.0, so don't offer it for any languages before that time
if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp6)
{
return false;
}
// Make sure that the syntax that we're looking at is actually a typeof expression and that
// the parent syntax is a member access expression otherwise the syntax is not the kind of
// expression that we want to analyze
return node is TypeOfExpressionSyntax { Parent: MemberAccessExpressionSyntax } typeofExpression &&
// nameof(System.Void) isn't allowed in C#.
typeofExpression is not { Type: PredefinedTypeSyntax { Keyword: { RawKind: (int)SyntaxKind.VoidKeyword } } };
}
}
}
| // 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 Microsoft.CodeAnalysis.ConvertTypeOfToNameOf;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis.CSharp.ConvertTypeOfToNameOf
{
/// <summary>
/// Finds code like typeof(someType).Name and determines whether it can be changed to nameof(someType), if yes then it offers a diagnostic
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpConvertTypeOfToNameOfDiagnosticAnalyzer : AbstractConvertTypeOfToNameOfDiagnosticAnalyzer
{
private static readonly string s_title = CSharpAnalyzersResources.typeof_can_be_converted__to_nameof;
public CSharpConvertTypeOfToNameOfDiagnosticAnalyzer() : base(s_title, LanguageNames.CSharp)
{
}
protected override bool IsValidTypeofAction(OperationAnalysisContext context)
{
var node = context.Operation.Syntax;
var syntaxTree = node.SyntaxTree;
// nameof was added in CSharp 6.0, so don't offer it for any languages before that time
if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp6)
{
return false;
}
// Make sure that the syntax that we're looking at is actually a typeof expression and that
// the parent syntax is a member access expression otherwise the syntax is not the kind of
// expression that we want to analyze
return node is TypeOfExpressionSyntax { Parent: MemberAccessExpressionSyntax } &&
// nameof(System.Void) isn't allowed in C#.
((ITypeOfOperation)context.Operation).TypeOperand.SpecialType != SpecialType.System_Void;
}
}
}
| mit | C# |
3093302edaa40ce7cc6d165e4c200921d37352ea | initialize returns gameobject | taka-oyama/UniHttp | Assets/UniHttp/HttpManager.cs | Assets/UniHttp/HttpManager.cs | using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System;
namespace UniHttp
{
public sealed class HttpManager : MonoBehaviour
{
public string dataPath;
public int maxPersistentConnections;
public string encryptionPassword;
public static IContentSerializer RequestBodySerializer;
public static ISslVerifier SslVerifier;
public static CacheStorage CacheStorage;
internal static Queue<Action> MainThreadQueue;
internal static HttpStreamPool TcpConnectionPool;
internal static CookieJar CookieJar;
internal static CacheHandler CacheHandler;
public static GameObject Initalize(string dataPath = null, int maxPersistentConnections = 6)
{
if(GameObject.Find("HttpManager")) {
throw new Exception("HttpManager should not be Initialized more than once");
}
GameObject go = new GameObject("HttpManager");
GameObject.DontDestroyOnLoad(go);
go.AddComponent<HttpManager>().Setup(dataPath, maxPersistentConnections);
return go;
}
void Setup(string baseDataPath, int maxPersistentConnections)
{
this.dataPath = baseDataPath ?? Application.temporaryCachePath + "/UniHttp/";
this.maxPersistentConnections = maxPersistentConnections;
this.encryptionPassword = Application.bundleIdentifier;
Directory.CreateDirectory(dataPath);
RequestBodySerializer = new JsonSerializer();
SslVerifier = new DefaultSslVerifier();
CacheStorage = new CacheStorage(new DirectoryInfo(dataPath + "Cache/"), encryptionPassword);
MainThreadQueue = new Queue<Action>();
TcpConnectionPool = new HttpStreamPool(maxPersistentConnections);
CookieJar = new CookieJar(new SecureFileIO(dataPath + "Cookie.bin", encryptionPassword));
CacheHandler = new CacheHandler(new SecureFileIO(dataPath + "CacheInfo.bin", encryptionPassword), CacheStorage);
}
void FixedUpdate()
{
while(MainThreadQueue.Count > 0) {
MainThreadQueue.Dequeue().Invoke();
}
}
internal static void Save()
{
CookieJar.SaveToFile();
CacheHandler.SaveToFile();
}
void OnApplicationPause(bool isPaused)
{
if(isPaused) {
Save();
}
}
void OnApplicationQuit()
{
Save();
}
}
}
| using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System;
namespace UniHttp
{
public sealed class HttpManager : MonoBehaviour
{
public string dataPath;
public int maxPersistentConnections;
public string encryptionPassword;
public static IContentSerializer RequestBodySerializer;
public static ISslVerifier SslVerifier;
public static CacheStorage CacheStorage;
internal static Queue<Action> MainThreadQueue;
internal static HttpStreamPool TcpConnectionPool;
internal static CookieJar CookieJar;
internal static CacheHandler CacheHandler;
public static void Initalize(string dataPath = null, int maxPersistentConnections = 6)
{
if(GameObject.Find("HttpManager")) {
throw new Exception("HttpManager should not be Initialized more than once");
}
GameObject go = new GameObject("HttpManager");
go.AddComponent<HttpManager>().Setup(dataPath, maxPersistentConnections);
GameObject.DontDestroyOnLoad(go);
}
void Setup(string baseDataPath, int maxPersistentConnections)
{
this.dataPath = baseDataPath ?? Application.temporaryCachePath + "/UniHttp/";
this.maxPersistentConnections = maxPersistentConnections;
this.encryptionPassword = Application.bundleIdentifier;
Directory.CreateDirectory(dataPath);
RequestBodySerializer = new JsonSerializer();
SslVerifier = new DefaultSslVerifier();
CacheStorage = new CacheStorage(new DirectoryInfo(dataPath + "Cache/"), encryptionPassword);
MainThreadQueue = new Queue<Action>();
TcpConnectionPool = new HttpStreamPool(maxPersistentConnections);
CookieJar = new CookieJar(new SecureFileIO(dataPath + "Cookie.bin", encryptionPassword));
CacheHandler = new CacheHandler(new SecureFileIO(dataPath + "CacheInfo.bin", encryptionPassword), CacheStorage);
}
void FixedUpdate()
{
while(MainThreadQueue.Count > 0) {
MainThreadQueue.Dequeue().Invoke();
}
}
internal static void Save()
{
CookieJar.SaveToFile();
CacheHandler.SaveToFile();
}
void OnApplicationPause(bool isPaused)
{
if(isPaused) {
Save();
}
}
void OnApplicationQuit()
{
Save();
}
}
}
| mit | C# |
cfbed220f37829c80b2e9ae1c2fc523919f6da98 | Fix creation of admin role in DB initialization | GeorgDangl/WebDocu,GeorgDangl/WebDocu,GeorgDangl/WebDocu | src/Dangl.WebDocumentation/Models/DatabaseInitialization.cs | src/Dangl.WebDocumentation/Models/DatabaseInitialization.cs | using System.Linq;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Dangl.WebDocumentation.Models
{
public static class DatabaseInitialization
{
public static void Initialize(ApplicationDbContext Context)
{
SetUpRoles(Context);
}
private static void SetUpRoles(ApplicationDbContext Context)
{
// Add Admin role if not present
if (Context.Roles.All(role => role.Name != "Admin"))
{
Context.Roles.Add(new IdentityRole {Name = "Admin", NormalizedName = "ADMIN"});
Context.SaveChanges();
}
else if (Context.Roles.Any(role => role.Name == "Admin" && role.NormalizedName != "Admin"))
{
var adminRole = Context.Roles.FirstOrDefault(role => role.Name == "Admin");
adminRole.NormalizedName = "ADMIN";
Context.SaveChanges();
}
}
}
} | using System.Linq;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Dangl.WebDocumentation.Models
{
public static class DatabaseInitialization
{
public static void Initialize(ApplicationDbContext Context)
{
SetUpRoles(Context);
}
private static void SetUpRoles(ApplicationDbContext Context)
{
// Add Admin role if not present
if (Context.Roles.All(Role => Role.Name != "Admin"))
{
Context.Roles.Add(new IdentityRole {Name = "Admin"});
Context.SaveChanges();
}
}
}
} | mit | C# |
82157f6e927869d62c69924003cf0b35e90b073a | Remove Margin from Approval Buttons | 4-of-3/cvgs,4-of-3/cvgs | CVGS/Views/Reviews/Pending.cshtml | CVGS/Views/Reviews/Pending.cshtml | @model IEnumerable<CVGS.Models.REVIEW>
@{
ViewBag.Title = "Pending Reviews";
}
<h2>@ViewBag.Title</h2>
<table class="table">
<tr>
<th>
User
</th>
<th>
@Html.DisplayNameFor(model => model.GAME.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th>
@Html.DisplayNameFor(model => model.ReviewText)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.MEMBER.FName) @Html.DisplayFor(modelItem => item.MEMBER.LName)
(@Html.DisplayFor(modelItem => item.MEMBER.UserName))
</td>
<td>
@Html.DisplayFor(modelItem => item.GAME.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rating)
</td>
<td>
@if (item.ReviewText != null && item.ReviewText.Length > 140)
{
item.ReviewText = item.ReviewText.Substring(0, 137) + "...";
}
@Html.DisplayFor(modelItem => item.ReviewText)
</td>
<td style="white-space:nowrap;">
<a href="@Url.Action("Approve", new { memberId = item.MemberId, gameId = item.GameId })" class="btn btn--empty btn--save"><i class="fa fa-check"></i></a>
<a href="@Url.Action("Delete", new { memberId = item.MemberId, gameId = item.GameId })" class="btn btn--empty btn btn--delete"><i class="fa fa-close btn--empty"></i></a>
<a href="@Url.Action("Details", new { memberId = item.MemberId, gameId = item.GameId })" class="btn btn-default">Details</a>
</td>
</tr>
}
</table>
| @model IEnumerable<CVGS.Models.REVIEW>
@{
ViewBag.Title = "Pending Reviews";
}
<h2>@ViewBag.Title</h2>
<table class="table">
<tr>
<th>
User
</th>
<th>
@Html.DisplayNameFor(model => model.GAME.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th>
@Html.DisplayNameFor(model => model.ReviewText)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.MEMBER.FName) @Html.DisplayFor(modelItem => item.MEMBER.LName)
(@Html.DisplayFor(modelItem => item.MEMBER.UserName))
</td>
<td>
@Html.DisplayFor(modelItem => item.GAME.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rating)
</td>
<td>
@if (item.ReviewText != null && item.ReviewText.Length > 140)
{
item.ReviewText = item.ReviewText.Substring(0, 137) + "...";
}
@Html.DisplayFor(modelItem => item.ReviewText)
</td>
<td style="white-space:nowrap;">
<a href="@Url.Action("Approve", new { memberId = item.MemberId, gameId = item.GameId })" class="btn btn--action btn--save"><i class="fa fa-check"></i></a>
<a href="@Url.Action("Delete", new { memberId = item.MemberId, gameId = item.GameId })" class="btn btn-default btn btn--delete"><i class="fa fa-close"></i></a>
<a href="@Url.Action("Details", new { memberId = item.MemberId, gameId = item.GameId })" class="btn btn-default">Details</a>
</td>
</tr>
}
</table>
| mit | C# |
663ce7ec1bd069904dbee36cb9e43451a6726ec5 | Use Span to drop byte[1] allocations (dotnet/coreclr#15680) (#5190) | gregkalapos/corert,gregkalapos/corert,gregkalapos/corert,gregkalapos/corert | src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.cs | src/System.Private.CoreLib/shared/System/IO/PinnedBufferMemoryStream.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.
/*============================================================
**
**
**
**
**
** Purpose: Pins a byte[], exposing it as an unmanaged memory
** stream. Used in ResourceReader for corner cases.
**
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.IO
{
internal sealed unsafe class PinnedBufferMemoryStream : UnmanagedMemoryStream
{
private byte[] _array;
private GCHandle _pinningHandle;
internal PinnedBufferMemoryStream(byte[] array)
{
Debug.Assert(array != null, "Array can't be null");
_array = array;
_pinningHandle = GCHandle.Alloc(array, GCHandleType.Pinned);
// Now the byte[] is pinned for the lifetime of this instance.
// But I also need to get a pointer to that block of memory...
int len = array.Length;
fixed (byte* ptr = &MemoryMarshal.GetReference((Span<byte>)array))
Initialize(ptr, len, len, FileAccess.Read);
}
public override int Read(Span<byte> destination) => ReadCore(destination);
public override void Write(ReadOnlySpan<byte> source) => WriteCore(source);
~PinnedBufferMemoryStream()
{
Dispose(false);
}
protected override void Dispose(bool disposing)
{
if (_pinningHandle.IsAllocated)
{
_pinningHandle.Free();
}
base.Dispose(disposing);
}
}
}
| // 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.
/*============================================================
**
**
**
**
**
** Purpose: Pins a byte[], exposing it as an unmanaged memory
** stream. Used in ResourceReader for corner cases.
**
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.IO
{
internal sealed unsafe class PinnedBufferMemoryStream : UnmanagedMemoryStream
{
private byte[] _array;
private GCHandle _pinningHandle;
internal PinnedBufferMemoryStream(byte[] array)
{
Debug.Assert(array != null, "Array can't be null");
int len = array.Length;
// Handle 0 length byte arrays specially.
if (len == 0)
{
array = new byte[1];
len = 0;
}
_array = array;
_pinningHandle = GCHandle.Alloc(array, GCHandleType.Pinned);
// Now the byte[] is pinned for the lifetime of this instance.
// But I also need to get a pointer to that block of memory...
fixed (byte* ptr = &_array[0])
Initialize(ptr, len, len, FileAccess.Read);
}
public override int Read(Span<byte> destination) => ReadCore(destination);
public override void Write(ReadOnlySpan<byte> source) => WriteCore(source);
~PinnedBufferMemoryStream()
{
Dispose(false);
}
protected override void Dispose(bool disposing)
{
if (_pinningHandle.IsAllocated)
{
_pinningHandle.Free();
}
base.Dispose(disposing);
}
}
}
| mit | C# |
2254d475bdebe3a4b1ce46d501e0a193a374d3f5 | Apply suggestions from code review | dawoe/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS | src/Umbraco.Web.Common/Extensions/UmbracoApplicationBuilder.Identity.cs | src/Umbraco.Web.Common/Extensions/UmbracoApplicationBuilder.Identity.cs | using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Security;
namespace Umbraco.Extensions
{
public static partial class UmbracoApplicationBuilderExtensions
{
public static IUmbracoBuilder SetBackOfficeUserManager<TUserManager>(this IUmbracoBuilder builder)
where TUserManager : UserManager<BackOfficeIdentityUser>, IBackOfficeUserManager
{
Type customType = typeof(TUserManager);
Type userManagerType = typeof(UserManager<BackOfficeIdentityUser>);
builder.Services.Replace(ServiceDescriptor.Scoped(typeof(IBackOfficeUserManager), customType));
builder.Services.AddScoped(customType, services => services.GetRequiredService(userManagerType));
builder.Services.Replace(ServiceDescriptor.Scoped(userManagerType, customType));
return builder;
}
}
}
| using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Security;
namespace Umbraco.Extensions
{
public static partial class UmbracoApplicationBuilderExtensions
{
public static IUmbracoBuilder SetBackOfficeUserManager<TUserManager>(this IUmbracoBuilder builder)
where TUserManager : UserManager<BackOfficeIdentityUser>, IBackOfficeUserManager
{
var customType = typeof(TUserManager);
var userManagerType = typeof(UserManager<BackOfficeIdentityUser>);
builder.Services.Replace(ServiceDescriptor.Scoped(typeof(IBackOfficeUserManager),customType));
builder.Services.AddScoped(customType, services => services.GetRequiredService(userManagerType));
builder.Services.Replace(ServiceDescriptor.Scoped(userManagerType,customType));
return builder;
}
}
}
| mit | C# |
304bb9ce5b9058a59925cb425e1cec1b25658561 | Send proper 401 for access denied | MacDennis76/Unicorn,rmwatson5/Unicorn,PetersonDave/Unicorn,bllue78/Unicorn,kamsar/Unicorn,GuitarRich/Unicorn,kamsar/Unicorn,PetersonDave/Unicorn,MacDennis76/Unicorn,bllue78/Unicorn,GuitarRich/Unicorn,rmwatson5/Unicorn | src/Unicorn/ControlPanel/AccessDenied.cs | src/Unicorn/ControlPanel/AccessDenied.cs | using System.Web;
using System.Web.UI;
namespace Unicorn.ControlPanel
{
public class AccessDenied : IControlPanelControl
{
public void Render(HtmlTextWriter writer)
{
writer.Write("<h2>Access Denied</h2>");
writer.Write("<p>You need to <a href=\"/sitecore/admin/login.aspx?ReturnUrl={0}\">sign in to Sitecore as an administrator</a> to use the Unicorn control panel.</p>", HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
HttpContext.Current.Response.StatusCode = 401;
}
}
}
| using System.Web;
using System.Web.UI;
namespace Unicorn.ControlPanel
{
public class AccessDenied : IControlPanelControl
{
public void Render(HtmlTextWriter writer)
{
writer.Write("<h2>Access Denied</h2>");
writer.Write("<p>You need to <a href=\"/sitecore/admin/login.aspx?ReturnUrl={0}\">sign in to Sitecore as an administrator</a> to use the Unicorn control panel.</p>", HttpUtility.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery));
}
}
}
| mit | C# |
84a198800e4e07871fa246ca4273468e899028f8 | change IsNew_OldEntity_Returns* test name from true to false | tc-dev/tc-dev.Core | tests/tc-dev.Core.UnitTests/Domain/Extensions/IdentifiableUtilsTests.cs | tests/tc-dev.Core.UnitTests/Domain/Extensions/IdentifiableUtilsTests.cs | using System;
using NUnit.Framework;
using tc_dev.Core.Domain.Extensions;
namespace tc_dev.Core.UnitTests.Domain.Extensions
{
[TestFixture]
public class IdentifiableUtilsTests
{
[Test]
public void IsNew_NullEntity_ThrowsException() {
FakeEntity nullEntity = null;
Assert.Throws<ArgumentNullException>(() => nullEntity.IsNew());
}
[Test]
public void IsNew_NewEntity_ReturnsTrue() {
FakeEntity newEntity = new FakeEntity();
var result = newEntity.IsNew();
Assert.That(result, Is.True);
}
[Test]
public void IsNew_OldEntity_ReturnsFalse() {
FakeEntity oldEntity = new FakeEntity {
Id = 42,
DateCreated = DateTime.Now.AddDays(-42)
};
var result = oldEntity.IsNew();
Assert.That(result, Is.False);
}
}
}
| using System;
using NUnit.Framework;
using tc_dev.Core.Domain.Extensions;
namespace tc_dev.Core.UnitTests.Domain.Extensions
{
[TestFixture]
public class IdentifiableUtilsTests
{
[Test]
public void IsNew_NullEntity_ThrowsException() {
FakeEntity nullEntity = null;
Assert.Throws<ArgumentNullException>(() => nullEntity.IsNew());
}
[Test]
public void IsNew_NewEntity_ReturnsTrue() {
FakeEntity newEntity = new FakeEntity();
var result = newEntity.IsNew();
Assert.That(result, Is.True);
}
[Test]
public void IsNew_OldEntity_ReturnsTrue() {
FakeEntity oldEntity = new FakeEntity {
Id = 42,
DateCreated = DateTime.Now.AddDays(-42)
};
var result = oldEntity.IsNew();
Assert.That(result, Is.False);
}
}
}
| mit | C# |
ebe61a232837dd4c782deca5f8aabbba34e6085e | Comment code | mstrother/BmpListener | BmpListener/Bgp/Capability.cs | BmpListener/Bgp/Capability.cs | using System;
using System.Linq;
namespace BmpListener.Bgp
{
public abstract class Capability
{
//private readonly int length;
// http://www.iana.org/assignments/capability-codes/capability-codes.xhtml
public enum CapabilityCode
{
Multiprotocol = 1,
RouteRefresh = 2,
//TODO capability code 4
GracefulRestart = 64,
FourOctetAs = 65,
AddPath = 69,
EnhancedRouteRefresh = 70,
CiscoRouteRefresh = 128
//TODO capability code 129
}
protected Capability(ArraySegment<byte> data)
{
CapabilityType = (CapabilityCode)data.First();
Length = data.ElementAt(1);
}
public CapabilityCode CapabilityType { get; }
public int Length { get; }
public bool ShouldSerializeLength()
{
return false;
}
public static Capability GetCapability(ArraySegment<byte> data)
{
var capabilityType = (CapabilityCode)data.First();
switch (capabilityType)
{
case CapabilityCode.Multiprotocol:
return new CapabilityMultiProtocol(data);
case CapabilityCode.RouteRefresh:
return new CapabilityRouteRefresh(data);
case CapabilityCode.GracefulRestart:
return new CapabilityGracefulRestart(data);
case CapabilityCode.FourOctetAs:
return new CapabilityFourOctetAsNumber(data);
case CapabilityCode.AddPath:
return new CapabilityAddPath(data);
case CapabilityCode.EnhancedRouteRefresh:
return new CapabilityEnhancedRouteRefresh(data);
case CapabilityCode.CiscoRouteRefresh:
return new CapabilityCiscoRouteRefresh(data);
default:
return null;
}
}
}
} | using System;
using System.Linq;
namespace BmpListener.Bgp
{
public abstract class Capability
{
//private readonly int length;
public enum CapabilityCode
{
Multiprotocol = 1,
RouteRefresh = 2,
//TODO capability code 4
GracefulRestart = 64,
FourOctetAs = 65,
AddPath = 69,
EnhancedRouteRefresh = 70,
CiscoRouteRefresh = 128
//TODO capability code 129
}
protected Capability(ArraySegment<byte> data)
{
CapabilityType = (CapabilityCode)data.First();
Length = data.ElementAt(1);
}
public CapabilityCode CapabilityType { get; }
public int Length { get; }
public bool ShouldSerializeLength()
{
return false;
}
public static Capability GetCapability(ArraySegment<byte> data)
{
var capabilityType = (CapabilityCode)data.First();
switch (capabilityType)
{
case CapabilityCode.Multiprotocol:
return new CapabilityMultiProtocol(data);
case CapabilityCode.RouteRefresh:
return new CapabilityRouteRefresh(data);
case CapabilityCode.GracefulRestart:
return new CapabilityGracefulRestart(data);
case CapabilityCode.FourOctetAs:
return new CapabilityFourOctetAsNumber(data);
case CapabilityCode.AddPath:
return new CapabilityAddPath(data);
case CapabilityCode.EnhancedRouteRefresh:
return new CapabilityEnhancedRouteRefresh(data);
case CapabilityCode.CiscoRouteRefresh:
return new CapabilityCiscoRouteRefresh(data);
default:
return null;
}
}
}
} | mit | C# |
54d1fbd369a962611dfca191f65ace6344b070af | update directives for AHK v2 | maul-esel/CobaltAHK,maul-esel/CobaltAHK | CobaltAHK/Syntax/Directive.cs | CobaltAHK/Syntax/Directive.cs | using System;
namespace CobaltAHK
{
public static partial class Syntax
{
public enum Directive
{
ClipboardTimeout,
ErrorStdOut,
HotkeyInterval,
HotkeyModifierTimeout,
Hotstring,
If,
IfTimeout,
IfWinActive,
IfWinExist,
Include,
InputLevel,
InstallKeybdHook,
InstallMouseHook,
KeyHistory,
MaxHotkeysPerInterval,
MaxThreads,
MaxThreadsBuffer,
MaxThreadsPerHotkey,
MenuMaskKey,
MustDeclare,
NoTrayIcon,
SingleInstance,
UseHook,
Warn,
WinActivateForce
}
}
}
| using System;
namespace CobaltAHK
{
public static partial class Syntax
{
public enum Directive
{
ClipboardTimeout,
CommentFlag,
ErrorStdOut,
EscapeChar,
HotkeyInterval,
HotkeyModifierTimeout,
Hotstring,
If,
IfTimeout,
IfWinActive,
IfWinExist,
Include,
InputLevel,
InstallKeybdHook,
InstallMouseHook,
KeyHistory,
MaxHotkeysPerInterval,
MaxMem,
MaxThreads,
MaxThreadsBuffer,
MaxThreadsPerHotkey,
MenuMaskKey,
NoEnv,
NoTrayIcon,
Persistent,
SingleInstance,
UseHook,
Warn,
WinActivateForce
}
}
}
| mit | C# |
806a069cebf13347f5a96a5a9ceb7a3e000904cc | Simplify code | ridercz/AutoACME | Altairis.AutoAcme.Core/Challenges/ManagementExtensions.cs | Altairis.AutoAcme.Core/Challenges/ManagementExtensions.cs | using System;
using System.Collections.Generic;
using System.Management;
using System.Threading.Tasks;
namespace Altairis.AutoAcme.Core.Challenges {
public static class ManagementExtensions {
private static CompletedEventHandler CreateCompletedHandler<T>(this TaskCompletionSource<T> that, T result = default) {
return (sender, eventArgs) => {
switch (eventArgs.Status) {
case ManagementStatus.NoError:
case ManagementStatus.False:
that.SetResult(result);
break;
case ManagementStatus.OperationCanceled:
that.SetCanceled();
break;
default:
that.SetException(new ManagementException(eventArgs.Status.ToString()));
break;
}
};
}
public static Task<IReadOnlyList<ManagementBaseObject>> InvokeMethodAsync(this ManagementClass that, string name, params object[] args) {
var objects = new List<ManagementBaseObject>();
var taskSource = new TaskCompletionSource<IReadOnlyList<ManagementBaseObject>>();
var watcher = new ManagementOperationObserver();
watcher.ObjectReady += (sender, eventArgs) => objects.Add(eventArgs.NewObject);
watcher.Completed += taskSource.CreateCompletedHandler(objects);
that.InvokeMethod(watcher, name, args);
return taskSource.Task;
}
public static Task DeleteAsync(this ManagementObject that) {
var taskSource = new TaskCompletionSource<object>();
var watcher = new ManagementOperationObserver();
watcher.Completed += taskSource.CreateCompletedHandler();
that.Delete(watcher);
return taskSource.Task;
}
}
}
| using System;
using System.Collections.Generic;
using System.Management;
using System.Threading.Tasks;
namespace Altairis.AutoAcme.Core.Challenges {
public static class ManagementExtensions {
private static CompletedEventHandler CreateCompletedHandler<T>(this TaskCompletionSource<T> that, T result = default(T)) {
return (sender, eventArgs) => {
switch (eventArgs.Status) {
case ManagementStatus.NoError:
case ManagementStatus.False:
that.SetResult(result);
break;
case ManagementStatus.OperationCanceled:
that.SetCanceled();
break;
default:
that.SetException(new ManagementException(eventArgs.Status.ToString()));
break;
}
};
}
public static Task<IReadOnlyList<ManagementBaseObject>> InvokeMethodAsync(this ManagementClass that, string name, params object[] args) {
var objects = new List<ManagementBaseObject>();
var taskSource = new TaskCompletionSource<IReadOnlyList<ManagementBaseObject>>();
var watcher = new ManagementOperationObserver();
watcher.ObjectReady += (sender, eventArgs) => objects.Add(eventArgs.NewObject);
watcher.Completed += taskSource.CreateCompletedHandler(objects);
that.InvokeMethod(watcher, name, args);
return taskSource.Task;
}
public static Task DeleteAsync(this ManagementObject that) {
var taskSource = new TaskCompletionSource<object>();
var watcher = new ManagementOperationObserver();
watcher.Completed += taskSource.CreateCompletedHandler();
that.Delete(watcher);
return taskSource.Task;
}
}
}
| mit | C# |
58d48c6ba452a5a0592cc9b28c9dbe8837f36a8a | Fix it again | appetizermonster/Unity3D-ActionEngine | Assets/ActionEngine/AEScript/Editor/AEScriptDataDrawer.cs | Assets/ActionEngine/AEScript/Editor/AEScriptDataDrawer.cs | using System;
using System.Collections;
using UnityEditor;
using UnityEngine;
namespace ActionEngine {
[CustomPropertyDrawer(typeof(AEScriptData))]
public sealed class AEScriptDataDrawer : PropertyDrawer {
private const int TEXT_HEIGHT = 18;
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
EditorGUI.BeginProperty(position, label, property);
var labelPosition = position;
labelPosition.height = TEXT_HEIGHT - 2;
property.isExpanded = EditorGUI.Foldout(labelPosition, property.isExpanded, label);
if (!property.isExpanded) {
EditorGUI.EndProperty();
return;
}
var oldIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
const int INDENT = 30;
const int LABEL_WIDTH = 50;
var keyRect = new Rect(position.x + INDENT + LABEL_WIDTH, position.y + TEXT_HEIGHT, position.width - INDENT - LABEL_WIDTH, TEXT_HEIGHT);
var typeRect = keyRect; typeRect.y += TEXT_HEIGHT;
var valueRect = typeRect; valueRect.y += TEXT_HEIGHT;
var keyLabelRect = new Rect(position.x + INDENT, keyRect.y, LABEL_WIDTH, TEXT_HEIGHT);
var typeLabelRect = keyLabelRect; typeLabelRect.y += TEXT_HEIGHT;
var valueLabelRect = typeLabelRect; valueLabelRect.y += TEXT_HEIGHT;
var keyProp = property.FindPropertyRelative("key");
var typeProp = property.FindPropertyRelative("type");
EditorGUI.PrefixLabel(keyLabelRect, new GUIContent("Key"));
EditorGUI.PropertyField(keyRect, keyProp, GUIContent.none);
EditorGUI.PrefixLabel(typeLabelRect, new GUIContent("Type"));
EditorGUI.PropertyField(typeRect, typeProp, GUIContent.none);
try {
var typeEnumString = typeProp.enumNames[typeProp.enumValueIndex];
// Unity strips '@' prefix for naming variables, so we don't need to add '@' prefix
var valueVariableName = typeEnumString.ToLowerInvariant();
var valueProp = property.FindPropertyRelative(valueVariableName);
EditorGUI.PrefixLabel(valueLabelRect, new GUIContent("Value"));
EditorGUI.PropertyField(valueRect, valueProp, GUIContent.none, true);
} catch (Exception ex) {
Debug.LogException(ex);
}
EditorGUI.indentLevel = oldIndent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight (SerializedProperty property, GUIContent label) {
if (property.isExpanded)
return base.GetPropertyHeight(property, label) + TEXT_HEIGHT * 3;
return base.GetPropertyHeight(property, label);
}
}
}
| using System;
using System.Collections;
using UnityEditor;
using UnityEngine;
namespace ActionEngine {
[CustomPropertyDrawer(typeof(AEScriptData))]
public sealed class AEScriptDataDrawer : PropertyDrawer {
private const int TEXT_HEIGHT = 18;
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
EditorGUI.BeginProperty(position, label, property);
property.isExpanded = EditorGUI.Foldout(position, property.isExpanded, label);
if (!property.isExpanded) {
EditorGUI.EndProperty();
return;
}
var oldIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
const int INDENT = 30;
const int LABEL_WIDTH = 50;
var keyRect = new Rect(position.x + INDENT + LABEL_WIDTH, position.y + TEXT_HEIGHT, position.width - INDENT - LABEL_WIDTH, TEXT_HEIGHT);
var typeRect = keyRect; typeRect.y += TEXT_HEIGHT;
var valueRect = typeRect; valueRect.y += TEXT_HEIGHT;
var keyLabelRect = new Rect(position.x + INDENT, keyRect.y, LABEL_WIDTH, TEXT_HEIGHT);
var typeLabelRect = keyLabelRect; typeLabelRect.y += TEXT_HEIGHT;
var valueLabelRect = typeLabelRect; valueLabelRect.y += TEXT_HEIGHT;
var keyProp = property.FindPropertyRelative("key");
var typeProp = property.FindPropertyRelative("type");
EditorGUI.PrefixLabel(keyLabelRect, new GUIContent("Key"));
EditorGUI.PropertyField(keyRect, keyProp, GUIContent.none);
EditorGUI.PrefixLabel(typeLabelRect, new GUIContent("Type"));
EditorGUI.PropertyField(typeRect, typeProp, GUIContent.none);
try {
var typeEnumString = typeProp.enumNames[typeProp.enumValueIndex];
// Unity strips '@' prefix for naming variables, so we don't need to add '@' prefix
var valueVariableName = typeEnumString.ToLowerInvariant();
var valueProp = property.FindPropertyRelative(valueVariableName);
EditorGUI.PrefixLabel(valueLabelRect, new GUIContent("Value"));
EditorGUI.PropertyField(valueRect, valueProp, GUIContent.none, true);
} catch (Exception ex) {
Debug.LogException(ex);
}
EditorGUI.indentLevel = oldIndent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight (SerializedProperty property, GUIContent label) {
if (property.isExpanded)
return base.GetPropertyHeight(property, label) + TEXT_HEIGHT * 3;
return base.GetPropertyHeight(property, label);
}
}
}
| mit | C# |
996430b495c9b26db2e43037462d37676ea65be1 | Fix typo. | int19h/PTVS,zooba/PTVS,int19h/PTVS,zooba/PTVS,int19h/PTVS,int19h/PTVS,zooba/PTVS,zooba/PTVS,int19h/PTVS,zooba/PTVS,zooba/PTVS,int19h/PTVS | Python/Product/PythonTools/PythonTools/Options/LanguageServerOptions.cs | Python/Product/PythonTools/PythonTools/Options/LanguageServerOptions.cs | // Python Tools for Visual Studio
// Copyright(c) Microsoft 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. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using Microsoft.PythonTools.Infrastructure;
namespace Microsoft.PythonTools.Options {
/// <summary>
/// Stores options related to the language server
/// </summary>
public sealed class LanguageServerOptions {
private readonly PythonToolsService _pyService;
private const string Category = "LanguageServer";
internal LanguageServerOptions(PythonToolsService pyService) {
_pyService = pyService;
Load();
}
public string TypeShedPath { get; set; }
public bool SuppressTypeShed { get; set; }
public bool ServerDisabled { get; set; }
public void Load() {
TypeShedPath = _pyService.LoadString(nameof(TypeShedPath), Category);
SuppressTypeShed = _pyService.LoadBool(nameof(SuppressTypeShed), Category) ?? false;
ServerDisabled = _pyService.LoadBool(nameof(ServerDisabled), Category) ?? false;
Changed?.Invoke(this, EventArgs.Empty);
}
public void Save() {
_pyService.SaveString(nameof(TypeShedPath), Category, TypeShedPath);
_pyService.SaveBool(nameof(SuppressTypeShed), Category, SuppressTypeShed);
_pyService.SaveBool(nameof(ServerDisabled), Category, ServerDisabled);
Changed?.Invoke(this, EventArgs.Empty);
}
public void Reset() {
TypeShedPath = string.Empty;
SuppressTypeShed = false;
ServerDisabled = false;
Changed?.Invoke(this, EventArgs.Empty);
}
public event EventHandler Changed;
}
} | // Python Tools for Visual Studio
// Copyright(c) Microsoft 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. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using Microsoft.PythonTools.Infrastructure;
namespace Microsoft.PythonTools.Options {
/// <summary>
/// Stores options related to the language server
/// </summary>
public sealed class LanguageServerOptions {
private readonly PythonToolsService _pyService;
private const string Category = "LanguageServer";
internal LanguageServerOptions(PythonToolsService pyService) {
_pyService = pyService;
Load();
}
public string TypeShedPath { get; set; }
public bool SuppressTypeShed { get; set; }
public bool ServerDisabled { get; set; }
public void Load() {
TypeShedPath = _pyService.LoadString(nameof(TypeShedPath), Category);
SuppressTypeShed = _pyService.LoadBool(nameof(SuppressTypeShed), Category) ?? false;
ServerDisabled = _pyService.LoadBool(nameof(ServerDisabled), Category) ?? false;
Changed?.Invoke(this, EventArgs.Empty);
}
public void Save() {
_pyService.SaveString(nameof(TypeShedPath), Category, TypeShedPath);
_pyService.SaveBool(nameof(SuppressTypeShed), Category, SuppressTypeShed);
_pyService.SaveBool(nameof(ServerDisabled), Category, ServerDisabled);
Changed?.Invoke(this, EventArgs.Empty);
}
public void Reset() {
TypeShedPath = string.Empty;
SuppressTypeShed = false;
ServerDisabled = false;
Changed?.Invoke(this, EventArgs.Empty);
}
public event EventHandler Changed;
}
} | apache-2.0 | C# |
09c55bd178c864b374767f8cb34b2d2e780a10b5 | Remove this last piece of hardcodedness | red-gate/Knockout.Binding | Knockout.Binding/KnockoutProxy.cs | Knockout.Binding/KnockoutProxy.cs | using System;
namespace KnckoutBindingGenerater
{
public class KnockoutProxy
{
private readonly string m_ViewModelName;
private readonly string m_PrimitiveObservables;
private readonly string m_MethodProxies;
private readonly string m_CollectionObservables;
const string c_ViewModelTemplate = @"
var {0}ProxyObject = function() {{
{1}
{2}
{3}
}}
window.{4} = new {0}ProxyObject();
ko.applyBindings({4});
";
public KnockoutProxy(string viewModelName, string primitiveObservables, string methodProxies, string collectionObservables)
{
m_ViewModelName = viewModelName;
m_PrimitiveObservables = primitiveObservables;
m_MethodProxies = methodProxies;
m_CollectionObservables = collectionObservables;
}
public string KnockoutViewModel
{
get
{
return String.Format(c_ViewModelTemplate,
m_ViewModelName,
m_PrimitiveObservables,
m_MethodProxies,
m_CollectionObservables,
ViewModelInstanceName);
}
}
public string ViewModelInstanceName
{
get { return String.Format("{0}ProxyObjectInstance", m_ViewModelName); }
}
}
} | using System;
namespace KnckoutBindingGenerater
{
public class KnockoutProxy
{
private readonly string m_ViewModelName;
private readonly string m_PrimitiveObservables;
private readonly string m_MethodProxies;
private readonly string m_CollectionObservables;
const string c_ViewModelTemplate = @"
var {0}ProxyObject = function() {{
{1}
{2}
{3}
}}
window.{4} = new {0}ProxyObject();
ko.applyBindings({4});
";
public KnockoutProxy(string viewModelName, string primitiveObservables, string methodProxies, string collectionObservables)
{
m_ViewModelName = viewModelName;
m_PrimitiveObservables = primitiveObservables;
m_MethodProxies = methodProxies;
m_CollectionObservables = collectionObservables;
}
public string KnockoutViewModel
{
get
{
return String.Format(c_ViewModelTemplate,
m_ViewModelName,
m_PrimitiveObservables,
m_MethodProxies,
m_CollectionObservables,
ViewModelInstanceName);
}
}
public string ViewModelInstanceName
{
get { return "kevin"; }
}
}
} | mit | C# |
1b9d19e646d8a5cf53f038a3f727ff0461bdcac0 | Fix failing tests | rmunn/lfmerge-autosrtests,rmunn/lfmerge-autosrtests | LfMerge.AutomatedSRTests/Tests.cs | LfMerge.AutomatedSRTests/Tests.cs | // Copyright (c) 2017 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace LfMerge.AutomatedSRTests
{
[TestFixture]
public class Tests
{
private const int MinVersion = 7000068;
private const int MaxVersion = 7000070;
private LanguageDepotHelper _languageDepot;
private MongoHelper _mongo;
private static string SRState
{
get
{
var stateFile = Path.Combine(LfMergeHelper.BaseDir, "state", "autosrtests.state");
Assert.That(File.Exists(stateFile), Is.True, $"Statefile '{stateFile}' doesn't exist");
var stateFileContent = JObject.Parse(File.ReadAllText(stateFile));
var state = stateFileContent["SRState"].ToString();
return state;
}
}
[TestFixtureSetUp]
public void FixtureSetup()
{
MongoHelper.Initialize();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
MongoHelper.Cleanup();
Settings.Cleanup();
}
[SetUp]
public void Setup()
{
_languageDepot = new LanguageDepotHelper();
_mongo = new MongoHelper("sf_autosrtests");
}
[TearDown]
public void TearDown()
{
_mongo.Dispose();
_languageDepot.Dispose();
}
[Test]
public void Clone([Range(MinVersion, MaxVersion)] int dbVersion)
{
// Setup
_mongo.RestoreDatabase("r1");
_languageDepot.ApplyPatch(Path.Combine(dbVersion.ToString(), "r1.patch"));
// Exercise
LfMergeHelper.Run("--project autosrtests --clone --action=Synchronize");
// Verify
Assert.That(SRState, Is.EqualTo("IDLE"));
}
}
}
| // Copyright (c) 2017 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace LfMerge.AutomatedSRTests
{
[TestFixture]
public class Tests
{
private const int MinVersion = 7000068;
private const int MaxVersion = 7000070;
private LanguageDepotHelper _languageDepot;
private MongoHelper _mongo;
private static string SRState
{
get
{
var stateFile = Path.Combine(LfMergeHelper.BaseDir, "state", "autosrtests.state");
Assert.That(File.Exists(stateFile), Is.True, $"Statefile '{stateFile}' doesn't exist");
var stateFileContent = JObject.Parse(File.ReadAllText(stateFile));
var state = stateFileContent["SRState"].ToString();
return state;
}
}
[TestFixtureSetUp]
public void FixtureSetup()
{
MongoHelper.Initialize();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
MongoHelper.Cleanup();
}
[SetUp]
public void Setup()
{
_languageDepot = new LanguageDepotHelper();
_mongo = new MongoHelper("sf_autosrtests");
}
[TearDown]
public void TearDown()
{
_mongo.Dispose();
_languageDepot.Dispose();
Settings.Cleanup();
}
[Test]
public void Clone([Range(MinVersion, MaxVersion)] int dbVersion)
{
// Setup
_mongo.RestoreDatabase("r1");
_languageDepot.ApplyPatch(Path.Combine(dbVersion.ToString(), "r1.patch"));
// Exercise
LfMergeHelper.Run("--project autosrtests --clone --action=Synchronize");
// Verify
Assert.That(SRState, Is.EqualTo("IDLE"));
}
}
}
| mit | C# |
72067187dac92d7eecb54d084ebe81cf3956db95 | add headless mode for tests | yashaka/NSelene,yashaka/NSelene,yashaka/NSelene | NSeleneTests/Integration/SharedDriver/Harness/BaseTest.cs | NSeleneTests/Integration/SharedDriver/Harness/BaseTest.cs | using NUnit.Framework;
using OpenQA.Selenium.Chrome;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using static NSelene.Selene;
namespace NSelene.Tests.Integration.SharedDriver.Harness
{
[TestFixture]
public class BaseTest
{
[OneTimeSetUp]
public void initDriver()
{
string chromeVersion = "Latest"; // e.g. "83.0.4103.39" or "Latest", see https://chromedriver.chromium.org/downloads
new DriverManager().SetUpDriver(new ChromeConfig(), version: chromeVersion);
ChromeOptions options = new ChromeOptions();
options.AddArgument("--no-sandbox");
options.AddArgument("--disable-dev-shm-usage");
options.AddArgument("--headless");
SetWebDriver(new ChromeDriver(options));
}
[OneTimeTearDown]
public void disposeDriver()
{
GetWebDriver().Quit();
}
}
}
| using NUnit.Framework;
using OpenQA.Selenium.Chrome;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using static NSelene.Selene;
namespace NSelene.Tests.Integration.SharedDriver.Harness
{
[TestFixture]
public class BaseTest
{
[OneTimeSetUp]
public void initDriver()
{
string chromeVersion = "Latest"; // e.g. "83.0.4103.39" or "Latest", see https://chromedriver.chromium.org/downloads
new DriverManager().SetUpDriver(new ChromeConfig(), version: chromeVersion);
ChromeOptions options = new ChromeOptions();
options.AddArgument("--no-sandbox");
options.AddArgument("--disable-dev-shm-usage");
SetWebDriver(new ChromeDriver(options));
}
[OneTimeTearDown]
public void disposeDriver()
{
GetWebDriver().Quit();
}
}
}
| mit | C# |
c1ebadf4f7d56483f1112fc7f81e42de2a614d39 | Access operator for array is now "item" | hahoyer/reni.cs,hahoyer/reni.cs,hahoyer/reni.cs | src/reni2/FeatureTest/Reference/ArrayReferenceByInstance.cs | src/reni2/FeatureTest/Reference/ArrayReferenceByInstance.cs | using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;
namespace Reni.FeatureTest.Reference
{
[TestFixture]
[ArrayElementType]
[TargetSet(@"
text: 'abcdefghijklmnopqrstuvwxyz';
pointer: ((text type item)*1) array_reference instance (text);
pointer item(7) dump_print;
pointer item(0) dump_print;
pointer item(11) dump_print;
pointer item(11) dump_print;
pointer item(14) dump_print;
", "hallo")]
public sealed class ArrayReferenceByInstance : CompilerTest {}
} | using System;
using System.Collections.Generic;
using System.Linq;
using hw.UnitTest;
namespace Reni.FeatureTest.Reference
{
[TestFixture]
[ArrayElementType]
[TargetSet(@"
text: 'abcdefghijklmnopqrstuvwxyz';
pointer: ((text type >>)*1) array_reference instance (text);
(pointer >> 7) dump_print;
(pointer >> 0) dump_print;
(pointer >> 11) dump_print;
(pointer >> 11) dump_print;
(pointer >> 14) dump_print;
", "hallo")]
public sealed class ArrayReferenceByInstance : CompilerTest {}
} | mit | C# |
e1ae408db9bdff035cb096ea9d9d9ed41517f5aa | Adjust some code comments | andrasm/prometheus-net | Prometheus.AspNetCore/MetricServerMiddlewareExtensions.cs | Prometheus.AspNetCore/MetricServerMiddlewareExtensions.cs | using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace Prometheus
{
public static class MetricServerMiddlewareExtensions
{
/// <summary>
/// Starts a Prometheus metrics exporter, filtering to only handle requests received on a specific port.
/// The default URL is /metrics, which is a Prometheus convention.
/// Use static methods on the <see cref="Metrics"/> class to create your metrics.
/// </summary>
public static IApplicationBuilder UseMetricServer(this IApplicationBuilder builder, int port, string? url = "/metrics", CollectorRegistry? registry = null)
{
return builder
.Map(url, b => b.MapWhen(PortMatches(), b1 => b1.InternalUseMiddleware(registry)));
Func<HttpContext, bool> PortMatches()
{
return c => c.Connection.LocalPort == port;
}
}
/// <summary>
/// Starts a Prometheus metrics exporter.
/// The default URL is /metrics, which is a Prometheus convention.
/// Use static methods on the <see cref="Metrics"/> class to create your metrics.
/// </summary>
public static IApplicationBuilder UseMetricServer(this IApplicationBuilder builder, string? url = "/metrics", CollectorRegistry? registry = null)
{
// If there is a URL to map, map it and re-enter without the URL.
if (url != null)
return builder.Map(url, b => b.InternalUseMiddleware(registry));
else
return builder.InternalUseMiddleware(registry);
}
private static IApplicationBuilder InternalUseMiddleware(this IApplicationBuilder builder, CollectorRegistry? registry = null)
{
return builder.UseMiddleware<MetricServerMiddleware>(new MetricServerMiddleware.Settings
{
Registry = registry
});
}
}
}
| using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace Prometheus
{
public static class MetricServerMiddlewareExtensions
{
/// <summary>
/// Starts a Prometheus metrics exporter on a specific port.
/// Use static methods on the <see cref="Metrics"/> class to create your metrics.
/// </summary>
public static IApplicationBuilder UseMetricServer(this IApplicationBuilder builder, int port, string? url = "/metrics", CollectorRegistry? registry = null)
{
return builder
.Map(url, b => b.MapWhen(PortMatches(), b1 => b1.InternalUseMiddleware(registry)));
Func<HttpContext, bool> PortMatches()
{
return c => c.Connection.LocalPort == port;
}
}
/// <summary>
/// Starts a Prometheus metrics exporter. The default URL is /metrics, which is a Prometheus convention.
/// Use static methods on the <see cref="Metrics"/> class to create your metrics.
/// </summary>
public static IApplicationBuilder UseMetricServer(this IApplicationBuilder builder, string? url = "/metrics", CollectorRegistry? registry = null)
{
// If there is a URL to map, map it and re-enter without the URL.
if (url != null)
return builder.Map(url, b => b.InternalUseMiddleware(registry));
else
return builder.InternalUseMiddleware(registry);
}
private static IApplicationBuilder InternalUseMiddleware(this IApplicationBuilder builder, CollectorRegistry? registry = null)
{
return builder.UseMiddleware<MetricServerMiddleware>(new MetricServerMiddleware.Settings
{
Registry = registry
});
}
}
}
| mit | C# |
c331c04f9a23b614bb9979398b2d6802bbbac3c4 | switch index to outtask | ResourceDataInc/Simpler.Data,ResourceDataInc/Simpler.Data,ResourceDataInc/Simpler.Data,gregoryjscott/Simpler,gregoryjscott/Simpler | MvcExample/Tasks/Players/Index.cs | MvcExample/Tasks/Players/Index.cs | using MvcExample.Models.Players;
using Simpler;
using Simpler.Data.Tasks;
using Simpler.Web.Models;
namespace MvcExample.Tasks.Players
{
public class Index : OutTask<IndexResult<PlayerIndex>>
{
public RunSqlAndReturn<PlayerIndexItem> FetchPlayers { get; set; }
public override void Execute()
{
FetchPlayers.ConnectionName = Config.Database;
FetchPlayers.Sql =
@"
select
PlayerId,
Player.FirstName + ' ' + Player.LastName as Name,
Team.Mascot as Team
from
Player
inner join
Team on
Player.TeamId = Team.TeamId
";
FetchPlayers.Execute();
Outputs = new IndexResult<PlayerIndex>
{
Model = new PlayerIndex
{
PlayerIndexItems = FetchPlayers.Models
}
};
}
}
} | using MvcExample.Models.Players;
using Simpler;
using Simpler.Data.Tasks;
using Simpler.Web.Models;
namespace MvcExample.Tasks.Players
{
public class Index : InOutTask<object, IndexResult<PlayerIndex>>
{
public RunSqlAndReturn<PlayerIndexItem> FetchPlayers { get; set; }
public override void Execute()
{
FetchPlayers.ConnectionName = Config.Database;
FetchPlayers.Sql =
@"
select
PlayerId,
Player.FirstName + ' ' + Player.LastName as Name,
Team.Mascot as Team
from
Player
inner join
Team on
Player.TeamId = Team.TeamId
";
FetchPlayers.Execute();
Outputs = new IndexResult<PlayerIndex>
{
Model = new PlayerIndex
{
PlayerIndexItems = FetchPlayers.Models
}
};
}
}
} | mit | C# |
2137b7ef9c79ef30ecbebf6bb118d43bbf4ce8b3 | Add copy constructor. | mcneel/RhinoCycles | LinearWorkflow.cs | LinearWorkflow.cs | /**
Copyright 2014-2015 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
using System;
using LwFlow = Rhino.Render.ChangeQueue.LinearWorkflow;
namespace RhinoCycles
{
public class LinearWorkflow
{
public bool Active { get; set; }
public float Gamma { get; set; }
public float GammaReciprocal { get; set; }
public LinearWorkflow(LwFlow lwf)
{
Active = lwf.Active;
Gamma = lwf.Gamma;
GammaReciprocal = lwf.GammaReciprocal;
}
public LinearWorkflow(LinearWorkflow old)
{
Active = old.Active;
Gamma = old.Gamma;
GammaReciprocal = old.GammaReciprocal;
}
public override bool Equals(object obj)
{
LinearWorkflow lwf = obj as LinearWorkflow;
if (lwf == null) return false;
return Active == lwf.Active && Math.Abs(Gamma-lwf.Gamma) < float.Epsilon && Math.Abs(GammaReciprocal - lwf.GammaReciprocal) < float.Epsilon;
}
}
}
| /**
Copyright 2014-2015 Robert McNeel and Associates
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**/
using System;
using LwFlow = Rhino.Render.ChangeQueue.LinearWorkflow;
namespace RhinoCycles
{
public class LinearWorkflow
{
public bool Active { get; set; }
public float Gamma { get; set; }
public float GammaReciprocal { get; set; }
public LinearWorkflow(LwFlow lwf)
{
Active = lwf.Active;
Gamma = lwf.Gamma;
GammaReciprocal = lwf.GammaReciprocal;
}
public override bool Equals(object obj)
{
LinearWorkflow lwf = obj as LinearWorkflow;
if (lwf == null) return false;
return Active == lwf.Active && Math.Abs(Gamma-lwf.Gamma) < float.Epsilon && Math.Abs(GammaReciprocal - lwf.GammaReciprocal) < float.Epsilon;
}
}
}
| apache-2.0 | C# |
f9428edead7d82b1c9bab4219e3a6c0336f4dc4b | Add missing client method to interface | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Client/ICommitmentsApiClient.cs | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Client/ICommitmentsApiClient.cs | using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
namespace SFA.DAS.CommitmentsV2.Api.Client
{
public interface ICommitmentsApiClient
{
Task<bool> HealthCheck();
Task<AccountLegalEntityResponse> GetLegalEntity(long accountLegalEntityId, CancellationToken cancellationToken = default);
// To be removed latter
Task<string> SecureCheck();
Task<string> SecureEmployerCheck();
Task<string> SecureProviderCheck();
Task<CreateCohortResponse> CreateCohort(CreateCohortRequest request, CancellationToken cancellationToken = default);
Task<UpdateDraftApprenticeshipResponse> UpdateDraftApprenticeship(long cohortId, long apprenticeshipId, UpdateDraftApprenticeshipRequest request, CancellationToken cancellationToken = default);
Task<GetCohortResponse> GetCohort(long cohortId, CancellationToken cancellationToken = default);
}
}
| using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.CommitmentsV2.Api.Types.Requests;
using SFA.DAS.CommitmentsV2.Api.Types.Responses;
namespace SFA.DAS.CommitmentsV2.Api.Client
{
public interface ICommitmentsApiClient
{
Task<bool> HealthCheck();
Task<AccountLegalEntityResponse> GetLegalEntity(long accountLegalEntityId, CancellationToken cancellationToken = default);
// To be removed latter
Task<string> SecureCheck();
Task<string> SecureEmployerCheck();
Task<string> SecureProviderCheck();
Task<CreateCohortResponse> CreateCohort(CreateCohortRequest request, CancellationToken cancellationToken = default);
Task<UpdateDraftApprenticeshipResponse> UpdateDraftApprenticeship(long cohortId, long apprenticeshipId, UpdateDraftApprenticeshipRequest request, CancellationToken cancellationToken = default);
}
}
| mit | C# |
7a082677a9f2b4dd2091c5149befb44b3b0d24dd | Add comment | diryboy/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,aelij/roslyn,MichalStrehovsky/roslyn,panopticoncentral/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,wvdd007/roslyn,reaction1989/roslyn,VSadov/roslyn,bartdesmet/roslyn,davkean/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,davkean/roslyn,ErikSchierboom/roslyn,tmat/roslyn,nguerrera/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,stephentoub/roslyn,stephentoub/roslyn,AmadeusW/roslyn,weltkante/roslyn,mavasani/roslyn,physhi/roslyn,aelij/roslyn,agocke/roslyn,tmat/roslyn,MichalStrehovsky/roslyn,AlekseyTs/roslyn,sharwell/roslyn,reaction1989/roslyn,jmarolf/roslyn,dotnet/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,abock/roslyn,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,jmarolf/roslyn,VSadov/roslyn,physhi/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,weltkante/roslyn,heejaechang/roslyn,wvdd007/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,swaroop-sridhar/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,nguerrera/roslyn,diryboy/roslyn,gafter/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,brettfo/roslyn,panopticoncentral/roslyn,sharwell/roslyn,tannergooding/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,brettfo/roslyn,eriawan/roslyn,weltkante/roslyn,heejaechang/roslyn,genlu/roslyn,jasonmalinowski/roslyn,gafter/roslyn,abock/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,aelij/roslyn,KevinRansom/roslyn,physhi/roslyn,reaction1989/roslyn,mgoertz-msft/roslyn,agocke/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,AlekseyTs/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,davkean/roslyn,panopticoncentral/roslyn,eriawan/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,agocke/roslyn,eriawan/roslyn,abock/roslyn,genlu/roslyn | src/Features/CSharp/Portable/EmbeddedLanguages/EmbeddedLanguageUtilities.cs | src/Features/CSharp/Portable/EmbeddedLanguages/EmbeddedLanguageUtilities.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.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Features.EmbeddedLanguages
{
internal static class EmbeddedLanguageUtilities
{
public static string EscapeText(string text, SyntaxToken token)
{
// This function is called when Completion needs to escape something its going to
// insert into the user's string token. This means that we only have to escape
// things that completion could insert. In this case, the only regex character
// that is relevant is the \ character, and it's only relevant if we insert into
// a normal string and not a verbatim string. There are no other regex characters
// that completion will produce that need any escaping.
Debug.Assert(token.Kind() == SyntaxKind.StringLiteralToken);
return token.IsVerbatimStringLiteral()
? text
: text.Replace(@"\", @"\\");
}
}
}
| // 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.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Features.EmbeddedLanguages
{
internal static class EmbeddedLanguageUtilities
{
public static string EscapeText(string text, SyntaxToken token)
{
Debug.Assert(token.Kind() == SyntaxKind.StringLiteralToken);
return token.IsVerbatimStringLiteral()
? text
: text.Replace("\\", "\\\\");
}
}
}
| mit | C# |
9db8a94d8218772a434e3e6a41820a39513f96cd | allow customizing DefaultNamingConventions | SathishN/JSONAPI.NET,SphtKr/JSONAPI.NET,JSONAPIdotNET/JSONAPI.NET,danshapir/JSONAPI.NET | JSONAPI/Core/DefaultNamingConventions.cs | JSONAPI/Core/DefaultNamingConventions.cs | using System;
using System.Linq;
using System.Reflection;
using JSONAPI.Extensions;
using Newtonsoft.Json;
namespace JSONAPI.Core
{
/// <summary>
/// Default implementation of INamingConventions
/// </summary>
public class DefaultNamingConventions : INamingConventions
{
private readonly IPluralizationService _pluralizationService;
/// <summary>
/// Creates a new DefaultNamingConventions
/// </summary>
/// <param name="pluralizationService"></param>
public DefaultNamingConventions(IPluralizationService pluralizationService)
{
_pluralizationService = pluralizationService;
}
/// <summary>
/// This method first checks if the property has a [JsonProperty] attribute. If so,
/// it uses the attribute's PropertyName. Otherwise, it falls back to taking the
/// property's name, and dasherizing it.
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
public virtual string GetFieldNameForProperty(PropertyInfo property)
{
var jsonPropertyAttribute = (JsonPropertyAttribute)property.GetCustomAttributes(typeof(JsonPropertyAttribute)).FirstOrDefault();
return jsonPropertyAttribute != null ? jsonPropertyAttribute.PropertyName : property.Name.Dasherize();
}
/// <summary>
/// This method first checks if the type has a [JsonObject] attribute. If so,
/// it uses the attribute's Title. Otherwise it falls back to pluralizing the
/// type's name using the given <see cref="IPluralizationService" /> and then
/// dasherizing that value.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public virtual string GetResourceTypeNameForType(Type type)
{
var jsonObjectAttribute = type.GetCustomAttributes().OfType<JsonObjectAttribute>().FirstOrDefault();
string title = null;
if (jsonObjectAttribute != null)
{
title = jsonObjectAttribute.Title;
}
if (string.IsNullOrEmpty(title))
{
title = GetNameForType(type);
}
return _pluralizationService.Pluralize(title).Dasherize();
}
/// <summary>
/// Gets the name for a CLR type.
/// </summary>
protected virtual string GetNameForType(Type type)
{
return type.Name;
}
}
} | using System;
using System.Linq;
using System.Reflection;
using JSONAPI.Extensions;
using Newtonsoft.Json;
namespace JSONAPI.Core
{
/// <summary>
/// Default implementation of INamingConventions
/// </summary>
public class DefaultNamingConventions : INamingConventions
{
private readonly IPluralizationService _pluralizationService;
/// <summary>
/// Creates a new DefaultNamingConventions
/// </summary>
/// <param name="pluralizationService"></param>
public DefaultNamingConventions(IPluralizationService pluralizationService)
{
_pluralizationService = pluralizationService;
}
/// <summary>
/// This method first checks if the property has a [JsonProperty] attribute. If so,
/// it uses the attribute's PropertyName. Otherwise, it falls back to taking the
/// property's name, and dasherizing it.
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
public string GetFieldNameForProperty(PropertyInfo property)
{
var jsonPropertyAttribute = (JsonPropertyAttribute)property.GetCustomAttributes(typeof(JsonPropertyAttribute)).FirstOrDefault();
return jsonPropertyAttribute != null ? jsonPropertyAttribute.PropertyName : property.Name.Dasherize();
}
/// <summary>
/// This method first checks if the type has a [JsonObject] attribute. If so,
/// it uses the attribute's Title. Otherwise it falls back to pluralizing the
/// type's name using the given <see cref="IPluralizationService" /> and then
/// dasherizing that value.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public string GetResourceTypeNameForType(Type type)
{
var attrs = type.CustomAttributes.Where(x => x.AttributeType == typeof(JsonObjectAttribute)).ToList();
string title = type.Name;
if (attrs.Any())
{
var titles = attrs.First().NamedArguments.Where(arg => arg.MemberName == "Title")
.Select(arg => arg.TypedValue.Value.ToString()).ToList();
if (titles.Any()) title = titles.First();
}
return _pluralizationService.Pluralize(title).Dasherize();
}
}
} | mit | C# |
5a5cceb2ee010ca71727dd8350dcd5ce2e6e6857 | refactor tests | OlegKleyman/Omego.Extensions | tests/unit/Omego.Extensions.Tests.Unit/Poco/GenericEqualityComparerTests.cs | tests/unit/Omego.Extensions.Tests.Unit/Poco/GenericEqualityComparerTests.cs | using System;
namespace Omego.Extensions.Tests.Unit.Poco
{
using FluentAssertions;
using Omego.Extensions.Poco;
using Xunit;
[CLSCompliant(false)]
public class GenericEqualityComparerTests
{
[Theory]
[InlineData(1)]
[InlineData(default(int))]
public void GetHashCodeShouldReturnHashCodeFromLambda(int hashCode)
=>
GetGenericEqualityComparer<object>(o => hashCode)
.GetHashCode(default(object))
.ShouldBeEquivalentTo(hashCode);
[Theory]
[InlineData(1)]
[InlineData(default(int))]
public void EqualsShouldReturnWhetherObjectsAreEquivalentFromLambda(bool areEqual)
=>
GetGenericEqualityComparer<object>((o, o1) => areEqual)
.Equals(default(object), default(object))
.ShouldBeEquivalentTo(areEqual);
private GenericEqualityComparer<TSource> GetGenericEqualityComparer<TSource>(
Func<TSource, TSource, bool> areEqual,
Func<TSource, int> hashCode) => new GenericEqualityComparer<TSource>(areEqual, hashCode);
private GenericEqualityComparer<TSource> GetGenericEqualityComparer<TSource>(
Func<TSource, TSource, bool> areEqual) => GetGenericEqualityComparer(areEqual, source => default(int));
private GenericEqualityComparer<TSource> GetGenericEqualityComparer<TSource>(Func<TSource, int> hashCode)
=> GetGenericEqualityComparer((source, source1) => default(bool), hashCode);
}
}
| using System;
namespace Omego.Extensions.Tests.Unit.Poco
{
using FluentAssertions;
using Omego.Extensions.Poco;
using Xunit;
[CLSCompliant(false)]
public class GenericEqualityComparerTests
{
[Theory]
[InlineData(1)]
[InlineData(default(int))]
public void GetHashCodeShouldReturnHashCodeFromLambda(int hashCode)
{
Func<object, int> hashCodeGenerator = o => hashCode;
GetGenericEqualityComparer(hashCodeGenerator).GetHashCode(default(object)).ShouldBeEquivalentTo(hashCode);
}
[Theory]
[InlineData(1)]
[InlineData(default(int))]
public void EqualsShouldReturnWhetherObjectsAreEquivalentFromLambda(bool areEqual)
{
Func<object, object, bool> areEqualGenerator = (o, o1) => areEqual;
GetGenericEqualityComparer(areEqualGenerator)
.Equals(default(object), default(object))
.ShouldBeEquivalentTo(areEqual);
}
private GenericEqualityComparer<TSource> GetGenericEqualityComparer<TSource>(
Func<TSource, TSource, bool> areEqual,
Func<TSource, int> hashCode) => new GenericEqualityComparer<TSource>(areEqual, hashCode);
private GenericEqualityComparer<TSource> GetGenericEqualityComparer<TSource>(
Func<TSource, TSource, bool> areEqual) => GetGenericEqualityComparer(areEqual, source => default(int));
private GenericEqualityComparer<TSource> GetGenericEqualityComparer<TSource>(
Func<TSource, int> hashCode) => GetGenericEqualityComparer((source, source1) => default(bool), hashCode);
}
}
| unlicense | C# |
cd7515977aae568eee28baf6aef514d494acfb09 | Update HttpPoller.cs | keith-hall/Extensions,keith-hall/Extensions | src/HttpPoller.cs | src/HttpPoller.cs | using System;
using System.Net;
using System.Reactive.Linq;
public static class HttpPoller
{
public struct ResponseDetails
{
public WebHeaderCollection Headers;
public string Text;
}
public static IObservable<ResponseDetails> PollURL(string url, TimeSpan frequency, Func<WebClient> createWebClient = null)
{
createWebClient = createWebClient ?? (() => new WebClient());
Func<ResponseDetails> download = () =>
{
var wc = createWebClient();
return new ResponseDetails { Text = wc.DownloadString(url), Headers = wc.ResponseHeaders };
};
return Observable.Interval(frequency)
.Select(l => download())
.StartWith(download())
.DistinctUntilChanged(wc => wc.Text).Publish().RefCount();
}
}
| public static class HttpPoller {
public struct ResponseDetails {
public WebHeaderCollection Headers;
public string Text;
}
public static IObservable<ResponseDetails> PollURL (string url, TimeSpan frequency, Func<WebClient> createWebClient = null) {
createWebClient = createWebClient ?? (() => new WebClient());
Func<ResponseDetails> download = () => {
var wc = createWebClient();
return new ResponseDetails { Text = wc.DownloadString(url), Headers = wc.ResponseHeaders };
};
return Observable.Interval(frequency)
.Select(l => download())
.StartWith(download())
.DistinctUntilChanged(wc => wc.Text).Publish().RefCount();
}
}
| apache-2.0 | C# |
20fddfa83bc4707b13030abf4fbfdb3b31cc42c9 | Update Mod.cs | maritaria/terratech-mod,Exund/nuterra,Nuterra/Nuterra | src/Sylver/Mod.cs | src/Sylver/Mod.cs | using System;
using UnityEngine;
namespace Sylver
{
public static class Mod
{
public static void Init()
{
Console.WriteLine("Sylver.Mod.Init()");
Mod.BehaviorHolder = new GameObject();
Mod.BehaviorHolder.AddComponent<SylverMod>();
Mod.BehaviorHolder.AddComponent<GUIRenderer>();
UnityEngine.Object.DontDestroyOnLoad(Mod.BehaviorHolder);
}
static Mod()
{
}
public static GameObject BehaviorHolder;
}
}
| using System;
using UnityEngine;
namespace Sylver
{
public static class Mod
{
public static void Init()
{
Console.WriteLine("Sylver.Mod.Init()");
Mod.BehaviorHolder = new GameObject();
Mod.BehaviorHolder.AddComponent<SylverMod>();
UnityEngine.Object.DontDestroyOnLoad(Mod.BehaviorHolder);
}
static Mod()
{
}
public static GameObject BehaviorHolder;
}
}
| mit | C# |
5d0c5a7c5a6a30a02463939856c9e78ae4d86a70 | update version number to 1.8 | estorski/langlay | Langlay.Common/AppSpecific.cs | Langlay.Common/AppSpecific.cs | namespace Product.Common
{
public static class AppSpecific
{
public const string MainAppTitle = "Langlay";
public const string MainAppProcessName = "Langlay";
public const string MainAppProcessNameDebug = MainAppProcessName + ".vshost";
public const string MainAppFilename = "Langlay.exe";
public const string MainAppConfigFilename = MainAppFilename + ".config";
public const string SettingsAppFilename = "Langlay.SettingsUi.exe";
public const string AppVersion = "1.8";
}
}
| namespace Product.Common
{
public static class AppSpecific
{
public const string MainAppTitle = "Langlay";
public const string MainAppProcessName = "Langlay";
public const string MainAppProcessNameDebug = MainAppProcessName + ".vshost";
public const string MainAppFilename = "Langlay.exe";
public const string MainAppConfigFilename = MainAppFilename + ".config";
public const string SettingsAppFilename = "Langlay.SettingsUi.exe";
public const string AppVersion = "1.7";
}
}
| mit | C# |
7c2dc68e13178647e01919d01c4b7d2c1bc82003 | Update RectangleMarker.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Modules/Renderer/SkiaSharp/Nodes/Markers/RectangleMarker.cs | src/Core2D/Modules/Renderer/SkiaSharp/Nodes/Markers/RectangleMarker.cs | #nullable enable
using SkiaSharp;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes.Markers;
internal class RectangleMarker : MarkerBase
{
public SKRect Rect { get; set; }
public override void Draw(object? dc)
{
if (dc is not SKCanvas canvas)
{
return;
}
if (ShapeViewModel is null)
{
return;
}
var count = canvas.Save();
canvas.SetMatrix(MatrixHelper.Multiply(Rotation, canvas.TotalMatrix));
if (ShapeViewModel.IsFilled)
{
canvas.DrawRect(Rect, Brush);
}
if (ShapeViewModel.IsStroked)
{
canvas.DrawRect(Rect, Pen);
}
canvas.RestoreToCount(count);
}
}
| #nullable enable
using SkiaSharp;
namespace Core2D.Modules.Renderer.SkiaSharp.Nodes.Markers;
internal class RectangleMarker : MarkerBase
{
public SKRect Rect { get; set; }
public override void Draw(object? dc)
{
if (dc is not SKCanvas canvas)
{
return;
}
var count = canvas.Save();
canvas.SetMatrix(MatrixHelper.Multiply(Rotation, canvas.TotalMatrix));
if (ShapeViewModel.IsFilled)
{
canvas.DrawRect(Rect, Brush);
}
if (ShapeViewModel.IsStroked)
{
canvas.DrawRect(Rect, Pen);
}
canvas.RestoreToCount(count);
}
}
| mit | C# |
ded1e579ac6ccb2c1fc849dc3587bc06bb2cdbaa | Fix bug in log globalmethod (#6806) | petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,petedavis/Orchard2 | src/OrchardCore.Modules/OrchardCore.Scripting/Providers/LogProvider.cs | src/OrchardCore.Modules/OrchardCore.Scripting/Providers/LogProvider.cs | using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace OrchardCore.Scripting.Providers
{
public class LogProvider : IGlobalMethodProvider
{
private readonly GlobalMethod _log;
public LogProvider(ILogger<LogProvider> logger)
{
_log = new GlobalMethod
{
Name = "log",
Method = serviceProvider => (Action<string, string, object>)((level, text, param) =>
{
try
{
if (!Enum.TryParse<LogLevel>(level, true, out var logLevel))
{
logLevel = LogLevel.Information;
}
if (param == null)
{
logger.Log(logLevel, text);
}
else
{
object[] args;
if (!(param is Array))
{
args = new[] { param };
}
else
{
args = (object[])param;
}
logger.Log(logLevel, text, args);
}
}
catch (Exception ex)
{
logger.Log(LogLevel.Error, ex, "Error logging text template {text} with param {param} from Scripting Engine.", text, param);
}
})
};
}
public IEnumerable<GlobalMethod> GetMethods()
{
return new[] { _log };
}
}
}
| using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace OrchardCore.Scripting.Providers
{
public class LogProvider : IGlobalMethodProvider
{
private readonly GlobalMethod _log;
public LogProvider(ILogger<LogProvider> logger)
{
_log = new GlobalMethod
{
Name = "log",
Method = serviceProvider => (Action<string, string, object>)((level, text, param) =>
{
if (!Enum.TryParse<LogLevel>(level, true, out var logLevel))
{
logLevel = LogLevel.Information;
}
object[] args;
if (!(param is Array))
{
args = new[] { param };
}
else
{
args = (object[])param;
}
logger.Log(logLevel, text, args);
})
};
}
public IEnumerable<GlobalMethod> GetMethods()
{
return new[] { _log };
}
}
}
| bsd-3-clause | C# |
576104044ec8d8cc361481881975b5a4d0d200d8 | 修改版本号。 | RabbitTeam/RabbitHub | Components/Rabbit.Components.Data/Properties/AssemblyInfo.cs | Components/Rabbit.Components.Data/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Rabbit.Components.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rabbit.Components.Data")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("6f57adcd-3141-41db-8f11-2aec7b4a7fdf")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Rabbit.Components.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rabbit.Components.Data")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("6f57adcd-3141-41db-8f11-2aec7b4a7fdf")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.2.4")]
[assembly: AssemblyFileVersion("1.2.2.4")] | apache-2.0 | C# |
bfb9c8fbacd37108790e15353be05c48fd635abf | read kek | XomakNet/tasks | Eval/EvalProgram.cs | Eval/EvalProgram.cs | using System;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace EvalTask
{
class EvalProgram
{
static void Main(string[] args)
{
string input = Console.In.ReadLine()?.Replace(',', '.');
string json = Console.In.ReadToEnd();
string output;
try
{
output = DoThings(json, input);
}
catch (Exception e)
{
output = "error";
}
Console.WriteLine(output);
}
private static string DoThings(string json, string input)
{
var replaced = JsonReplacer.Replace(json, input);
return new Calculator(replaced).Calc().ToString(CultureInfo.InvariantCulture);
}
[TestFixture]
public class EvalProgram_Should
{
[Test]
public void WorkOnNullJson()
{
string json = null;
string expr = "1+2-2+1";
Assert.AreEqual("2", DoThings(json, expr));
}
[Test]
public void WorkWithEmptyJson()
{
string json = "{}";
string expr = "1+2-2+1";
Assert.AreEqual("2", DoThings(json, expr));
}
[Test]
public void WorkWithJson()
{
string json = "{x:1,xx:2,yy:3,y:5}";
string expr = "x+xx+yy+y";
Assert.AreEqual("11", DoThings(json, expr));
}
}
}
} | using System;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace EvalTask
{
class EvalProgram
{
static void Main(string[] args)
{
string input = Console.In.ReadLine()?.Replace(',', '.');
string json = "";//Console.In.ReadToEnd();
string output;
try
{
output = DoThings(json, input);
}
catch (Exception e)
{
output = "error";
}
Console.WriteLine(output);
}
private static string DoThings(string json, string input)
{
var replaced = JsonReplacer.Replace(json, input);
return new Calculator(replaced).Calc().ToString(CultureInfo.InvariantCulture);
}
[TestFixture]
public class EvalProgram_Should
{
[Test]
public void WorkOnNullJson()
{
string json = null;
string expr = "1+2-2+1";
Assert.AreEqual("2", DoThings(json, expr));
}
[Test]
public void WorkWithEmptyJson()
{
string json = "{}";
string expr = "1+2-2+1";
Assert.AreEqual("2", DoThings(json, expr));
}
[Test]
public void WorkWithJson()
{
string json = "{x:1,xx:2,yy:3,y:5}";
string expr = "x+xx+yy+y";
Assert.AreEqual("11", DoThings(json, expr));
}
}
}
} | mit | C# |
b99060d693935653075ce4ea0a234927ea01ac97 | Update BaseClassTests.cs | mcintyre321/OneOf | OneOf.Tests/BaseClassTests.cs | OneOf.Tests/BaseClassTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace OneOf.Tests
{
public abstract class Response : OneOfBase<
Response.MethodNotAllowed,
Response.InvokeSuccessResponse
>
{
public class MethodNotAllowed : Response
{
}
public class InvokeSuccessResponse : Response
{
}
}
public class BaseClassTests
{
[Test]
public void CanMatchOnBase()
{
Response x = new Response.MethodNotAllowed();
Assert.AreEqual(true, x.Match(
methodNotAllowed => true,
invokeSuccessResponse => false));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace OneOf.Tests
{
public abstract class Response : OneOfBase<
Response.MethodNotAllowed,
Response.InvokeSuccessResponse
>
{
public class MethodNotAllowed : Response
{
}
public class InvokeSuccessResponse : Response
{
}
}
public class BaseClassTests
{
[Test]
public void CanMatchOnBase()
{
Response x = new Response.MethodNotAllowed();
Assert.AreEqual(true, x.Match(
allowed => true,
response => false));
}
}
}
| mit | C# |
f2a8b3a61edbdaca5401d177e1d3e7b8fa54cadc | write scenario output if any step in the scenario fails (was only asserts) | mvbalaw/FluentAssert | src/FluentAssert/TestRunner.cs | src/FluentAssert/TestRunner.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace FluentAssert
{
internal class TestStep
{
public Action Action;
public string Description;
public string FailureSuffix;
public string SuccessSuffix;
}
[DebuggerNonUserCode]
[DebuggerStepThrough]
internal static class TestRunner
{
private static void DoStep(StringBuilder scenarioDescription, TestStep testStep)
{
scenarioDescription.Append(testStep.Description);
try
{
testStep.Action();
scenarioDescription.AppendLine(testStep.SuccessSuffix);
}
catch (Exception)
{
scenarioDescription.AppendLine(testStep.FailureSuffix);
Console.Error.WriteLine(scenarioDescription.ToString());
throw;
}
}
public static void Verify(string actionDescription,
IEnumerable<IParameterActionWrapper> initializationsForActionParameters,
Action action,
IEnumerable<IAssertionActionWrapper> assertions)
{
var steps = initializationsForActionParameters
.Select((arrange,i) => new TestStep
{
Description = string.Format("STEP {0}: {1}", (1+i), arrange.Description),
Action = arrange.Setup,
FailureSuffix = " - FAILED",
SuccessSuffix = ""
})
.ToList();
steps.Add(new TestStep
{
Description = "WHEN " + actionDescription,
Action = action,
FailureSuffix = " - FAILED",
SuccessSuffix = ""
});
steps.AddRange(
assertions.Select(assertion => new TestStep
{
Description = "SHOULD " + assertion.Description,
Action = assertion.Verify,
FailureSuffix = " - FAILED",
SuccessSuffix = " - PASSED"
}));
var scenarioDescription = new StringBuilder();
steps.ForEach(x => DoStep(scenarioDescription, x));
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace FluentAssert
{
[DebuggerNonUserCode]
[DebuggerStepThrough]
internal static class TestRunner
{
public static void Verify(string actionDescription,
IEnumerable<IParameterActionWrapper> initializationsForActionParameters,
Action action,
IEnumerable<IAssertionActionWrapper> assertions)
{
var scenarioDescription = new StringBuilder();
foreach (var arrange in initializationsForActionParameters)
{
scenarioDescription.AppendLine("WITH " + arrange.Description);
arrange.Setup();
}
scenarioDescription.AppendLine("WHEN " + actionDescription);
action();
foreach (var assertion in assertions)
{
scenarioDescription.Append("SHOULD " + assertion.Description);
try
{
assertion.Verify();
scenarioDescription.AppendLine(" - PASSED");
}
catch (Exception)
{
scenarioDescription.AppendLine(" - FAILED");
Console.Error.WriteLine(scenarioDescription.ToString());
throw;
}
}
}
}
} | mit | C# |
587658b31fc7c2a8cb9a0c8b2b5a3849919caa83 | Fix namespace. | yonglehou/msgpack-rpc-cli,yfakariya/msgpack-rpc-cli | test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Protocols/_SetUpFixture.cs | test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Protocols/_SetUpFixture.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Diagnostics.Contracts;
using NUnit.Framework;
namespace MsgPack.Rpc.Server.Protocols
{
[CLSCompliant( false )]
[SetUpFixture]
public sealed class _SetUpFixture
{
[SetUp]
public void SetupCurrentNamespaceTests()
{
Contract.ContractFailed += ( sender, e ) => e.SetUnwind();
}
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Diagnostics.Contracts;
using NUnit.Framework;
namespace MsgPack.Rpc.Server.Transport
{
[CLSCompliant( false )]
[SetUpFixture]
public sealed class _SetUpFixture
{
[SetUp]
public void SetupCurrentNamespaceTests()
{
Contract.ContractFailed += ( sender, e ) => e.SetUnwind();
}
}
}
| apache-2.0 | C# |
67997b9ed910506abdd0ecc516d24a59c8ce7d2a | Clean up | Weingartner/SolidworksAddinFramework | SolidworksAddinFramework/OpenGl/Animation/LinearAnimation.cs | SolidworksAddinFramework/OpenGl/Animation/LinearAnimation.cs | using System;
using System.Diagnostics;
using System.Numerics;
using ReactiveUI;
namespace SolidworksAddinFramework.OpenGl.Animation
{
public class LinearAnimation<T> : ReactiveObject, IAnimationSection
where T : IInterpolatable<T>
{
public T From { get; }
public T To { get; }
public TimeSpan Duration { get; }
public LinearAnimation(TimeSpan duration, T @from, T to)
{
Duration = duration;
From = @from;
To = to;
}
public Matrix4x4 Transform( TimeSpan deltaTime)
{
var beta = deltaTime.TotalMilliseconds/Duration.TotalMilliseconds;
return BlendTransform(beta);
}
public Matrix4x4 BlendTransform(double beta)
{
Debug.Assert(beta>=0 && beta<=1);
return From.Interpolate(To, beta).Transform();
}
}
} | using System;
using System.Diagnostics;
using System.Numerics;
using ReactiveUI;
using SolidWorks.Interop.sldworks;
namespace SolidworksAddinFramework.OpenGl.Animation
{
public class LinearAnimation<T> : ReactiveObject, IAnimationSection
where T : IInterpolatable<T>
{
private readonly IMathUtility _Math;
public T From { get; }
public T To { get; }
public TimeSpan Duration { get; }
public LinearAnimation
(TimeSpan duration, T @from, T to, IMathUtility math)
{
Duration = duration;
From = @from;
To = to;
_Math = math;
}
public Matrix4x4 Transform( TimeSpan deltaTime)
{
var beta = deltaTime.TotalMilliseconds/Duration.TotalMilliseconds;
return BlendTransform(beta);
}
public Matrix4x4 BlendTransform(double beta)
{
Debug.Assert(beta>=0 && beta<=1);
return From.Interpolate(To, beta).Transform();
}
}
} | mit | C# |
01a180abee6c22423fd5baf6d8419ec68261f495 | Update ParameterRebinder.cs | Ar3sDevelopment/Caelan.DynamicLinq | Caelan.DynamicLinq/Classes/ParameterRebinder.cs | Caelan.DynamicLinq/Classes/ParameterRebinder.cs | using System.Linq.Expressions;
using System.Collections.Generic;
namespace Caelan.DynamicLinq.Classes
{
public class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> _map;
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
_map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (_map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
| using System.Linq.Expressions;
using System.Collections.Generic;
namespace Caelan.DynamicLinq.Classes
{
public class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> _map;
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
_map = _map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (_map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
| apache-2.0 | C# |
979d8c928fd7235c8331b699c08c3dc4c17db0c1 | Add client function for creating dumps | tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server | src/Tgstation.Server.Client/Components/DreamDaemonClient.cs | src/Tgstation.Server.Client/Components/DreamDaemonClient.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Api;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Client.Components
{
/// <inheritdoc />
sealed class DreamDaemonClient : IDreamDaemonClient
{
/// <summary>
/// The <see cref="IApiClient"/> for the <see cref="DreamDaemonClient"/>
/// </summary>
readonly IApiClient apiClient;
/// <summary>
/// The <see cref="Instance"/> for the <see cref="DreamDaemonClient"/>
/// </summary>
readonly Instance instance;
/// <summary>
/// Construct a <see cref="DreamDaemonClient"/>
/// </summary>
/// <param name="apiClient">The value of <see cref="apiClient"/></param>
/// <param name="instance">The value of <see cref="instance"/></param>
public DreamDaemonClient(IApiClient apiClient, Instance instance)
{
this.apiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient));
this.instance = instance ?? throw new ArgumentNullException(nameof(instance));
}
/// <inheritdoc />
public Task Shutdown(CancellationToken cancellationToken) => apiClient.Delete(Routes.DreamDaemon, instance.Id, cancellationToken);
/// <inheritdoc />
public Task<Job> Start(CancellationToken cancellationToken) => apiClient.Create<Job>(Routes.DreamDaemon, instance.Id, cancellationToken);
/// <inheritdoc />
public Task<Job> Restart(CancellationToken cancellationToken) => apiClient.Patch<Job>(Routes.DreamDaemon, instance.Id, cancellationToken);
/// <inheritdoc />
public Task<DreamDaemon> Read(CancellationToken cancellationToken) => apiClient.Read<DreamDaemon>(Routes.DreamDaemon, instance.Id, cancellationToken);
/// <inheritdoc />
public Task<DreamDaemon> Update(DreamDaemon dreamDaemon, CancellationToken cancellationToken) => apiClient.Update<DreamDaemon, DreamDaemon>(Routes.DreamDaemon, dreamDaemon ?? throw new ArgumentNullException(nameof(dreamDaemon)), instance.Id, cancellationToken);
/// <inheritdoc />
public Task<Job> CreateDump(CancellationToken cancellationToken) => apiClient.Patch<Job>(Routes.Diagnostics, instance.Id, cancellationToken);
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Api;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Client.Components
{
/// <inheritdoc />
sealed class DreamDaemonClient : IDreamDaemonClient
{
/// <summary>
/// The <see cref="IApiClient"/> for the <see cref="DreamDaemonClient"/>
/// </summary>
readonly IApiClient apiClient;
/// <summary>
/// The <see cref="Instance"/> for the <see cref="DreamDaemonClient"/>
/// </summary>
readonly Instance instance;
/// <summary>
/// Construct a <see cref="DreamDaemonClient"/>
/// </summary>
/// <param name="apiClient">The value of <see cref="apiClient"/></param>
/// <param name="instance">The value of <see cref="instance"/></param>
public DreamDaemonClient(IApiClient apiClient, Instance instance)
{
this.apiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient));
this.instance = instance ?? throw new ArgumentNullException(nameof(instance));
}
/// <inheritdoc />
public Task Shutdown(CancellationToken cancellationToken) => apiClient.Delete(Routes.DreamDaemon, instance.Id, cancellationToken);
/// <inheritdoc />
public Task<Job> Start(CancellationToken cancellationToken) => apiClient.Create<Job>(Routes.DreamDaemon, instance.Id, cancellationToken);
/// <inheritdoc />
public Task<Job> Restart(CancellationToken cancellationToken) => apiClient.Patch<Job>(Routes.DreamDaemon, instance.Id, cancellationToken);
/// <inheritdoc />
public Task<DreamDaemon> Read(CancellationToken cancellationToken) => apiClient.Read<DreamDaemon>(Routes.DreamDaemon, instance.Id, cancellationToken);
/// <inheritdoc />
public Task<DreamDaemon> Update(DreamDaemon dreamDaemon, CancellationToken cancellationToken) => apiClient.Update<DreamDaemon, DreamDaemon>(Routes.DreamDaemon, dreamDaemon ?? throw new ArgumentNullException(nameof(dreamDaemon)), instance.Id, cancellationToken);
}
} | agpl-3.0 | C# |
fb541104923a432fa6970a506cff1ec647363fe1 | Add implementation to produce list of all users. | tvanfosson/dapper-integration-testing | DapperTesting/Core/Data/DapperUserRepository.cs | DapperTesting/Core/Data/DapperUserRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using DapperTesting.Core.Model;
namespace DapperTesting.Core.Data
{
public class DapperUserRepository : DapperRepositoryBase, IUserRepository
{
public DapperUserRepository(IConnectionFactory connectionFactory, string connectionStringName)
: base(connectionFactory, connectionStringName)
{
}
public void Create(User user)
{
var date = DateTime.Now;
const string sql = "INSERT INTO [Users] ([DisplayName], [Email], [CreatedDate], [Active]) OUTPUT inserted.[Id] VALUES (@displayName, @email, @createdDate, @active)";
var id = Fetch(c => c.Query<int>(sql, new
{
displayName = user.DisplayName,
email = user.Email,
createdDate = date,
active = user.Active
}).Single());
user.Id = id;
user.CreatedDate = date;
}
public void Delete(int id)
{
const string sql = "DELETE FROM [Users] WHERE [Id] = @userId";
Execute(c => c.Execute(sql, new { userId = id }));
}
public User Get(int id)
{
const string sql = "SELECT * FROM [Users] WHERE [Id] = @userId";
var user = Fetch(c => c.Query<User>(sql, new { userId = id }).SingleOrDefault());
return user;
}
public User Get(string email)
{
throw new NotImplementedException();
}
public List<User> GetAll()
{
const string sql = "SELECT * FROM [Users]";
var users = Fetch(c => c.Query<User>(sql));
return users.ToList();
}
public void Update(User user)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using DapperTesting.Core.Model;
namespace DapperTesting.Core.Data
{
public class DapperUserRepository : DapperRepositoryBase, IUserRepository
{
public DapperUserRepository(IConnectionFactory connectionFactory, string connectionStringName)
: base(connectionFactory, connectionStringName)
{
}
public void Create(User user)
{
var date = DateTime.Now;
const string sql = "INSERT INTO [Users] ([DisplayName], [Email], [CreatedDate], [Active]) OUTPUT inserted.[Id] VALUES (@displayName, @email, @createdDate, @active)";
var id = Fetch(c => c.Query<int>(sql, new
{
displayName = user.DisplayName,
email = user.Email,
createdDate = date,
active = user.Active
}).Single());
user.Id = id;
user.CreatedDate = date;
}
public void Delete(int id)
{
const string sql = "DELETE FROM [Users] WHERE [Id] = @userId";
Execute(c => c.Execute(sql, new { userId = id }));
}
public User Get(int id)
{
const string sql = "SELECT * FROM [Users] WHERE [Id] = @userId";
var user = Fetch(c => c.Query<User>(sql, new { userId = id }).SingleOrDefault());
return user;
}
public User Get(string email)
{
throw new NotImplementedException();
}
public List<User> GetAll()
{
throw new NotImplementedException();
}
public void Update(User user)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
9e225cbeda93a5ebd03e9576c75eee1c896d9164 | add err tracking | Just1n/Jog | Jog/Bootstrapper.cs | Jog/Bootstrapper.cs | using Nancy.Bootstrapper;
using Nancy.Session;
using Nancy.TinyIoc;
namespace Jog
{
using Nancy;
public class Bootstrapper : DefaultNancyBootstrapper
{
// The bootstrapper enables you to reconfigure the composition of the framework,
// by overriding the various methods and properties.
// For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
base.ApplicationStartup(container, pipelines);
StaticConfiguration.DisableErrorTraces = false;
}
}
} | using Nancy.Bootstrapper;
using Nancy.Session;
using Nancy.TinyIoc;
namespace Jog
{
using Nancy;
public class Bootstrapper : DefaultNancyBootstrapper
{
// The bootstrapper enables you to reconfigure the composition of the framework,
// by overriding the various methods and properties.
// For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper
}
} | apache-2.0 | C# |
48d3fccd770c28f212af58e1dd3c9cca2fe0e04b | Set pause to 2 seconds so we can watch the mock run | ProjectExtensions/ProjectExtensions.Azure.ServiceBus | src/Tests/ProjectExtensions.Azure.ServiceBus.Tests.Unit/SampleTest.cs | src/Tests/ProjectExtensions.Azure.ServiceBus.Tests.Unit/SampleTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Threading;
namespace ProjectExtensions.Azure.ServiceBus.Tests.Unit {
[TestFixture]
public class SampleTest {
[Test]
public void Test() {
Thread.Sleep(2000);
Assert.IsTrue(true);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Threading;
namespace ProjectExtensions.Azure.ServiceBus.Tests.Unit {
[TestFixture]
public class SampleTest {
[Test]
public void Test() {
Thread.Sleep(30000);
Assert.IsTrue(true);
}
}
}
| bsd-3-clause | C# |
548f197c03fe4b5004c368760d3009685d8d5911 | add conversational style | timheuer/alexa-skills-dotnet,stoiveyp/alexa-skills-dotnet | Alexa.NET/Response/Ssml/DomainName.cs | Alexa.NET/Response/Ssml/DomainName.cs | namespace Alexa.NET.Response.Ssml
{
public static class DomainName
{
public const string News = "news";
public const string Music = "music";
public const string Conversational = "conversational";
}
} | namespace Alexa.NET.Response.Ssml
{
public static class DomainName
{
public const string News = "news";
public const string Music = "music";
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.