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 |
|---|---|---|---|---|---|---|---|---|
b6ceaa461346fb5c8830709c8e8afe092cbe00b0 | Disable alternative rules by default | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers/AnalyzerConstants.cs | StyleCop.Analyzers/StyleCop.Analyzers/AnalyzerConstants.cs | namespace StyleCop.Analyzers
{
using Microsoft.CodeAnalysis;
internal static class AnalyzerConstants
{
static AnalyzerConstants()
{
#if DEBUG
// In DEBUG builds, the tests are enabled to simplify development and testing.
DisabledNoTests = true;
#else
DisabledNoTests = false;
#endif
}
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to disable a diagnostic which is currently untested.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to disable a diagnostic which is currently untested.
/// </value>
internal static bool DisabledNoTests { get; }
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic is disabled by default because it is an alternative to a reference StyleCop
/// rule.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic is disabled by default because it is an alternative to a reference StyleCop
/// rule.
/// </value>
internal static bool DisabledAlternative => false;
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic should be enabled by default.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic should be enabled by default.
/// </value>
internal static bool EnabledByDefault => true;
}
}
| namespace StyleCop.Analyzers
{
using Microsoft.CodeAnalysis;
internal static class AnalyzerConstants
{
static AnalyzerConstants()
{
#if DEBUG
// In DEBUG builds, the tests are enabled to simplify development and testing.
DisabledNoTests = true;
#else
DisabledNoTests = false;
#endif
}
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to disable a diagnostic which is currently untested.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to disable a diagnostic which is currently untested.
/// </value>
internal static bool DisabledNoTests { get; }
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic is disabled by default because it is an alternative to a reference StyleCop
/// rule.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic is disabled by default because it is an alternative to a reference StyleCop
/// rule.
/// </value>
internal static bool DisabledAlternative => true;
/// <summary>
/// Gets a reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic should be enabled by default.
/// </summary>
/// <value>
/// A reference value which can be passed to
/// <see cref="DiagnosticDescriptor(string, string, string, string, DiagnosticSeverity, bool, string, string, string[])"/>
/// to indicate that the diagnostic should be enabled by default.
/// </value>
internal static bool EnabledByDefault => true;
}
}
| mit | C# |
5c3549521c9fc363073397cef1208f3ca02f9a2f | Fix typo in MenuButton | NitorInc/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare | Assets/Scripts/Menu/MenuButton.cs | Assets/Scripts/Menu/MenuButton.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MenuButton : MonoBehaviour
{
#pragma warning disable 0649 //Serialized Fields
[SerializeField]
private Button button;
[SerializeField]
private Animator buttonAnimator;
[SerializeField]
private Collider2D backupCollider;
[SerializeField]
private bool playPressAnimation = true;
[SerializeField]
private bool checkMouseOverCollider = true;
[SerializeField]
private KeyCode pressKey = KeyCode.None;
#pragma warning restore 0649
private bool _forceDisable;
public bool forceDisable
{
get { return _forceDisable; }
set { _forceDisable = value; }
}
private int clickBuffer; //Waits one frame to enable button to prevent carry-over clicks from last scene
void Start()
{
bufferClick();
}
private void OnEnable()
{
bufferClick();
}
void bufferClick()
{
button.interactable = false;
clickBuffer = 2;
}
void enableButton()
{
button.interactable = true;
}
void LateUpdate()
{
if (clickBuffer > 0)
{
clickBuffer--;
if (clickBuffer == 0)
button.interactable = true;
return;
}
bool shouldEnable = shouldButtonBeEnabled();
if (button.interactable != shouldEnable)
setButtonEnabled(shouldEnable);
buttonAnimator.SetBool("MouseHeld", Input.GetMouseButton(0));
buttonAnimator.SetBool("MouseDown", playPressAnimation && Input.GetMouseButtonDown(0));
buttonAnimator.SetBool("MouseOver", !checkMouseOverCollider || isMouseOver());
if (button.enabled && button.interactable && Input.GetKeyDown(pressKey))
{
button.onClick.Invoke();
}
}
bool shouldButtonBeEnabled()
{
return !_forceDisable && !GameMenu.shifting;
}
void setButtonEnabled(bool enabled)
{
button.interactable = enabled;
if (enabled && isMouseOver())
{
buttonAnimator.ResetTrigger("Normal");
buttonAnimator.SetTrigger("Highlighted");
}
}
public bool isMouseOver()
{
return !GameMenu.shifting && CameraHelper.isMouseOver(backupCollider);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MenuButton : MonoBehaviour
{
#pragma warning disable 0649 //Serialized Fields
[SerializeField]
private Button button;
[SerializeField]
private Animator buttonAnimator;
[SerializeField]
private Collider2D backupCollider;
[SerializeField]
private bool playPressAnimation = true;
[SerializeField]
private bool checkMouseOverCollider = true;
[SerializeField]
private KeyCode pressKey = KeyCode.None;
#pragma warning restore 0649
private bool _forceDisable;
public bool forceDisable
{
get { return _forceDisable; }
set { _forceDisable = value; }
}
private int clickBuffer; //Waits one frame to enable button to prevent carry-over clicks from last scene
void Start()
{
bufferClick();
}
private void OnEnable()
{
bufferClick();
}
void bufferClick()
{
button.interactable = false;
clickBuffer = 2;
}
void enableButton()
{
button.interactable = true;
}
void LateUpdate()
{
if (clickBuffer > 0)
{
clickBuffer--;
if (clickBuffer == 0)
button.interactable = true;
return;
}
bool shouldEnable = shouldButtonBeEnabled();
if (button.interactable != shouldEnable)
setButtonEnabled(shouldEnable);
buttonAnimator.SetBool("MouseHeld", Input.GetMouseButton(0));
buttonAnimator.SetBool("MouseDown", playPressAnimation && Input.GetMouseButtonDown(0));
buttonAnimator.SetBool("MouseOver", !checkMouseOverCollider || isMouseOver());
if (button.enabled & button.interactable && Input.GetKeyDown(pressKey))
{
button.onClick.Invoke();
}
}
bool shouldButtonBeEnabled()
{
return !_forceDisable && !GameMenu.shifting;
}
void setButtonEnabled(bool enabled)
{
button.interactable = enabled;
if (enabled && isMouseOver())
{
buttonAnimator.ResetTrigger("Normal");
buttonAnimator.SetTrigger("Highlighted");
}
}
public bool isMouseOver()
{
return !GameMenu.shifting && CameraHelper.isMouseOver(backupCollider);
}
}
| mit | C# |
819d39aa51e1f36b0cca4e00f24670b96808b1e6 | change exception message | inputfalken/Sharpy | DataGen/Types/Mail/MailFactory.cs | DataGen/Types/Mail/MailFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace DataGen.Types.Mail {
public class MailFactory {
/// <summary>
/// Since this is static it will not get created for each new instance of this object. Which means this can keep track
/// of all created mails.
/// Cons: List will be huge if use alot of mails are created.
/// </summary>
private static readonly List<string> CreatedMails = new List<string>();
/// <summary>
/// Used for separating strings with symbols
/// </summary>
private static readonly List<char> Separators = new List<char> {
'_', '.', '-'
};
private readonly List<string> _emailDomains = new List<string>();
/// <summary>
/// Will use the strings as mail providers
/// </summary>
/// <param name="mailProviders">If Left Empty the mail providers will be defaulted to popular free providers.</param>
public MailFactory(params string[] mailProviders) {
if (mailProviders.Any())
mailProviders.ForEach(_emailDomains.Add);
else
_emailDomains.AddRange(new[] { "yahoo.com", "gmail.com", "hotmail.com" });
}
/// <summary>
/// Returns a string representing a mail address.
/// </summary>
/// <param name="text">the string/strings used to construct a mail string</param>
/// <returns></returns>
public string Mail(params string[] text) {
foreach (var i in Enumerable.Range(1, 10)) {
var address =
$"{text.Aggregate((s, s1) => s + Separators[HelperClass.Randomizer(Separators.Count)] + s1).ToLower()}@{_emailDomains[HelperClass.Randomizer(_emailDomains.Count)]}";
if (CreatedMails.Contains(address)) continue;
CreatedMails.Add(address);
return address;
}
throw new Exception("Reached maxium attempts to create unique Mails");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace DataGen.Types.Mail {
public class MailFactory {
/// <summary>
/// Since this is static it will not get created for each new instance of this object. Which means this can keep track
/// of all created mails.
/// Cons: List will be huge if use alot of mails are created.
/// </summary>
private static readonly List<string> CreatedMails = new List<string>();
/// <summary>
/// Used for separating strings with symbols
/// </summary>
private static readonly List<char> Separators = new List<char> {
'_', '.', '-'
};
private readonly List<string> _emailDomains = new List<string>();
/// <summary>
/// Will use the strings as mail providers
/// </summary>
/// <param name="mailProviders">If Left Empty the mail providers will be defaulted to popular free providers.</param>
public MailFactory(params string[] mailProviders) {
if (mailProviders.Any())
mailProviders.ForEach(_emailDomains.Add);
else
_emailDomains.AddRange(new[] { "yahoo.com", "gmail.com", "hotmail.com" });
}
/// <summary>
/// Returns a string representing a mail address.
/// </summary>
/// <param name="text">the string/strings used to construct a mail string</param>
/// <returns></returns>
public string Mail(params string[] text) {
foreach (var i in Enumerable.Range(1, 10)) {
var address =
$"{text.Aggregate((s, s1) => s + Separators[HelperClass.Randomizer(Separators.Count)] + s1).ToLower()}@{_emailDomains[HelperClass.Randomizer(_emailDomains.Count)]}";
if (CreatedMails.Contains(address)) continue;
CreatedMails.Add(address);
return address;
}
throw new Exception("Reached maxium attempts to create Mail");
}
}
} | mit | C# |
3dc629dae1278a5be7fe1681e3522907130fd962 | Simplify image summarizer code | jcmoyer/Yeena | Yeena/Data/StashImageSummarizer.cs | Yeena/Data/StashImageSummarizer.cs | // Copyright 2013 J.C. Moyer
//
// 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.Drawing;
using System.Net.Http;
using Yeena.PathOfExile;
namespace Yeena.Data {
class StashImageSummarizer : IStashSummarizer {
private readonly HttpClient _client;
private readonly int _tabWidth;
private readonly ImageCache _imageCache;
public StashImageSummarizer(ImageCache imgCache) {
_imageCache = imgCache;
_client = new HttpClient();
// TODO: Make 32 parameterizable here and below
_tabWidth = PoEGame.StashWidth * 32;
}
public void Summarize(string filename, PoEStash stash) {
int imageWidth = PoEGame.StashWidth * 32 * stash.Tabs.Count;
int imageHeight = PoEGame.StashHeight * 32;
var bitmap = new Bitmap(imageWidth, imageHeight);
using (var g = Graphics.FromImage(bitmap)) {
g.FillRectangle(Brushes.Black, 0, 0, imageWidth, imageHeight);
foreach (var tab in stash.Tabs) {
RenderTab(g, tab);
}
}
bitmap.Save(filename);
}
private void RenderTab(Graphics g, PoEStashTab tab) {
foreach (var item in tab) {
RenderItem(g, item, tab.TabInfo.Index * _tabWidth);
}
}
private async void RenderItem(Graphics g, PoEItem item, int offsetX) {
var itemImage = await _imageCache.GetAsync(_client, new Uri(PoESite.Uri, item.IconUrl));
g.DrawImage(itemImage, offsetX + item.X * 32, item.Y * 32, item.Width * 32, item.Height * 32);
}
}
}
| // Copyright 2013 J.C. Moyer
//
// 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.Drawing;
using System.Net.Http;
using Yeena.PathOfExile;
namespace Yeena.Data {
class StashImageSummarizer : IStashSummarizer {
private readonly ImageCache _imageCache;
public StashImageSummarizer(ImageCache imgCache) {
_imageCache = imgCache;
}
public async void Summarize(string filename, PoEStash stash) {
HttpClient cl = new HttpClient();
int tabWidth = PoEGame.StashWidth * 32;
int imageWidth = PoEGame.StashWidth * 32 * stash.Tabs.Count;
int imageHeight = PoEGame.StashHeight * 32;
var bitmap = new Bitmap(imageWidth, imageHeight);
var g = Graphics.FromImage(bitmap);
int t = 0;
g.FillRectangle(Brushes.Black, 0, 0, imageWidth, imageHeight);
foreach (var tab in stash.Tabs) {
foreach (var item in tab) {
var itemImage = await _imageCache.GetAsync(cl, new Uri(PoESite.Uri, item.IconUrl));
g.DrawImage(itemImage, tabWidth * t + item.X * 32, item.Y * 32, item.Width * 32, item.Height * 32);
}
t++;
}
g.Dispose();
bitmap.Save(filename);
}
}
}
| apache-2.0 | C# |
dca60f9e7f14f29584767daaaa973b6691fa12a3 | Update Index.cshtml - Fixed Edit link | NinjaVault/NinjaHive,NinjaVault/NinjaHive | NinjaHive.WebApp/Views/EquipmentItem/Index.cshtml | NinjaHive.WebApp/Views/EquipmentItem/Index.cshtml | @using NinjaHive.Contract.DTOs
@using NinjaHive.WebApp.Controllers
@using NinjaHive.WebApp.Services
@model EquipmentItem[]
<div class="row">
<div class="col-md-12">
<br />
<p>
@Html.ActionLink("Create Equipment Item", "Create", null, new { @class = "btn btn-default" })
</p>
<hr />
<h4>List of items in the database</h4>
</div>
@foreach (var item in Model)
{
var itemId = item.Id;
var itemDetailsUrl = UrlProvider<EquipmentItemController>.GetUrl(c => c.Edit(itemId));
<div class="col-md-2">
<div class="thumbnail">
<a href="@itemDetailsUrl" class="thumbnail">
<img src="/Content/Images/default_image.png" alt="..."/>
</a>
<div class="caption">
<p>@item.Name</p>
<p>
@Html.ActionLink("Delete", "Delete", item)<br />
<a href="@itemDetailsUrl"> Edit </a>
</p>
</div>
</div>
</div>
}
</div> | @using NinjaHive.Contract.DTOs
@using NinjaHive.WebApp.Controllers
@using NinjaHive.WebApp.Services
@model EquipmentItem[]
<div class="row">
<div class="col-md-12">
<br />
<p>
@Html.ActionLink("Create Equipment Item", "Create", null, new { @class = "btn btn-default" })
</p>
<hr />
<h4>List of items in the database</h4>
</div>
@foreach (var item in Model)
{
var itemId = item.Id;
var itemDetailsUrl = UrlProvider<EquipmentItemController>.GetUrl(c => c.Edit(itemId));
<div class="col-md-2">
<div class="thumbnail">
<a href="@itemDetailsUrl" class="thumbnail">
<img src="/Content/Images/default_image.png" alt="..."/>
</a>
<div class="caption">
<p>@item.Name</p>
<p>
@Html.ActionLink("Delete", "Delete", item)<br />
<a href="@itemDetailsUrl">Edit</a>
</p>
</div>
</div>
</div>
}
</div> | apache-2.0 | C# |
87f52b82331dc1f6ba4b198d96cb8b768a152c19 | Remove redundant switch section | ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu | osu.Game/Overlays/OverlayView.cs | osu.Game/Overlays/OverlayView.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API;
namespace osu.Game.Overlays
{
/// <summary>
/// Drawable which used to represent online content in <see cref="FullscreenOverlay"/>.
/// </summary>
/// <typeparam name="T">Response type</typeparam>
public abstract class OverlayView<T> : Container, IOnlineComponent
where T : class
{
[Resolved]
protected IAPIProvider API { get; private set; }
protected override Container<Drawable> Content => content;
private readonly FillFlowContainer content;
protected OverlayView()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
AddInternal(content = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
});
}
protected override void LoadComplete()
{
base.LoadComplete();
API.Register(this);
}
private APIRequest<T> request;
protected abstract APIRequest<T> CreateRequest();
protected abstract void OnSuccess(T response);
public virtual void APIStateChanged(IAPIProvider api, APIState state)
{
switch (state)
{
case APIState.Online:
request = CreateRequest();
request.Success += response => Schedule(() => OnSuccess(response));
api.Queue(request);
break;
}
}
protected override void Dispose(bool isDisposing)
{
request?.Cancel();
API?.Unregister(this);
base.Dispose(isDisposing);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API;
namespace osu.Game.Overlays
{
/// <summary>
/// Drawable which used to represent online content in <see cref="FullscreenOverlay"/>.
/// </summary>
/// <typeparam name="T">Response type</typeparam>
public abstract class OverlayView<T> : Container, IOnlineComponent
where T : class
{
[Resolved]
protected IAPIProvider API { get; private set; }
protected override Container<Drawable> Content => content;
private readonly FillFlowContainer content;
protected OverlayView()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
AddInternal(content = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
});
}
protected override void LoadComplete()
{
base.LoadComplete();
API.Register(this);
}
private APIRequest<T> request;
protected abstract APIRequest<T> CreateRequest();
protected abstract void OnSuccess(T response);
public virtual void APIStateChanged(IAPIProvider api, APIState state)
{
switch (state)
{
case APIState.Online:
request = CreateRequest();
request.Success += response => Schedule(() => OnSuccess(response));
api.Queue(request);
break;
default:
break;
}
}
protected override void Dispose(bool isDisposing)
{
request?.Cancel();
API?.Unregister(this);
base.Dispose(isDisposing);
}
}
}
| mit | C# |
2e9a6608fb30cf590fb743b7cd340888be205b5d | Move control initialization to OnInit method | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University.Launchpad/SettingsLaunchpad.ascx.cs | R7.University.Launchpad/SettingsLaunchpad.ascx.cs | using System;
using System.Web.UI.WebControls;
using System.Linq;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.UI.UserControls;
using R7.University;
namespace R7.University.Launchpad
{
public partial class SettingsLaunchpad : ModuleSettingsBase
{
public void OnInit()
{
// fill PageSize combobox
for (var i = 1; i <= 10; i++)
{
var strPageSize = (i * 5).ToString();
comboPageSize.AddItem(strPageSize, strPageSize);
}
// fill tables list
listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Positions", "positions"));
listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Divisions", "divisions"));
listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Employees", "employees"));
}
/// <summary>
/// Handles the loading of the module setting for this control
/// </summary>
public override void LoadSettings ()
{
try {
if (!IsPostBack) {
var settings = new LaunchpadSettings (this);
// TODO: Allow select nearest pagesize value
comboPageSize.Select (settings.PageSize.ToString(), false);
// check table list items
var tableNames = settings.Tables.Split(';');
foreach (var tableName in tableNames)
{
var item = listTables.FindItemByValue(tableName);
if (item != null) item.Checked = true;
}
}
} catch (Exception ex) {
Exceptions.ProcessModuleLoadException (this, ex);
}
}
/// <summary>
/// handles updating the module settings for this control
/// </summary>
public override void UpdateSettings ()
{
try {
var settings = new LaunchpadSettings (this);
settings.PageSize = int.Parse(comboPageSize.SelectedValue);
settings.Tables = Utils.FormatList(";", listTables.CheckedItems.Select(i => i.Value).ToArray());
// NOTE: update module cache (temporary fix before 7.2.0)?
// more info: https://github.com/dnnsoftware/Dnn.Platform/pull/21
var moduleController = new ModuleController();
moduleController.ClearCache(TabId);
Utils.SynchronizeModule(this);
} catch (Exception ex) {
Exceptions.ProcessModuleLoadException (this, ex);
}
}
}
}
| using System;
using System.Web.UI.WebControls;
using System.Linq;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.UI.UserControls;
using R7.University;
namespace R7.University.Launchpad
{
public partial class SettingsLaunchpad : ModuleSettingsBase
{
/// <summary>
/// Handles the loading of the module setting for this control
/// </summary>
public override void LoadSettings ()
{
try {
if (!IsPostBack) {
var settings = new LaunchpadSettings (this);
// fill PageSize combobox
for (var i = 1; i <= 10; i++)
{
var strPageSize = (i * 5).ToString();
comboPageSize.AddItem(strPageSize, strPageSize);
}
// TODO: Allow select nearest pagesize value
comboPageSize.Select (settings.PageSize.ToString(), false);
// fill tables list
listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Positions", "positions"));
listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Divisions", "divisions"));
listTables.Items.Add (new Telerik.Web.UI.RadListBoxItem("Employees", "employees"));
// check table list items
var tableNames = settings.Tables.Split(';');
foreach (var tableName in tableNames)
{
var item = listTables.FindItemByValue(tableName);
if (item != null) item.Checked = true;
}
}
} catch (Exception ex) {
Exceptions.ProcessModuleLoadException (this, ex);
}
}
/// <summary>
/// handles updating the module settings for this control
/// </summary>
public override void UpdateSettings ()
{
try {
var settings = new LaunchpadSettings (this);
settings.PageSize = int.Parse(comboPageSize.SelectedValue);
settings.Tables = Utils.FormatList(";", listTables.CheckedItems.Select(i => i.Value).ToArray());
// NOTE: update module cache (temporary fix before 7.2.0)?
// more info: https://github.com/dnnsoftware/Dnn.Platform/pull/21
var moduleController = new ModuleController();
moduleController.ClearCache(TabId);
Utils.SynchronizeModule(this);
} catch (Exception ex) {
Exceptions.ProcessModuleLoadException (this, ex);
}
}
}
}
| agpl-3.0 | C# |
05b5b5c1dc3e49f06d0ef936c3f24c62acaf4aad | optimize slovenia provider | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date/PublicHolidays/SloveniaProvider.cs | Src/Nager.Date/PublicHolidays/SloveniaProvider.cs | using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class SloveniaProvider : CatholicBaseProvider
{
public override IEnumerable<PublicHoliday> Get(int year)
{
//Slovenia
//https://en.wikipedia.org/wiki/Public_holidays_in_Slovenia
var countryCode = CountryCode.SI;
var easterSunday = base.EasterSunday(year);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "novo leto", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 1, 2, "novo leto", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 2, 8, "Prešernov dan", "Prešeren Day", countryCode));
items.Add(new PublicHoliday(easterSunday, "velikonočna nedelja in ponedeljek", "Easter Sunday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(1), "velikonočna nedelja in ponedeljek", "Easter Monday", countryCode));
items.Add(new PublicHoliday(year, 4, 27, "dan upora proti okupatorju", "Day of Uprising Against Occupation", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "praznik dela", "May Day Holiday", countryCode, 1949));
items.Add(new PublicHoliday(year, 5, 2, "praznik dela", "May Day Holiday", countryCode, 1949));
items.Add(new PublicHoliday(easterSunday.AddDays(49), "binkoštna nedelja, binkošti", "Whit Sunday", countryCode));
//items.Add(new PublicHoliday(year, 6, 8, "dan Primoža Trubarja", "Primož Trubar Day", countryCode)); not work-free
items.Add(new PublicHoliday(year, 6, 25, "dan državnosti", "Statehood Day", countryCode));
items.Add(new PublicHoliday(year, 8, 15, "Marijino vnebovzetje", "Assumption Day", countryCode, 1992));
items.Add(new PublicHoliday(year, 10, 31, "dan reformacije", "Reformation Day", countryCode, 1992));
items.Add(new PublicHoliday(year, 11, 1, "dan spomina na mrtve", "Day of the Dead", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "božič", "Christmas Day", countryCode));
items.Add(new PublicHoliday(year, 12, 26, "dan samostojnosti in enotnosti", "Independence and Unity Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class SloveniaProvider : CatholicBaseProvider
{
public override IEnumerable<PublicHoliday> Get(int year)
{
//Slovenia
//https://en.wikipedia.org/wiki/Public_holidays_in_Slovenia
var countryCode = CountryCode.SI;
var easterSunday = base.EasterSunday(year);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "novo leto", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 1, 2, "novo leto", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 2, 8, "Prešernov dan", "Prešeren Day", countryCode));
items.Add(new PublicHoliday(easterSunday, "velikonočna nedelja in ponedeljek", "Easter Sunday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(1), "velikonočna nedelja in ponedeljek", "Easter Monday", countryCode));
items.Add(new PublicHoliday(year, 4, 27, "dan upora proti okupatorju", "Day of Uprising Against Occupation", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "praznik dela", "May Day Holiday", countryCode, 1949));
items.Add(new PublicHoliday(year, 5, 2, "praznik dela", "May Day Holiday", countryCode, 1949));
items.Add(new PublicHoliday(easterSunday.AddDays(49), "binkoštna nedelja, binkošti", "Whit Sunday", countryCode));
items.Add(new PublicHoliday(year, 6, 8, "dan Primoža Trubarja", "Primož Trubar Day", countryCode));
items.Add(new PublicHoliday(year, 6, 25, "dan državnosti", "Statehood Day", countryCode));
items.Add(new PublicHoliday(year, 8, 15, "Marijino vnebovzetje", "Assumption Day", countryCode, 1992));
items.Add(new PublicHoliday(year, 10, 31, "dan reformacije", "Reformation Day", countryCode, 1992));
items.Add(new PublicHoliday(year, 10, 31, "dan spomina na mrtve", "Day of the Dead", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "božič", "Christmas Day", countryCode));
items.Add(new PublicHoliday(year, 12, 26, "dan samostojnosti in enotnosti", "Independence and Unity Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| mit | C# |
ae94cde718003c8a59e6a8b4010a9ba44979ea64 | Rename public enumerators | y-iihoshi/ThScoreFileConverter,y-iihoshi/ThScoreFileConverter | ThScoreFileConverter/Models/Th10/StageProgress.cs | ThScoreFileConverter/Models/Th10/StageProgress.cs | //-----------------------------------------------------------------------
// <copyright file="StageProgress.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
namespace ThScoreFileConverter.Models.Th10
{
/// <summary>
/// Represents a stage progress of a gameplay.
/// </summary>
public enum StageProgress
{
/// <summary>
/// Not played yet.
/// </summary>
[EnumAltName("-------")]
None,
/// <summary>
/// Lost at stage 1.
/// </summary>
[EnumAltName("Stage 1")]
One,
/// <summary>
/// Lost at stage 2.
/// </summary>
[EnumAltName("Stage 2")]
Two,
/// <summary>
/// Lost at stage 3.
/// </summary>
[EnumAltName("Stage 3")]
Three,
/// <summary>
/// Lost at stage 4.
/// </summary>
[EnumAltName("Stage 4")]
Four,
/// <summary>
/// Lost at stage 5.
/// </summary>
[EnumAltName("Stage 5")]
Five,
/// <summary>
/// Lost at stage 6.
/// </summary>
[EnumAltName("Stage 6")]
Six,
/// <summary>
/// Lost at Extra stage.
/// </summary>
[EnumAltName("Extra Stage")]
Extra,
/// <summary>
/// All cleared.
/// </summary>
[EnumAltName("All Clear")]
Clear,
}
}
| //-----------------------------------------------------------------------
// <copyright file="StageProgress.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
namespace ThScoreFileConverter.Models.Th10
{
/// <summary>
/// Represents a stage progress of a gameplay.
/// </summary>
public enum StageProgress
{
/// <summary>
/// Not played yet.
/// </summary>
[EnumAltName("-------")]
None,
/// <summary>
/// Lost at stage 1.
/// </summary>
[EnumAltName("Stage 1")]
St1,
/// <summary>
/// Lost at stage 2.
/// </summary>
[EnumAltName("Stage 2")]
St2,
/// <summary>
/// Lost at stage 3.
/// </summary>
[EnumAltName("Stage 3")]
St3,
/// <summary>
/// Lost at stage 4.
/// </summary>
[EnumAltName("Stage 4")]
St4,
/// <summary>
/// Lost at stage 5.
/// </summary>
[EnumAltName("Stage 5")]
St5,
/// <summary>
/// Lost at stage 6.
/// </summary>
[EnumAltName("Stage 6")]
St6,
/// <summary>
/// Lost at Extra stage.
/// </summary>
[EnumAltName("Extra Stage")]
Extra,
/// <summary>
/// All cleared.
/// </summary>
[EnumAltName("All Clear")]
Clear,
}
}
| bsd-2-clause | C# |
90f1c6c278ff2ba5df62080f70325f57221d1f1d | Use new parsing to be able to process simple typed JSON returned by servers. | clanofthecloud/unity-sdk,xtralifecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,clanofthecloud/unity-sdk,xtralifecloud/unity-sdk,clanofthecloud/unity-sdk,xtralifecloud/unity-sdk,clanofthecloud/unity-sdk,xtralifecloud/unity-sdk | CotcSdk/Internal/HttpResponse.cs | CotcSdk/Internal/HttpResponse.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace CotcSdk {
internal class HttpResponse {
public byte[] Body {
get { return body; }
set { body = value; CachedBundle = null; CachedString = null; }
}
public string BodyString {
get {
if (CachedString == null && body != null) {
CachedString = Encoding.UTF8.GetString(Body);
}
return CachedString;
}
}
public Bundle BodyJson
{
get { CachedBundle = CachedBundle ?? Bundle.FromAnyJson(BodyString); return CachedBundle; }
}
public Exception Exception;
public bool HasBody {
get { return body != null; }
}
/// <summary>
/// If true, means that the request has completely failed, not that it received an error code such as 400.
/// This will appear as completely normal. Use Common.HasFailed in that case.
/// </summary>
public bool HasFailed {
get { return Exception != null; }
}
public Dictionary<String, String> Headers = new Dictionary<string, string>();
/// <summary>Returns whether this response is in an error state that should be retried according to the request configuration.</summary>
public bool ShouldBeRetried(HttpRequest request) {
switch (request.RetryPolicy) {
case HttpRequest.Policy.NonpermanentErrors:
return HasFailed || StatusCode < 100 || (StatusCode >= 300 && StatusCode < 400) || StatusCode >= 500;
case HttpRequest.Policy.AllErrors:
return HasFailed || StatusCode < 100 || StatusCode >= 300;
case HttpRequest.Policy.Never:
default:
return false;
}
}
public int StatusCode;
public HttpResponse() {}
public HttpResponse(Exception e) { Exception = e; }
private byte[] body;
private Bundle CachedBundle;
private string CachedString;
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace CotcSdk {
internal class HttpResponse {
public byte[] Body {
get { return body; }
set { body = value; CachedBundle = null; CachedString = null; }
}
public string BodyString {
get {
if (CachedString == null && body != null) {
CachedString = Encoding.UTF8.GetString(Body);
}
return CachedString;
}
}
public Bundle BodyJson
{
get { CachedBundle = CachedBundle ?? Bundle.FromJson(BodyString); return CachedBundle; }
}
public Exception Exception;
public bool HasBody {
get { return body != null; }
}
/// <summary>
/// If true, means that the request has completely failed, not that it received an error code such as 400.
/// This will appear as completely normal. Use Common.HasFailed in that case.
/// </summary>
public bool HasFailed {
get { return Exception != null; }
}
public Dictionary<String, String> Headers = new Dictionary<string, string>();
/// <summary>Returns whether this response is in an error state that should be retried according to the request configuration.</summary>
public bool ShouldBeRetried(HttpRequest request) {
switch (request.RetryPolicy) {
case HttpRequest.Policy.NonpermanentErrors:
return HasFailed || StatusCode < 100 || (StatusCode >= 300 && StatusCode < 400) || StatusCode >= 500;
case HttpRequest.Policy.AllErrors:
return HasFailed || StatusCode < 100 || StatusCode >= 300;
case HttpRequest.Policy.Never:
default:
return false;
}
}
public int StatusCode;
public HttpResponse() {}
public HttpResponse(Exception e) { Exception = e; }
private byte[] body;
private Bundle CachedBundle;
private string CachedString;
}
}
| mit | C# |
186d43366f08e9e6d6c50e3bb33afeb34a7054d0 | Add comment explaining UseUrls usage | dbjorge/housecannith,dbjorge/housecannith,dbjorge/housecannith | HouseCannith.Frontend/Program.cs | HouseCannith.Frontend/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace HouseCannith_Frontend
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
// This URL is only applicable to Development - when run behind a reverse-proxy IIS
// instance (like Azure App Service does in production), this is overriden
.UseUrls("https://localhost:5001")
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace HouseCannith_Frontend
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseUrls("https://localhost:5001")
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
| mit | C# |
049634ec2be54bf6f3df20f8976c0ec267575f2b | Update IntercomClient. | karonte84/IntercomDotnet,richard-kong/IntercomDotnet,tarr11/IntercomDotnet,mgoodfellow/IntercomDotnet | IntercomDotnet/IntercomClient.cs | IntercomDotnet/IntercomClient.cs | using IntercomDotNet.Resources;
namespace IntercomDotNet
{
public class IntercomClient
{
public const string ApiRoot = "https://api.intercom.io/";
public static IntercomClient GetClient(string appid, string apiKey)
{
var client = new Client
{
UserName = appid,
Password = apiKey,
ApiRoot = ApiRoot
};
return new IntercomClient(
new Users(client),
new Notes(client),
new Tags(client),
new Events(client),
new Segments(client),
new Companies(client));
}
private IntercomClient(Users users, Notes notes, Tags tags, Events events, Segments segments, Companies companies)
{
Users = users;
Notes = notes;
Tags = tags;
Events = events;
Segments = segments;
Companies = companies;
}
public Users Users { get; private set; }
public Notes Notes { get; private set; }
public Tags Tags { get; private set; }
public Events Events { get; private set; }
public Segments Segments { get; private set; }
public Companies Companies { get; private set; }
}
}
| using IntercomDotNet.Resources;
namespace IntercomDotNet
{
public class IntercomClient
{
public const string ApiRoot = "https://api.intercom.io/";
public static IntercomClient GetClient(string appid, string apiKey)
{
var client = new Client
{
UserName = appid,
Password = apiKey,
ApiRoot = ApiRoot
};
return new IntercomClient(
new Users(client),
new Notes(client),
new Tags(client),
new Events(client),
new Segments(client));
}
private IntercomClient(Users users, Notes notes, Tags tags, Events events, Segments segments)
{
Users = users;
Notes = notes;
Tags = tags;
Events = events;
Segments = segments;
}
public Users Users { get; private set; }
public Notes Notes { get; private set; }
public Tags Tags { get; private set; }
public Events Events { get; private set; }
public Segments Segments { get; private set; }
}
}
| apache-2.0 | C# |
cdc0f3401b389e776a2cc5b0dcc84fc7f65c51c9 | Optimize Single to avoid excessive slice operations when we simply need to inspect a single item at a known index. | plioi/parsley | src/Parsley/Grammar.Single.cs | src/Parsley/Grammar.Single.cs | using System.Diagnostics.CodeAnalysis;
namespace Parsley;
partial class Grammar
{
public static Parser<TItem, TItem> Single<TItem>(TItem expected)
{
return Single<TItem>(x => EqualityComparer<TItem>.Default.Equals(x, expected), $"{expected}");
}
public static Parser<TItem, TItem> Single<TItem>(Predicate<TItem> test, string name)
{
return (ReadOnlySpan<TItem> input, ref int index, [NotNullWhen(true)] out TItem? value, [NotNullWhen(false)] out string? expectation) =>
{
if (index + 1 <= input.Length)
{
var c = input[index]!;
if (test(c))
{
index += 1;
expectation = null;
value = c;
return true;
}
}
expectation = name;
value = default;
return false;
};
}
}
| using System.Diagnostics.CodeAnalysis;
namespace Parsley;
partial class Grammar
{
public static Parser<TItem, TItem> Single<TItem>(TItem expected)
{
return Single<TItem>(x => EqualityComparer<TItem>.Default.Equals(x, expected), $"{expected}");
}
public static Parser<TItem, TItem> Single<TItem>(Predicate<TItem> test, string name)
{
return (ReadOnlySpan<TItem> input, ref int index, [NotNullWhen(true)] out TItem? value, [NotNullWhen(false)] out string? expectation) =>
{
var next = input.Peek(index, 1);
if (next.Length == 1)
{
var c = next[0]!;
if (test(c))
{
index += 1;
expectation = null;
value = c;
return true;
}
}
expectation = name;
value = default;
return false;
};
}
}
| mit | C# |
2121475b8bbc83b0638c9f499acb90dab16ddaef | Add assignation in operation start of node | IfElseSwitch/hc-engine,IfElseSwitch/hc-engine | HCEngine/HCEngine/Default/Language/Statements/Operation.cs | HCEngine/HCEngine/Default/Language/Statements/Operation.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace HCEngine.Default.Language
{
/// <summary>
/// Base class for Operation item
/// </summary>
public class Operation : ISyntaxTreeItem
{
/// <summary>
/// <see cref="ISyntaxTreeItem.Execute(ISourceReader, IExecutionScope, bool)"/>
/// </summary>
public IScriptExecution Execute(ISourceReader reader, IExecutionScope scope, bool skipExec)
{
string word = reader.LastKeyword;
if (DefaultLanguageNodes.Assignation.IsStartOfNode(word, scope))
return DefaultLanguageNodes.Assignation.Execute(reader, scope, skipExec);
if (DefaultLanguageNodes.Call.IsStartOfNode(word, scope))
return DefaultLanguageNodes.Call.Execute(reader, scope, skipExec);
if (DefaultLanguageNodes.Variable.IsStartOfNode(word, scope))
return DefaultLanguageNodes.Variable.Execute(reader, scope, skipExec);
if (DefaultLanguageNodes.Constant.IsStartOfNode(word, scope))
return DefaultLanguageNodes.Constant.Execute(reader, scope, skipExec);
throw new SyntaxException(reader, "Not recognized as operation");
}
/// <summary>
/// <see cref="ISyntaxTreeItem.IsStartOfNode(string, IExecutionScope)"/>
/// </summary>
public bool IsStartOfNode(string word, IExecutionScope scope)
{
return DefaultLanguageNodes.Call.IsStartOfNode(word, scope) ||
DefaultLanguageNodes.Assignation.IsStartOfNode(word, scope) ||
DefaultLanguageNodes.Variable.IsStartOfNode(word, scope) ||
DefaultLanguageNodes.Constant.IsStartOfNode(word, scope);
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace HCEngine.Default.Language
{
/// <summary>
/// Base class for Operation item
/// </summary>
public class Operation : ISyntaxTreeItem
{
/// <summary>
/// <see cref="ISyntaxTreeItem.Execute(ISourceReader, IExecutionScope, bool)"/>
/// </summary>
public IScriptExecution Execute(ISourceReader reader, IExecutionScope scope, bool skipExec)
{
string word = reader.LastKeyword;
if (DefaultLanguageNodes.Assignation.IsStartOfNode(word, scope))
return DefaultLanguageNodes.Assignation.Execute(reader, scope, skipExec);
if (DefaultLanguageNodes.Call.IsStartOfNode(word, scope))
return DefaultLanguageNodes.Call.Execute(reader, scope, skipExec);
if (DefaultLanguageNodes.Variable.IsStartOfNode(word, scope))
return DefaultLanguageNodes.Variable.Execute(reader, scope, skipExec);
if (DefaultLanguageNodes.Constant.IsStartOfNode(word, scope))
return DefaultLanguageNodes.Constant.Execute(reader, scope, skipExec);
throw new SyntaxException(reader, "Not recognized as operation");
}
/// <summary>
/// <see cref="ISyntaxTreeItem.IsStartOfNode(string, IExecutionScope)"/>
/// </summary>
public bool IsStartOfNode(string word, IExecutionScope scope)
{
return DefaultLanguageNodes.Call.IsStartOfNode(word, scope) ||
DefaultLanguageNodes.Variable.IsStartOfNode(word, scope) ||
DefaultLanguageNodes.Constant.IsStartOfNode(word, scope);
}
}
}
| mit | C# |
6f582ca3dcd6e492f361ebb19eb2e151d3c4b4a9 | increment version number | billtowin/mega-epic-super-tankz,billtowin/mega-epic-super-tankz | modules/AppCore/1/main.cs | modules/AppCore/1/main.cs | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function AppCore::create( %this )
{
// Load system scripts
exec("./scripts/constants.cs");
exec("./scripts/defaultPreferences.cs");
exec("./scripts/canvas.cs");
exec("./scripts/openal.cs");
// Initialize the canvas
initializeCanvas("Mega Epic Super Tankz v0.02 ALPHA");
// Set the canvas color
Canvas.BackgroundColor = "CornflowerBlue";
Canvas.UseBackgroundColor = true;
// Initialize audio
initializeOpenAL();
ModuleDatabase.loadExplicit("MyModule");
}
//-----------------------------------------------------------------------------
function AppCore::destroy( %this )
{
}
| //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function AppCore::create( %this )
{
// Load system scripts
exec("./scripts/constants.cs");
exec("./scripts/defaultPreferences.cs");
exec("./scripts/canvas.cs");
exec("./scripts/openal.cs");
// Initialize the canvas
initializeCanvas("Mega Epic Super Tankz v0.01 ALPHA");
// Set the canvas color
Canvas.BackgroundColor = "CornflowerBlue";
Canvas.UseBackgroundColor = true;
// Initialize audio
initializeOpenAL();
ModuleDatabase.loadExplicit("MyModule");
}
//-----------------------------------------------------------------------------
function AppCore::destroy( %this )
{
}
| mit | C# |
eeda7820bf1c779d4728f901039f268117d1bc91 | Allow payments to be marked as reconciled | TDaphneB/XeroAPI.Net,XeroAPI/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,jcvandan/XeroAPI.Net | source/XeroApi/Model/Payment.cs | source/XeroApi/Model/Payment.cs | using System;
namespace XeroApi.Model
{
public class Payment : EndpointModelBase
{
[ItemId]
public Guid? PaymentID { get; set; }
public DateTime Date { get; set; }
public decimal Amount { get; set; }
public string Reference { get; set; }
public decimal? CurrencyRate { get; set; }
public string PaymentType { get; set; }
public string Status { get; set; }
public bool IsReconciled { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public Account Account { get; set; }
public Invoice Invoice { get; set; }
}
public class Payments : ModelList<Payment>
{
}
}
| using System;
namespace XeroApi.Model
{
public class Payment : EndpointModelBase
{
[ItemId]
public Guid? PaymentID { get; set; }
public DateTime Date { get; set; }
public decimal Amount { get; set; }
public string Reference { get; set; }
public decimal? CurrencyRate { get; set; }
public string PaymentType { get; set; }
public string Status { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public Account Account { get; set; }
public Invoice Invoice { get; set; }
}
public class Payments : ModelList<Payment>
{
}
} | mit | C# |
7acf638d8d6181767600a43f7ff1e2e1a1728ca6 | Change Transaction Type | songjiahong/revitapisamples | 1.6.FBXExporter/Command.cs | 1.6.FBXExporter/Command.cs | using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FBXExporter
{
[Transaction(TransactionMode.ReadOnly)]
[Regeneration(RegenerationOption.Manual)]
public class Command : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
FormExporter dialog = new FormExporter(commandData.Application.Application);
dialog.ShowDialog();
return Result.Succeeded;
}
}
}
| using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FBXExporter
{
[Transaction(TransactionMode.Manual)]
[Regeneration(RegenerationOption.Manual)]
public class Command : IExternalCommand
{
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
FormExporter dialog = new FormExporter(commandData.Application.Application);
dialog.ShowDialog();
return Result.Succeeded;
}
}
}
| mit | C# |
65469e5332a2952f6b1cac4685ddc1f2b13b8fe2 | Add an OrderRequest field | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Core/Domain/Order.cs | Anlab.Core/Domain/Order.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using Anlab.Core.Models;
using Newtonsoft.Json;
namespace Anlab.Core.Domain
{
public class Order :IDatedEntity
{
public int Id { get; set; }
[Required]
public string CreatorId { get; set; }
[ForeignKey("CreatorId")]
public User Creator { get; set; }
[StringLength(256)]
[Required]
public string Project { get; set; }
[StringLength(16)]
public string LabId { get; set; }
[StringLength(16)]
public string ClientId { get; set; }
public string AdditionalEmails { get; set; }
public string JsonDetails { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public string Status { get; set; }
public string OrderRequest { get; set; }
public ICollection<MailMessage> MailMessages { get; set; }
public OrderDetails GetOrderDetails()
{
try
{
return JsonConvert.DeserializeObject<OrderDetails>(JsonDetails);
}
catch (JsonSerializationException)
{
return new OrderDetails();
}
}
public void SaveDetails(OrderDetails details)
{
JsonDetails = JsonConvert.SerializeObject(details);
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using Anlab.Core.Models;
using Newtonsoft.Json;
namespace Anlab.Core.Domain
{
public class Order :IDatedEntity
{
public int Id { get; set; }
[Required]
public string CreatorId { get; set; }
[ForeignKey("CreatorId")]
public User Creator { get; set; }
[StringLength(256)]
[Required]
public string Project { get; set; }
[StringLength(16)]
public string LabId { get; set; }
[StringLength(16)]
public string ClientId { get; set; }
public string AdditionalEmails { get; set; }
public string JsonDetails { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public string Status { get; set; }
public ICollection<MailMessage> MailMessages { get; set; }
public OrderDetails GetOrderDetails()
{
try
{
return JsonConvert.DeserializeObject<OrderDetails>(JsonDetails);
}
catch (JsonSerializationException)
{
return new OrderDetails();
}
}
public void SaveDetails(OrderDetails details)
{
JsonDetails = JsonConvert.SerializeObject(details);
}
}
}
| mit | C# |
380557ada3bfdd3f3a4839b0185491a2d16cdc4a | Change .NET version | martincostello/api,martincostello/api,martincostello/api | src/API/Views/Home/Index.cshtml | src/API/Views/Home/Index.cshtml | @using System.Reflection
@{
ViewBag.Title = "Home Page";
string? mvcVersion = typeof(Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions)
.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
SiteOptions options = Options.Value;
}
<div class="jumbotron">
<h1>Martin Costello's API</h1>
<p class="lead">
This website is an excercise in the use of ASP.NET @Environment.Version.ToString(2) for a website and REST API.
</p>
</div>
<div>
<p>
This website is hosted in <a href="https://azure.microsoft.com" rel="noopener" target="_blank" title="Microsoft Azure">Microsoft Azure</a>
and the source code can be found on <a href="@options.Metadata?.Repository" rel="noopener" target="_blank" title="This application's GitHub repository">GitHub</a>.
</p>
<p>
It is currently running .NET @(System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription).
</p>
</div>
<div class="row">
<div class="col-lg-6">
<h2 class="h3">Website</h2>
<p>My main website.</p>
<p><a id="link-website" href="@options.Metadata?.Author?.Website" class="btn btn-lg btn-primary" rel="noopener" role="button" target="_blank" title="Visit my website">Visit website »</a></p>
</div>
<div class="col-lg-6">
<h2 class="h3">Blog</h2>
<p>I occasionally blog about topics related to .NET development.</p>
<p><a id="link-blog" href="@options.ExternalLinks?.Blog?.AbsoluteUri" class="btn btn-lg btn-primary" rel="noopener" role="button" target="_blank" title="Visit my blog">Visit blog »</a></p>
</div>
</div>
| @using System.Reflection
@{
ViewBag.Title = "Home Page";
string? mvcVersion = typeof(Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions)
.Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
SiteOptions options = Options.Value;
}
<div class="jumbotron">
<h1>Martin Costello's API</h1>
<p class="lead">
This website is an excercise in the use of ASP.NET @Environment.Version.ToString(2) for a website and REST API.
</p>
</div>
<div>
<p>
This website is hosted in <a href="https://azure.microsoft.com" rel="noopener" target="_blank" title="Microsoft Azure">Microsoft Azure</a>
and the source code can be found on <a href="@options.Metadata?.Repository" rel="noopener" target="_blank" title="This application's GitHub repository">GitHub</a>.
</p>
<p>
It is currently running <a href="https://github.com/dotnet/aspnetcore/tree/@(mvcVersion?.Split('+').ElementAtOrDefault(1) ?? "master")" rel="noopener" target="_blank" title="ASP.NET on GitHub">ASP.NET @(mvcVersion?.Split('+').FirstOrDefault())</a>.
</p>
</div>
<div class="row">
<div class="col-lg-6">
<h2 class="h3">Website</h2>
<p>My main website.</p>
<p><a id="link-website" href="@options.Metadata?.Author?.Website" class="btn btn-lg btn-primary" rel="noopener" role="button" target="_blank" title="Visit my website">Visit website »</a></p>
</div>
<div class="col-lg-6">
<h2 class="h3">Blog</h2>
<p>I occasionally blog about topics related to .NET development.</p>
<p><a id="link-blog" href="@options.ExternalLinks?.Blog?.AbsoluteUri" class="btn btn-lg btn-primary" rel="noopener" role="button" target="_blank" title="Visit my blog">Visit blog »</a></p>
</div>
</div>
| mit | C# |
ac41301a08a702f8739e74977debebfd7c800fc9 | update test | keithjjones/ArinWhois.NET,MaxHorstmann/ArinWhois.NET | src/ArinWhois.Tests/ApiTests.cs | src/ArinWhois.Tests/ApiTests.cs | using System;
using System.Net;
using ArinWhois.Client;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArinWhois.Tests
{
[TestClass]
public class ApiTests
{
[TestMethod]
public void TestNetwork()
{
var arinClient = new ArinClient();
var response = arinClient.QueryAsync(IPAddress.Parse("69.63.176.0")).Result;
Assert.IsNotNull(response.Network);
Assert.IsNotNull(response.Organization);
Assert.IsNotNull(response.PointOfContact);
Assert.IsTrue(response.Network.TermsOfUse.StartsWith("http"));
Assert.IsNotNull(response.Network.RegistrationDate.Value);
Assert.IsNotNull(response.Network.NetBlocks.NetBlock);
Assert.IsNotNull(response.Network.NetBlocks.NetBlock.CidrLength.Value);
Assert.IsNotNull(response.Network.NetBlocks.NetBlock.Description);
}
}
}
| using System;
using System.Net;
using ArinWhois.Client;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArinWhois.Tests
{
[TestClass]
public class ApiTests
{
[TestMethod]
public void TestNetwork()
{
var arinClient = new ArinClient();
// http://whois.arin.net/rest/net/NET-69-63-176-0-1/pft.json
// sync over async, ok for test. http://blogs.msdn.com/b/pfxteam/archive/2012/04/13/10293638.aspx
var response = arinClient.QueryAsync(IPAddress.Parse("69.63.176.0")).Result;
Assert.IsNotNull(response.Network);
Assert.IsNotNull(response.Organization);
Assert.IsNotNull(response.PointOfContact);
Assert.IsTrue(response.Network.TermsOfUse.StartsWith("http"));
Assert.IsNotNull(response.Network.RegistrationDate.Value);
Assert.IsNotNull(response.Network.NetBlocks.NetBlock);
Assert.IsNotNull(response.Network.NetBlocks.NetBlock.CidrLength.Value);
Assert.IsNotNull(response.Network.NetBlocks.NetBlock.Description);
}
}
}
| mit | C# |
c98c761a8024de92a94c4ba060629d62c9505159 | Update code generator relative filepath | xoofx/SharpScss,xoofx/SharpScss | src/LibSassGen/CodeGenerator.cs | src/LibSassGen/CodeGenerator.cs | using System;
using System.IO;
namespace LibSassGen
{
public partial class CodeGenerator
{
private const string DefaultIncludeDir = @"../../../../libsass/include";
private const string DefaultOutputFilePath = @"../../../SharpScss/LibSass.Generated.cs";
private const int IndentMultiplier = 4;
private int _indentLevel;
private TextWriter _writer;
private TextWriter _writerBody;
private TextWriter _writerGlobal;
public bool OutputToConsole { get; set; }
public void Run()
{
var outputFilePath = Path.Combine(Environment.CurrentDirectory, DefaultOutputFilePath);
outputFilePath = Path.GetFullPath(outputFilePath);
_writerGlobal = new StringWriter();
_writerBody = new StringWriter();
ParseAndWrite();
var finalWriter = OutputToConsole
? Console.Out
: new StreamWriter(outputFilePath);
finalWriter.Write(_writerGlobal);
if (!OutputToConsole)
{
finalWriter.Flush();
finalWriter.Dispose();
finalWriter = null;
}
}
}
}
| using System;
using System.IO;
namespace LibSassGen
{
public partial class CodeGenerator
{
private const string DefaultIncludeDir = @"../../../../../libsass/include";
private const string DefaultOutputFilePath = @"../../../../SharpScss/LibSass.Generated.cs";
private const int IndentMultiplier = 4;
private int _indentLevel;
private TextWriter _writer;
private TextWriter _writerBody;
private TextWriter _writerGlobal;
public bool OutputToConsole { get; set; }
public void Run()
{
var outputFilePath = Path.Combine(Environment.CurrentDirectory, DefaultOutputFilePath);
outputFilePath = Path.GetFullPath(outputFilePath);
_writerGlobal = new StringWriter();
_writerBody = new StringWriter();
ParseAndWrite();
var finalWriter = OutputToConsole
? Console.Out
: new StreamWriter(outputFilePath);
finalWriter.Write(_writerGlobal);
if (!OutputToConsole)
{
finalWriter.Flush();
finalWriter.Dispose();
finalWriter = null;
}
}
}
}
| bsd-2-clause | C# |
baa2ab8aab8c0cf670295c4b9da01e708833b549 | Update RoundRobin.cs | tomliversidge/protoactor-dotnet,tomliversidge/protoactor-dotnet,masteryee/protoactor-dotnet,AsynkronIT/protoactor-dotnet,masteryee/protoactor-dotnet | src/Proto.Cluster/RoundRobin.cs | src/Proto.Cluster/RoundRobin.cs | using System.Threading;
namespace Proto.Cluster
{
public class RoundRobin
{
private int _val;
private IMemberStrategy _m;
public RoundRobin(IMemberStrategy m)
{
this._m = m;
}
public string GetNode()
{
var members = _m.GetAllMembers();
var l = members.Count;
if (l == 0) return "";
if (l == 1) return members[0].Address;
var nv = Interlocked.Increment(ref _val);
return members[nv % l].Address;
}
}
}
| using System.Threading;
namespace Proto.Cluster
{
public class RoundRobin
{
private int _val;
private IMemberStrategy _m;
public RoundRobin(IMemberStrategy m)
{
this._m = m;
}
public string GetNode()
{
var members = _m.GetAllMembers();
var l = members.Count;
if (l == 0) return "";
if (l == 1) return members[0].Address;
Interlocked.Increment(ref _val);
return members[_val % l].Address;
}
}
} | apache-2.0 | C# |
434ebfb36353ff4f120a35314e3d9a90b6214144 | remove unused header | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen/DashboardBuilder.cs | Dashen/DashboardBuilder.cs | using Dashen.Components;
using StructureMap;
namespace Dashen
{
public class DashboardBuilder
{
public static Dashboard Create(DashboardConfiguration configuration)
{
var container = new Container(config =>
{
config.Scan(a =>
{
a.AssemblyContainingType<Dashboard>();
a.WithDefaultConventions();
a.AddAllTypesOf(typeof(Component<>));
});
config.For<DashboardConfiguration>().Use(configuration);
config.For<View>().Singleton();
config.For<ModelInfoRepository>().Singleton();
});
var dash = container.GetInstance<Dashboard>();
dash.Add<HeaderModel>(model =>
{
model.AppName = configuration.ApplicationName;
model.AppVersion = configuration.ApplicationVersion;
});
dash.Add<FooterModel>(model =>
{
model.DashenVersion = typeof(Dashboard).Assembly.GetName().Version.ToString();
});
return dash;
}
}
}
| using Dashen.Components;
using StructureMap;
namespace Dashen
{
public class DashboardBuilder
{
public static Dashboard Create(DashboardConfiguration configuration)
{
var container = new Container(config =>
{
config.Scan(a =>
{
a.AssemblyContainingType<Dashboard>();
a.WithDefaultConventions();
a.AddAllTypesOf(typeof(Component<>));
});
config.For<DashboardConfiguration>().Use(configuration);
config.For<View>().Singleton();
config.For<ModelInfoRepository>().Singleton();
});
var dash = container.GetInstance<Dashboard>();
dash.Add<HeaderModel>(model =>
{
model.Title = "ERMAGHAD";
model.AppName = configuration.ApplicationName;
model.AppVersion = configuration.ApplicationVersion;
});
dash.Add<FooterModel>(model =>
{
model.DashenVersion = typeof(Dashboard).Assembly.GetName().Version.ToString();
});
return dash;
}
}
}
| lgpl-2.1 | C# |
28fb1221601afdf629420509ae4147953aa9c3b4 | Make main program class static | printerpam/purpleonion,neoeinstein/purpleonion,printerpam/purpleonion | src/Xpdm.PurpleOnion/Program.cs | src/Xpdm.PurpleOnion/Program.cs | using System;
using System.IO;
using System.Security.Cryptography;
using Mono.Security;
using Mono.Security.Cryptography;
namespace Xpdm.PurpleOnion
{
static class Program
{
private static void Main()
{
long count = 0;
while (true)
{
RSA pki = RSA.Create();
ASN1 asn = RSAExtensions.ToAsn1Key(pki);
byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes());
string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant();
if (onion.Contains("tor") || onion.Contains("mirror"))
{
Console.WriteLine("Found: " + onion);
Directory.CreateDirectory(onion);
File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true));
File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki)));
File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion");
}
Console.WriteLine(onion + " " + ++count);
}
}
}
}
| using System;
using System.IO;
using System.Security.Cryptography;
using Mono.Security;
using Mono.Security.Cryptography;
namespace Xpdm.PurpleOnion
{
class Program
{
private static void Main()
{
long count = 0;
while (true)
{
RSA pki = RSA.Create();
ASN1 asn = RSAExtensions.ToAsn1Key(pki);
byte[] hash = SHA1CryptoServiceProvider.Create().ComputeHash(asn.GetBytes());
string onion = ConvertExtensions.FromBytesToBase32String(hash).Substring(0,16).ToLowerInvariant();
if (onion.Contains("tor") || onion.Contains("mirror"))
{
Console.WriteLine("Found: " + onion);
Directory.CreateDirectory(onion);
File.WriteAllText(Path.Combine(onion, "pki.xml"), pki.ToXmlString(true));
File.WriteAllText(Path.Combine(onion, "private_key"), System.Convert.ToBase64String(PKCS8.PrivateKeyInfo.Encode(pki)));
File.WriteAllText(Path.Combine(onion, "hostname"), onion + ".onion");
}
Console.WriteLine(onion + " " + ++count);
}
}
}
}
| bsd-3-clause | C# |
5e748e1bb2209c6909156e72338c96afe612eb3d | Fix #9 | farity/farity | Farity/DefaultTo.cs | Farity/DefaultTo.cs | using System.Linq;
using System.Collections.Generic;
namespace Farity
{
public static partial class F
{
/// <summary>
/// Returns the elements of the specified sequence or the specified value in a singleton collection
/// if the sequence is (null or) empty.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="value">The default value.</param>
/// <param name="source">The sequence to operate on.</param>
/// <returns>The elements of the specified sequence, or the specified value in a singleton collection
/// if the sequence is (null or) empty.</returns>
public static IEnumerable<T> DefaultTo<T>(T value, IEnumerable<T> source)
=> (source ?? Enumerable.Empty<T>()).DefaultIfEmpty(value);
}
}
| using System.Linq;
using System.Collections.Generic;
namespace Farity
{
public static partial class F
{
/// <summary>
/// Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.
/// </summary>
/// <typeparam name="T">The type of elements in the sequence.</typeparam>
/// <param name="value">The default value.</param>
/// <param name="source">The sequence to operate on.</param>
/// <returns>The elements of the specified sequence, or the specified value in a singleton collection if the sequence is empty.</returns>
public static IEnumerable<T> DefaultTo<T>(T value, IEnumerable<T> source) => source.DefaultIfEmpty(value);
}
}
| mit | C# |
fe925231bbf3f6c546fdccbf9a8844db88768f0d | Allow path-specific invocation | timotei/NUnit3Migration | NUnit3Migration/Program.cs | NUnit3Migration/Program.cs | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Text;
using NUnit3Migration.Processors;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NUnit3Migration
{
public class Program
{
private static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Need first argument a path to the directory in which to search recursively .cs files");
Environment.Exit(1);
}
new Program().Run(args[0]).Wait();
}
private readonly List<IProcessor> _syntaxNodeProcessors = new List<IProcessor>
{
new TestCaseAttributeProcessor()
};
private async Task Run(string path)
{
foreach (var fsEntry in Directory.EnumerateFileSystemEntries(path))
{
if (Directory.Exists(fsEntry))
{
await Run(fsEntry);
}
else if (".cs" == Path.GetExtension(fsEntry))
{
Console.WriteLine($"Processing {fsEntry} ...");
var originalStr = File.ReadAllText(fsEntry);
File.WriteAllText(fsEntry, await Process(_syntaxNodeProcessors, originalStr));
}
}
}
public static async Task<string> Process(IEnumerable<IProcessor> processors, string inputSource)
{
var workspace = new AdhocWorkspace();
string projName = "NewProject";
var projectId = ProjectId.CreateNewId();
var versionStamp = VersionStamp.Create();
var projectInfo = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
var newProject = workspace.AddProject(projectInfo);
workspace.AddDocument(newProject.Id, "NewFile.cs", SourceText.From(inputSource));
var document = workspace.CurrentSolution.Projects.First().Documents.First();
DocumentEditor editor = await DocumentEditor.CreateAsync(document);
foreach (var processor in processors)
{
processor.Process(editor);
}
return (await editor.GetChangedDocument().GetTextAsync()).ToString();
}
}
}
| using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Text;
using NUnit3Migration.Processors;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace NUnit3Migration
{
public class Program
{
private static void Main(string[] args)
{
new Program().Run().Wait();
}
private readonly List<IProcessor> _syntaxNodeProcessors = new List<IProcessor>
{
new TestCaseAttributeProcessor()
};
private async Task Run()
{
string path = @"F:\src\ullink\git\ul-trader-extension\" +
"desk/extension/test/legacy/ultrader.test/OrderEntryTests/ULOrderEntryFormBooksTests.cs";
var originalStr = File.ReadAllText(path);
File.WriteAllText(path, await Process(_syntaxNodeProcessors, originalStr));
}
public static async Task<string> Process(IEnumerable<IProcessor> processors, string inputSource)
{
var workspace = new AdhocWorkspace();
string projName = "NewProject";
var projectId = ProjectId.CreateNewId();
var versionStamp = VersionStamp.Create();
var projectInfo = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
var newProject = workspace.AddProject(projectInfo);
workspace.AddDocument(newProject.Id, "NewFile.cs", SourceText.From(inputSource));
var document = workspace.CurrentSolution.Projects.First().Documents.First();
DocumentEditor editor = await DocumentEditor.CreateAsync(document);
foreach (var processor in processors)
{
processor.Process(editor);
}
return (await editor.GetChangedDocument().GetTextAsync()).ToString();
}
}
}
| mit | C# |
a0b6d81c838b5b4663526d826f57fbe4febc1ac0 | Increment minor version | ashleydavis/RSG.UnityApp,Real-Serious-Games/RSG.UnityApp | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RSG.UnityApp")]
[assembly: AssemblyDescription("Basis for Unity applications")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Real Serious Games")]
[assembly: AssemblyProduct("RSG.Unity")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("12fda625-867c-4745-b2ec-512e8ff78554")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RSG.UnityApp")]
[assembly: AssemblyDescription("Basis for Unity applications")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Real Serious Games")]
[assembly: AssemblyProduct("RSG.Unity")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("12fda625-867c-4745-b2ec-512e8ff78554")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.4.4.0")]
[assembly: AssemblyFileVersion("0.4.4.0")]
| mit | C# |
f5ab8620110795a675ffbad86f687ae07ad99353 | Bump version | Yuisbean/WebMConverter,nixxquality/WebMConverter,o11c/WebMConverter | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.16.7")]
| 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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.16.6")]
| mit | C# |
b743144fd9a9789a5c389bf880e4db663324de43 | change scan method to a bool | DMagic1/Orbital-Science,Kerbas-ad-astra/Orbital-Science | Source/DMAnomalyStorage.cs | Source/DMAnomalyStorage.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace DMagic
{
public class DMAnomalyStorage
{
private CelestialBody body;
private bool scanned;
//private bool updated;
private Dictionary<string, DMAnomalyObject> anomalies = new Dictionary<string, DMAnomalyObject>();
public DMAnomalyStorage(CelestialBody b, bool s = true)
{
body = b;
scanned = s;
}
public void addAnomaly(DMAnomalyObject anom)
{
if (!anomalies.ContainsKey(anom.Name))
anomalies.Add(anom.Name, anom);
}
//public void updateAnomalyCity(PQSCity city)
//{
// DMAnomalyObject anom = anomalies.FirstOrDefault(a => a.Name == city.name);
// if (anom == null)
// return;
// anom.addPQSCity(city);
//}
public bool scanBody()
{
scanned = true;
if (body.pqsController == null)
return false;
PQSCity[] Cities = body.pqsController.GetComponentsInChildren<PQSCity>();
for (int i = 0; i < Cities.Length; i++)
{
PQSCity city = Cities[i];
if (city == null)
continue;
if (city.transform.parent.name != body.name)
continue;
DMAnomalyObject anom = new DMAnomalyObject(city);
addAnomaly(anom);
}
return true;
}
public DMAnomalyObject getAnomaly(string name)
{
if (anomalies.ContainsKey(name))
return anomalies[name];
return null;
}
public DMAnomalyObject getAnomaly(int index)
{
if (anomalies.Count > index)
return anomalies.ElementAt(index).Value;
return null;
}
public CelestialBody Body
{
get { return body; }
}
public bool Scanned
{
get { return scanned; }
}
//public bool Updated
//{
// get { return updated; }
// set { updated = value; }
//}
public int AnomalyCount
{
get { return anomalies.Count; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace DMagic
{
public class DMAnomalyStorage
{
private CelestialBody body;
private bool scanned;
private bool updated;
private Dictionary<string, DMAnomalyObject> anomalies = new Dictionary<string, DMAnomalyObject>();
public DMAnomalyStorage(CelestialBody b, bool s)
{
body = b;
scanned = s;
}
public void addAnomaly(DMAnomalyObject anom)
{
if (!anomalies.ContainsKey(anom.Name))
anomalies.Add(anom.Name, anom);
}
//public void updateAnomalyCity(PQSCity city)
//{
// DMAnomalyObject anom = anomalies.FirstOrDefault(a => a.Name == city.name);
// if (anom == null)
// return;
// anom.addPQSCity(city);
//}
public void scanBody()
{
scanned = true;
if (body.pqsController == null)
return;
PQSCity[] Cities = body.pqsController.GetComponentsInChildren<PQSCity>();
for (int i = 0; i < Cities.Length; i++)
{
PQSCity city = Cities[i];
if (city == null)
continue;
if (city.transform.parent.name != body.name)
continue;
DMAnomalyObject anom = new DMAnomalyObject(city);
addAnomaly(anom);
}
}
public DMAnomalyObject getAnomaly(string name)
{
if (anomalies.ContainsKey(name))
return anomalies[name];
return null;
}
public DMAnomalyObject getAnomaly(int index)
{
if (anomalies.Count > index)
return anomalies.ElementAt(index).Value;
return null;
}
public CelestialBody Body
{
get { return body; }
}
public bool Scanned
{
get { return scanned; }
}
public bool Updated
{
get { return updated; }
set { updated = value; }
}
public int AnomalyCount
{
get { return anomalies.Count; }
}
}
}
| bsd-3-clause | C# |
9a9eb39f65535f3c7a84a30f1c7fedb7bd125d30 | Bump version | rileywhite/Cilador | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | /***************************************************************************/
// Copyright 2013-2014 Riley White
//
// 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.Reflection;
[assembly: AssemblyCompany("Riley White")]
[assembly: AssemblyProduct("Bix.Mixers.Fody")]
[assembly: AssemblyCopyright("Copyright © Riley White 2013-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion(CommonAssemblyInfo.Version)]
[assembly: AssemblyFileVersion(CommonAssemblyInfo.Version)]
internal static class CommonAssemblyInfo
{
public const string Version = "0.1.1.0";
} | /***************************************************************************/
// Copyright 2013-2014 Riley White
//
// 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.Reflection;
[assembly: AssemblyCompany("Riley White")]
[assembly: AssemblyProduct("Bix.Mixers.Fody")]
[assembly: AssemblyCopyright("Copyright © Riley White 2013-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion(CommonAssemblyInfo.Version)]
[assembly: AssemblyFileVersion(CommonAssemblyInfo.Version)]
internal static class CommonAssemblyInfo
{
public const string Version = "0.1.0.0";
} | apache-2.0 | C# |
2755a47f35db149a4f9476eea7af85948db10810 | Change B.O.U.N.C.E. sound. | fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game | game/server/weapons/repel.sfx.cs | game/server/weapons/repel.sfx.cs | //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
datablock AudioProfile(RepelExplosionSound)
{
filename = "share/sounds/rotc/explosion8.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(RepelHitSound)
{
filename = "share/sounds/rotc/explosion6.wav";
description = AudioDefault3DLouder;
preload = true;
};
| //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
datablock AudioProfile(RepelExplosionSound)
{
filename = "share/sounds/rotc/explosion10.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(RepelHitSound)
{
filename = "share/sounds/rotc/explosion6.wav";
description = AudioDefault3DLouder;
preload = true;
};
| lgpl-2.1 | C# |
88175fc7a9be7d5d9457de4c53014cd26bc8cbde | Add LeagueId property (#25) | aj-r/RiotNet | RiotNet/Models/LeaguePosition.cs | RiotNet/Models/LeaguePosition.cs | namespace RiotNet.Models
{
/// <summary>
/// Contains league participant information representing a summoner. Also contains information about the legue containing this entry.
/// </summary>
public class LeaguePosition : LeagueItem
{
/// <summary>
/// Gets or sets the ID of the league.
/// </summary>
public string LeagueId { get; set; }
/// <summary>
/// Gets or sets the name of the league.
/// </summary>
public string LeagueName { get; set; }
/// <summary>
/// Gets or sets the league's queue type. This should equal one of the <see cref="RankedQueue"/> values.
/// </summary>
public string QueueType { get; set; }
/// <summary>
/// Gets or sets the league's tier. This should equal one of the <see cref="Models.Tier"/> values.
/// </summary>
public string Tier { get; set; }
}
}
| namespace RiotNet.Models
{
/// <summary>
/// Contains league participant information representing a summoner. Also contains information about the legue containing this entry.
/// </summary>
public class LeaguePosition : LeagueItem
{
/// <summary>
/// Gets or sets the name of the league.
/// </summary>
public string LeagueName { get; set; }
/// <summary>
/// Gets or sets the league's queue type. This should equal one of the <see cref="RankedQueue"/> values.
/// </summary>
public string QueueType { get; set; }
/// <summary>
/// Gets or sets the league's tier. This should equal one of the <see cref="Models.Tier"/> values.
/// </summary>
public string Tier { get; set; }
}
}
| mit | C# |
034b8d3450767ef178b573d73fa3f43be3946175 | add wherefragment overload that allows for per-fragment templateing customization | JasperFx/Marten,jokokko/marten,jamesfarrer/marten,tim-cools/Marten,jokokko/marten,jokokko/marten,mdissel/Marten,jmbledsoe/marten,jmbledsoe/marten,jmbledsoe/marten,JasperFx/Marten,jamesfarrer/marten,ericgreenmix/marten,ericgreenmix/marten,mysticmind/marten,tim-cools/Marten,jmbledsoe/marten,mysticmind/marten,mdissel/Marten,JasperFx/Marten,jamesfarrer/marten,jokokko/marten,jamesfarrer/marten,mysticmind/marten,mysticmind/marten,ericgreenmix/marten,tim-cools/Marten,jokokko/marten,ericgreenmix/marten,jmbledsoe/marten | src/Marten/Linq/WhereFragment.cs | src/Marten/Linq/WhereFragment.cs | using Baseline;
using Marten.Util;
using Npgsql;
namespace Marten.Linq
{
public class WhereFragment : IWhereFragment
{
private readonly string _sql;
private readonly object[] _parameters;
private readonly string _token;
public WhereFragment(string sql, params object[] parameters) : this(sql, "?", parameters) { }
public WhereFragment(string sql, string paramReplacementToken, params object[] parameters)
{
_sql = sql;
_parameters = parameters;
_token = paramReplacementToken;
}
public string ToSql(NpgsqlCommand command)
{
var sql = _sql;
_parameters.Each(x =>
{
var param = command.AddParameter(x);
sql = sql.ReplaceFirst(_token, ":" + param.ParameterName);
});
return sql;
}
public bool Contains(string sqlText)
{
return _sql.Contains(sqlText);
}
}
} | using System.Collections.Generic;
using Baseline;
using Marten.Util;
using Npgsql;
namespace Marten.Linq
{
public class WhereFragment : IWhereFragment
{
private readonly string _sql;
private readonly object[] _parameters;
public WhereFragment(string sql, params object[] parameters)
{
_sql = sql;
_parameters = parameters;
}
public string ToSql(NpgsqlCommand command)
{
var sql = _sql;
_parameters.Each(x =>
{
var param = command.AddParameter(x);
sql = sql.ReplaceFirst("?", ":" + param.ParameterName);
});
return sql;
}
public bool Contains(string sqlText)
{
return _sql.Contains(sqlText);
}
}
} | mit | C# |
ce912b9ad3bd47caee9312cd2dc47ea97e158249 | put #if UNITY_EDITOR guards around this editor script, because in certain folder arrangements and/or when building a DLL, Unity can erroneously try to include this script in the game build. | foolhuang/XUPorter,trampliu/XUPorter,karlgluck/XUPorter,onevcat/XUPorter,zhutaorun/XUPorter,sq5gvm/XUPorter,maoi/XUPorter | XCodePostProcess.cs | XCodePostProcess.cs | using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.XCodeEditor;
#endif
using System.IO;
public static class XCodePostProcess
{
#if UNITY_EDITOR
[PostProcessBuild]
public static void OnPostProcessBuild( BuildTarget target, string path )
{
if (target != BuildTarget.iPhone) {
Debug.LogWarning("Target is not iPhone. XCodePostProcess will not run");
return;
}
// Create a new project object from build target
XCProject project = new XCProject( path );
// Find and run through all projmods files to patch the project.
//Please pay attention that ALL projmods files in your project folder will be excuted!
string[] files = Directory.GetFiles( Application.dataPath, "*.projmods", SearchOption.AllDirectories );
foreach( string file in files ) {
project.ApplyMod( file );
}
// Finally save the xcode project
project.Save();
}
#endif
} | using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.XCodeEditor;
using System.IO;
public static class XCodePostProcess
{
[PostProcessBuild]
public static void OnPostProcessBuild( BuildTarget target, string path )
{
if (target != BuildTarget.iPhone) {
Debug.LogWarning("Target is not iPhone. XCodePostProcess will not run");
return;
}
// Create a new project object from build target
XCProject project = new XCProject( path );
// Find and run through all projmods files to patch the project.
//Please pay attention that ALL projmods files in your project folder will be excuted!
string[] files = Directory.GetFiles( Application.dataPath, "*.projmods", SearchOption.AllDirectories );
foreach( string file in files ) {
project.ApplyMod( file );
}
// Finally save the xcode project
project.Save();
}
} | mit | C# |
836d7e008a52e977403d94f40e316e2123aeee75 | Bump version. | mios-fi/mios.payment | core/Properties/AssemblyInfo.cs | core/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("Mios.Payment")]
[assembly: AssemblyDescription("A library for generating and verifying payment details for various online payment providers")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mios Ltd")]
[assembly: AssemblyProduct("Mios.Payment")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("90888035-e560-4ab7-bcc5-c88aee09f29b")]
// 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.7.0")]
[assembly: AssemblyFileVersion("1.0.7.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("Mios.Payment")]
[assembly: AssemblyDescription("A library for generating and verifying payment details for various online payment providers")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mios Ltd")]
[assembly: AssemblyProduct("Mios.Payment")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("90888035-e560-4ab7-bcc5-c88aee09f29b")]
// 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.6.0")]
[assembly: AssemblyFileVersion("1.0.6.0")]
| bsd-2-clause | C# |
83c34cc7608c21f2d5a62b2783e22040f03d159d | Update Cake.Issues | cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe | Cake.Recipe/Content/addins.cake | Cake.Recipe/Content/addins.cake | ///////////////////////////////////////////////////////////////////////////////
// ADDINS
///////////////////////////////////////////////////////////////////////////////
#addin nuget:?package=Cake.Codecov&version=0.5.0
#addin nuget:?package=Cake.Coveralls&version=0.9.0
#addin nuget:?package=Cake.Figlet&version=1.2.0
#addin nuget:?package=Cake.Git&version=0.19.0
#addin nuget:?package=Cake.Gitter&version=0.10.0
#addin nuget:?package=Cake.Graph&version=0.8.0
#addin nuget:?package=Cake.Incubator&version=4.0.2
#addin nuget:?package=Cake.Kudu&version=0.8.0
#addin nuget:?package=Cake.MicrosoftTeams&version=0.8.0
#addin nuget:?package=Cake.ReSharperReports&version=0.10.0
#addin nuget:?package=Cake.Slack&version=0.13.0
#addin nuget:?package=Cake.Transifex&version=0.7.0
#addin nuget:?package=Cake.Twitter&version=0.9.0
#addin nuget:?package=Cake.Wyam&version=2.2.4
#addin nuget:?package=Cake.Issues&version=0.7.0
#addin nuget:?package=Cake.Issues.MsBuild&version=0.7.0
#addin nuget:?package=Cake.Issues.InspectCode&version=0.7.1
#addin nuget:?package=Cake.Issues.Reporting&version=0.7.0
#addin nuget:?package=Cake.Issues.Reporting.Generic&version=0.7.0
Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => {
var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid())));
try
{
System.IO.File.WriteAllText(script.FullPath, code);
var arguments = new Dictionary<string, string>();
if(BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) {
arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient"));
}
if(BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) {
arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification"));
}
CakeExecuteScript(script,
new CakeSettings
{
EnvironmentVariables = envVars,
Arguments = arguments
});
}
finally
{
if (FileExists(script))
{
DeleteFile(script);
}
}
};
| ///////////////////////////////////////////////////////////////////////////////
// ADDINS
///////////////////////////////////////////////////////////////////////////////
#addin nuget:?package=Cake.Codecov&version=0.5.0
#addin nuget:?package=Cake.Coveralls&version=0.9.0
#addin nuget:?package=Cake.Figlet&version=1.2.0
#addin nuget:?package=Cake.Git&version=0.19.0
#addin nuget:?package=Cake.Gitter&version=0.10.0
#addin nuget:?package=Cake.Graph&version=0.8.0
#addin nuget:?package=Cake.Incubator&version=4.0.2
#addin nuget:?package=Cake.Kudu&version=0.8.0
#addin nuget:?package=Cake.MicrosoftTeams&version=0.8.0
#addin nuget:?package=Cake.ReSharperReports&version=0.10.0
#addin nuget:?package=Cake.Slack&version=0.13.0
#addin nuget:?package=Cake.Transifex&version=0.7.0
#addin nuget:?package=Cake.Twitter&version=0.9.0
#addin nuget:?package=Cake.Wyam&version=2.2.4
#addin nuget:?package=Cake.Issues&version=0.6.2
#addin nuget:?package=Cake.Issues.MsBuild&version=0.6.3
#addin nuget:?package=Cake.Issues.InspectCode&version=0.6.1
#addin nuget:?package=Cake.Issues.Reporting&version=0.6.1
#addin nuget:?package=Cake.Issues.Reporting.Generic&version=0.6.2
Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => {
var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid())));
try
{
System.IO.File.WriteAllText(script.FullPath, code);
var arguments = new Dictionary<string, string>();
if(BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) {
arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient"));
}
if(BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) {
arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification"));
}
CakeExecuteScript(script,
new CakeSettings
{
EnvironmentVariables = envVars,
Arguments = arguments
});
}
finally
{
if (FileExists(script))
{
DeleteFile(script);
}
}
};
| mit | C# |
3a2eaa280815cce4c35c5403f1c12e27c4a3994a | Fix order for key columns on Feature | basp/aegis | Aegis.Cfg/Feature.cs | Aegis.Cfg/Feature.cs | namespace Aegis.Cfg
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
using System.Linq;
public class Feature : IFeature
{
public Feature()
{
this.FieldValues = new List<FieldValue>();
}
[Key]
[Column(Order = 1)]
public int Index
{
get;
set;
}
[Key]
[Column(Order = 2)]
public int LayerId
{
get;
set;
}
internal virtual ICollection<FieldValue> FieldValues
{
get;
private set;
}
protected virtual DbGeometry Geometry
{
get;
private set;
}
public virtual double GetFieldAsDouble(int index)
{
var v = (DoubleValue)this.FieldValues.ElementAt(index);
return v.Double;
}
public virtual int GetFieldAsInt(int index)
{
throw new NotImplementedException();
}
public virtual long GetFieldAsInt64(int index)
{
var v = (LongValue)this.FieldValues.ElementAt(index);
return v.Long;
}
public virtual string GetFieldAsString(int index) =>
this.FieldValues.ElementAt(index).ToString();
public virtual IGeometry GetGeometry()
{
return new GeometryAdapter(this.Geometry);
}
}
}
| namespace Aegis.Cfg
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
using System.Linq;
public class Feature : IFeature
{
public Feature()
{
this.FieldValues = new List<FieldValue>();
}
[Key]
[Column(Order = 2)]
public int Index
{
get;
set;
}
[Key]
[Column(Order = 1)]
public int LayerId
{
get;
set;
}
internal virtual ICollection<FieldValue> FieldValues
{
get;
private set;
}
protected virtual DbGeometry Geometry
{
get;
private set;
}
public virtual double GetFieldAsDouble(int index)
{
var v = (DoubleValue)this.FieldValues.ElementAt(index);
return v.Double;
}
public virtual int GetFieldAsInt(int index)
{
throw new NotImplementedException();
}
public virtual long GetFieldAsInt64(int index)
{
var v = (LongValue)this.FieldValues.ElementAt(index);
return v.Long;
}
public virtual string GetFieldAsString(int index) =>
this.FieldValues.ElementAt(index).ToString();
public virtual IGeometry GetGeometry()
{
return new GeometryAdapter(this.Geometry);
}
}
}
| mit | C# |
2d14cfcd4dcf090fc184175abf08bcbfb75a897f | Accumulate forces, not accelerations. | drewnoakes/boing | Boing/Node.cs | Boing/Node.cs | namespace Boing
{
public sealed class Node
{
private Vector2f _force;
public string Id { get; }
public float Mass { get; set; }
public float Damping { get; set; }
public bool IsPinned { get; set; }
public object Tag { get; set; }
public Vector2f Position { get; set; }
public Vector2f Velocity { get; private set; }
public Node(string id, float mass = 1.0f, float damping = 0.5f, Vector2f? position = null)
{
Id = id;
Mass = mass;
Damping = damping;
Position = position ?? Vector2f.Random();
}
public void ApplyForce(Vector2f force)
{
// Accumulate force
_force += force;
}
public void Update(float dt)
{
// Update velocity
Velocity += _force/Mass*dt;
Velocity *= Damping;
// Update position
Position += Velocity*dt;
// Clear acceleration
_force = Vector2f.Zero;
}
}
} | namespace Boing
{
public sealed class Node
{
private Vector2f _acceleration;
public string Id { get; }
public float Mass { get; set; }
public float Damping { get; set; }
public bool IsPinned { get; set; }
public object Tag { get; set; }
public Vector2f Position { get; set; }
public Vector2f Velocity { get; private set; }
public Node(string id, float mass = 1.0f, float damping = 0.5f, Vector2f? position = null)
{
Id = id;
Mass = mass;
Damping = damping;
Position = position ?? Vector2f.Random();
}
public void ApplyForce(Vector2f force)
{
// Accumulate acceleration
_acceleration += force/Mass;
}
public void Update(float dt)
{
// Update velocity
Velocity += _acceleration*dt;
Velocity *= Damping;
// Update position
Position += Velocity*dt;
// Clear acceleration
_acceleration = Vector2f.Zero;
}
}
} | apache-2.0 | C# |
ea01e4ada082cd380c2df4e276aaa1015983d7bf | Fix compilation for the compact framework | sailro/cecil | Mono/Empty.cs | Mono/Empty.cs | //
// Empty.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Collections.Generic;
namespace Mono {
static class Empty<T> {
public static readonly T [] Array = new T [0];
}
}
namespace Mono.Cecil {
static partial class Mixin {
public static bool IsNullOrEmpty<T> (this T [] self)
{
return self == null || self.Length == 0;
}
public static bool IsNullOrEmpty<T> (this Collection<T> self)
{
return self == null || self.size == 0;
}
public static T [] Resize<T> (this T [] self, int length)
{
#if !CF
Array.Resize (ref self, length);
#else
var copy = new T [length];
Array.Copy (self, copy, self.Length);
self = copy;
#endif
return self;
}
}
}
| //
// Empty.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Collections.Generic;
namespace Mono {
static class Empty<T> {
public static readonly T [] Array = new T [0];
}
}
namespace Mono.Cecil {
static partial class Mixin {
public static bool IsNullOrEmpty<T> (this T [] self)
{
return self == null || self.Length == 0;
}
public static bool IsNullOrEmpty<T> (this Collection<T> self)
{
return self == null || self.size == 0;
}
public static T [] Resize<T> (this T [] self, int length)
{
#if !CF
Array.Resize (ref self, length);
#else
var copy = new T [length];
Array.Copy (self, copy, self.Length);
array = copy;
#endif
return self;
}
}
}
| mit | C# |
eb06195fbf397784cd529ca4939963f40efa92d3 | Set spawn height for soldiers to 20m | TomAlanCarroll/agent-search-and-rescue,TomAlanCarroll/agent-search-and-rescue,TomAlanCarroll/agent-search-and-rescue | Assets/Scripts/SpawnController.cs | Assets/Scripts/SpawnController.cs | using UnityEngine;
public class SpawnController : MonoBehaviour {
public GameObject friendlySoldierPrefab;
public GameObject dronePrefab;
// Constants
public const int NUM_DRONES = 10;
public const int MIN_SOLDIERS_PER_BUILDING = 8;
public const int MAX_SOLDIERS_PER_BUILDING = 12;
// Use this for initialization
void Start () {
// Initialize friendly soldiers in the buildings
foreach (GameObject building in GameObject.FindGameObjectsWithTag("BuildingSkeleton"))
{
int numSoldiers = Random.Range (10, 15);
for (int i = 0; i < numSoldiers; i++)
{
Vector3 spawnPosition = new Vector3(
Random.Range (building.renderer.bounds.min.x, building.renderer.bounds.max.x),
20,
Random.Range (building.renderer.bounds.min.z, building.renderer.bounds.max.z));
Instantiate (friendlySoldierPrefab, spawnPosition, Quaternion.identity);
}
}
// Initialize search drones
Vector3 helicopterPosition = GameObject.FindGameObjectWithTag ("Helicopter").transform.position;
for (int i = 0; i < NUM_DRONES; i++)
{
// Show the first drone camera in the corner of the screen
if (i == 0)
{
var drone = Instantiate (dronePrefab, helicopterPosition, Quaternion.identity);
((GameObject)drone).camera.depth = 1;
}
else
{
Instantiate (dronePrefab, helicopterPosition, Quaternion.identity);
}
}
}
}
| using UnityEngine;
public class SpawnController : MonoBehaviour {
public GameObject friendlySoldierPrefab;
public GameObject dronePrefab;
// Constants
public const int NUM_DRONES = 10;
public const int MIN_SOLDIERS_PER_BUILDING = 8;
public const int MAX_SOLDIERS_PER_BUILDING = 12;
// Use this for initialization
void Start () {
// Initialize friendly soldiers in the buildings
foreach (GameObject building in GameObject.FindGameObjectsWithTag("BuildingSkeleton"))
{
int numSoldiers = Random.Range (10, 15);
for (int i = 0; i < numSoldiers; i++)
{
Vector3 spawnPosition = new Vector3(
Random.Range (building.renderer.bounds.min.x, building.renderer.bounds.max.x),
Random.Range (building.renderer.bounds.min.y, 20),
Random.Range (building.renderer.bounds.min.z, building.renderer.bounds.max.z));
Instantiate (friendlySoldierPrefab, spawnPosition, Quaternion.identity);
}
}
// Initialize search drones
Vector3 helicopterPosition = GameObject.FindGameObjectWithTag ("Helicopter").transform.position;
for (int i = 0; i < NUM_DRONES; i++)
{
// Show the first drone camera in the corner of the screen
if (i == 0)
{
var drone = Instantiate (dronePrefab, helicopterPosition, Quaternion.identity);
((GameObject)drone).camera.depth = 1;
}
else
{
Instantiate (dronePrefab, helicopterPosition, Quaternion.identity);
}
}
}
}
| mit | C# |
dc16cdbf4fbc62ca6144f08da26b774eeba60ae0 | Refactor AutoPilot | setchi/kagaribi,setchi/kagaribi | Assets/Scripts/Title/AutoPilot.cs | Assets/Scripts/Title/AutoPilot.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UniRx;
using UniRx.Triggers;
public class AutoPilot : MonoBehaviour {
[SerializeField] SquareGenerator squareGenerator;
void Awake() {
squareGenerator.onPopTarget.First().Subscribe(target => Move(target.transform.position));
squareGenerator.onPopTarget.Buffer(2, 1)
.Subscribe(b => b[0].transform.ObserveEveryValueChanged(x => x.position)
.Where(pos => pos.z < 10)
.First().Subscribe(_ => Move(b[1].transform.position)));
}
void Move(Vector3 pos) {
var distance = pos.z;
pos.z = 0;
DOTween.Kill(gameObject);
transform.DOMove(pos, distance / 30f).SetEase(Ease.InOutQuad).SetId(gameObject);
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UniRx;
using UniRx.Triggers;
public class AutoPilot : MonoBehaviour {
[SerializeField] SquareGenerator squareGenerator;
void Awake() {
var targetQueue = new Queue<GameObject>();
squareGenerator.onPopTarget.Subscribe(targetQueue.Enqueue);
squareGenerator.onPopTarget.First().Subscribe(target => Move(target.transform.position));
this.UpdateAsObservable().Select(_ => targetQueue).Where(queue => queue.Count > 0)
.Where(queue => queue.Peek().transform.position.z < 10)
.Do(queue => queue.Dequeue())
.Subscribe(queue => Move(queue.Peek().transform.position));
}
void Move(Vector3 pos) {
var distance = pos.z;
pos.z = 0;
DOTween.Kill(gameObject);
transform.DOMove(pos, distance / 30f).SetEase(Ease.InOutQuad).SetId(gameObject);
}
}
| mit | C# |
eb548cc0377fbc0006a344115b57f8ab672fc312 | Remove extra code | setchi/NotesEditor,setchi/NoteEditor | Assets/Scripts/UndoRedoManager.cs | Assets/Scripts/UndoRedoManager.cs | using System;
using System.Collections.Generic;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
public class UndoRedoManager : SingletonGameObject<UndoRedoManager>
{
Stack<Command> undoStack = new Stack<Command>();
Stack<Command> redoStack = new Stack<Command>();
void Awake()
{
var model = NotesEditorModel.Instance;
model.OnLoadedMusicObservable
.DelayFrame(1)
.Subscribe(_ =>
{
undoStack.Clear();
redoStack.Clear();
});
this.UpdateAsObservable()
.Where(_ => KeyInput.CtrlPlus(KeyCode.Z))
.Subscribe(_ => Undo());
this.UpdateAsObservable()
.Where(_ => KeyInput.CtrlPlus(KeyCode.Y))
.Subscribe(_ => Redo());
}
static public void Do(Command command)
{
command.Do();
Instance.undoStack.Push(command);
Instance.redoStack.Clear();
}
void Undo()
{
if (undoStack.Count == 0)
return;
var command = undoStack.Pop();
command.Undo();
redoStack.Push(command);
}
void Redo()
{
if (redoStack.Count == 0)
return;
var command = redoStack.Pop();
command.Redo();
undoStack.Push(command);
}
}
public class Command
{
Action doAction;
Action redoAction;
Action undoAction;
public Command(Action doAction, Action undoAction, Action redoAction)
{
this.doAction = doAction;
this.undoAction = undoAction;
this.redoAction = redoAction;
}
public Command(Action doAction, Action undoAction)
{
this.doAction = doAction;
this.undoAction = undoAction;
this.redoAction = doAction;
}
public void Do() { doAction(); }
public void Undo() { undoAction(); }
public void Redo() { redoAction(); }
}
| using System;
using System.Collections.Generic;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
public class UndoRedoManager : SingletonGameObject<UndoRedoManager>
{
Stack<Command> undoStack = new Stack<Command>();
Stack<Command> redoStack = new Stack<Command>();
void Awake()
{
var model = NotesEditorModel.Instance;
model.OnLoadedMusicObservable
.DelayFrame(1)
.Subscribe(_ =>
{
undoStack.Clear();
redoStack.Clear();
});
this.UpdateAsObservable()
.Where(_ => KeyInput.CtrlPlus(KeyCode.Z))
.Subscribe(_ => Undo());
this.UpdateAsObservable()
.Where(_ => KeyInput.CtrlPlus(KeyCode.Y))
.Subscribe(_ => Redo());
}
static public void Do(Command command)
{
command.Do();
Instance.undoStack.Push(command);
Instance.redoStack.Clear();
}
void Undo()
{
if (Instance.undoStack.Count == 0)
return;
var command = undoStack.Pop();
command.Undo();
redoStack.Push(command);
}
void Redo()
{
if (Instance.redoStack.Count == 0)
return;
var command = redoStack.Pop();
command.Redo();
undoStack.Push(command);
}
}
public class Command
{
Action doAction;
Action redoAction;
Action undoAction;
public Command(Action doAction, Action undoAction, Action redoAction)
{
this.doAction = doAction;
this.undoAction = undoAction;
this.redoAction = redoAction;
}
public Command(Action doAction, Action undoAction)
{
this.doAction = doAction;
this.undoAction = undoAction;
this.redoAction = doAction;
}
public void Do() { doAction(); }
public void Undo() { undoAction(); }
public void Redo() { redoAction(); }
}
| mit | C# |
a118135f2f48c924343cb63237c497d1228146d0 | Change room caching to make it timeout really quickly. Mitigates #1047 as all caches reflect the truth after ~1s. | borisyankov/JabbR,JabbR/JabbR,yadyn/JabbR,yadyn/JabbR,SonOfSam/JabbR,18098924759/JabbR,yadyn/JabbR,e10/JabbR,18098924759/JabbR,mzdv/JabbR,borisyankov/JabbR,M-Zuber/JabbR,timgranstrom/JabbR,SonOfSam/JabbR,borisyankov/JabbR,JabbR/JabbR,M-Zuber/JabbR,timgranstrom/JabbR,mzdv/JabbR,ajayanandgit/JabbR,e10/JabbR,ajayanandgit/JabbR | JabbR/Services/CacheExtensions.cs | JabbR/Services/CacheExtensions.cs | using System;
using JabbR.Models;
namespace JabbR.Services
{
public static class CacheExtensions
{
public static T Get<T>(this ICache cache, string key)
{
return (T)cache.Get(key);
}
public static bool? IsUserInRoom(this ICache cache, ChatUser user, ChatRoom room)
{
string key = CacheKeys.GetUserInRoom(user, room);
return (bool?)cache.Get(key);
}
public static void SetUserInRoom(this ICache cache, ChatUser user, ChatRoom room, bool value)
{
string key = CacheKeys.GetUserInRoom(user, room);
// cache very briefly. We could set this much higher if we know that we're on a non-scaled-out server.
cache.Set(key, value, TimeSpan.FromSeconds(1));
}
public static void RemoveUserInRoom(this ICache cache, ChatUser user, ChatRoom room)
{
cache.Remove(CacheKeys.GetUserInRoom(user, room));
}
private static class CacheKeys
{
public static string GetUserInRoom(ChatUser user, ChatRoom room)
{
return "UserInRoom" + user.Key + "_" + room.Key;
}
}
}
} | using System;
using JabbR.Models;
namespace JabbR.Services
{
public static class CacheExtensions
{
public static T Get<T>(this ICache cache, string key)
{
return (T)cache.Get(key);
}
public static bool? IsUserInRoom(this ICache cache, ChatUser user, ChatRoom room)
{
string key = CacheKeys.GetUserInRoom(user, room);
return (bool?)cache.Get(key);
}
public static void SetUserInRoom(this ICache cache, ChatUser user, ChatRoom room, bool value)
{
string key = CacheKeys.GetUserInRoom(user, room);
// Cache this forever since people don't leave rooms often
cache.Set(key, value, TimeSpan.FromDays(365));
}
public static void RemoveUserInRoom(this ICache cache, ChatUser user, ChatRoom room)
{
cache.Remove(CacheKeys.GetUserInRoom(user, room));
}
private static class CacheKeys
{
public static string GetUserInRoom(ChatUser user, ChatRoom room)
{
return "UserInRoom" + user.Key + "_" + room.Key;
}
}
}
} | mit | C# |
b947f256cd6f88aab26ca341a09981ec1d793c1c | add docu | shrayasr/pinboard.net | pinboard.net/Endpoints/Tags.cs | pinboard.net/Endpoints/Tags.cs | using Flurl;
using Newtonsoft.Json;
using pinboard.net.Models;
using pinboard.net.Util;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace pinboard.net.Endpoints
{
public class Tags : Endpoint
{
public Tags(string apiToken, HttpClient httpClient)
: base(apiToken, httpClient) { }
/// <summary>
/// Returns a full list of the user's tags along with the number of times they were used.
/// </summary>
/// <returns>List of tags and their counts</returns>
public Task<AllTags> Get()
{
var url = TagsURL.AppendPathSegment("get");
return MakeRequestAsync<AllTags>(url, (content) =>
{
var allTagCounts = JsonConvert.DeserializeObject<IDictionary<string, int>>(content);
var allTags = new AllTags();
foreach(KeyValuePair<string, int> kv in allTagCounts)
{
allTags.Add(new TagCount
{
Tag = kv.Key,
Count = kv.Value
});
}
return allTags;
});
}
/// <summary>
/// Delete an existing tag.
/// </summary>
/// <param name="tag">The tag to delete</param>
/// <returns>A result code</returns>
public Task<TagsResult> Delete(string tag)
{
if (tag.IsEmpty())
throw new ArgumentException("Tag cannot be empty");
var url = TagsURL
.AppendPathSegment("delete")
.SetQueryParam("tag", tag);
return MakeRequestAsync<TagsResult>(url);
}
}
}
| using Flurl;
using Newtonsoft.Json;
using pinboard.net.Models;
using pinboard.net.Util;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace pinboard.net.Endpoints
{
public class Tags : Endpoint
{
public Tags(string apiToken, HttpClient httpClient)
: base(apiToken, httpClient) { }
/// <summary>
/// Returns a full list of the user's tags along with the number of times they were used.
/// </summary>
/// <returns>List of tags and their counts</returns>
public Task<AllTags> Get()
{
var url = TagsURL.AppendPathSegment("get");
return MakeRequestAsync<AllTags>(url, (content) =>
{
var allTagCounts = JsonConvert.DeserializeObject<IDictionary<string, int>>(content);
var allTags = new AllTags();
foreach(KeyValuePair<string, int> kv in allTagCounts)
{
allTags.Add(new TagCount
{
Tag = kv.Key,
Count = kv.Value
});
}
return allTags;
});
}
public Task<TagsResult> Delete(string tag)
{
if (tag.IsEmpty())
throw new ArgumentException("Tag cannot be empty");
var url = TagsURL
.AppendPathSegment("delete")
.SetQueryParam("tag", tag);
return MakeRequestAsync<TagsResult>(url);
}
}
}
| mit | C# |
c559cf04b7848605198583bca8eee3f9d047f4b6 | Set navigation bar translucent to false to fix views overlapping. Fix bug [14631] | davidrynn/monotouch-samples,sakthivelnagarajan/monotouch-samples,nelzomal/monotouch-samples,davidrynn/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,labdogg1003/monotouch-samples,kingyond/monotouch-samples,nervevau2/monotouch-samples,davidrynn/monotouch-samples,peteryule/monotouch-samples,labdogg1003/monotouch-samples,robinlaide/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,hongnguyenpro/monotouch-samples,davidrynn/monotouch-samples,nervevau2/monotouch-samples,hongnguyenpro/monotouch-samples,xamarin/monotouch-samples,andypaul/monotouch-samples,andypaul/monotouch-samples,haithemaraissia/monotouch-samples,peteryule/monotouch-samples,xamarin/monotouch-samples,nelzomal/monotouch-samples,kingyond/monotouch-samples,nervevau2/monotouch-samples,iFreedive/monotouch-samples,W3SS/monotouch-samples,sakthivelnagarajan/monotouch-samples,robinlaide/monotouch-samples,markradacz/monotouch-samples,haithemaraissia/monotouch-samples,haithemaraissia/monotouch-samples,albertoms/monotouch-samples,sakthivelnagarajan/monotouch-samples,nervevau2/monotouch-samples,hongnguyenpro/monotouch-samples,W3SS/monotouch-samples,albertoms/monotouch-samples,YOTOV-LIMITED/monotouch-samples,YOTOV-LIMITED/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,a9upam/monotouch-samples,andypaul/monotouch-samples,iFreedive/monotouch-samples,xamarin/monotouch-samples,W3SS/monotouch-samples,hongnguyenpro/monotouch-samples,a9upam/monotouch-samples,kingyond/monotouch-samples,markradacz/monotouch-samples,YOTOV-LIMITED/monotouch-samples,albertoms/monotouch-samples,sakthivelnagarajan/monotouch-samples,haithemaraissia/monotouch-samples,nelzomal/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,nelzomal/monotouch-samples,a9upam/monotouch-samples,markradacz/monotouch-samples,robinlaide/monotouch-samples,peteryule/monotouch-samples | RecipesAndPrinting/AppDelegate.cs | RecipesAndPrinting/AppDelegate.cs | //
// AppDelegate.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace RecipesAndPrinting
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
RecipeListTableViewController mainViewController;
UINavigationController navController;
UIWindow window;
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);
// Create the recipes controller object that provides recipe data to the application UI.
// The need for a data controller object such as this increases as the amount of data your
// application uses increases. However, for simplicity, this sample stores only two recipes.
RecipesController recipesController = new RecipesController ();
// Load the main table view controller that displays a list of recipes.
mainViewController = new RecipeListTableViewController (UITableViewStyle.Plain, recipesController);
navController = new UINavigationController (mainViewController);
navController.NavigationBar.Translucent = false;
window.AddSubview (navController.View);
window.MakeKeyAndVisible ();
return true;
}
}
}
| //
// AppDelegate.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace RecipesAndPrinting
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
RecipeListTableViewController mainViewController;
UINavigationController navController;
UIWindow window;
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
window = new UIWindow (UIScreen.MainScreen.Bounds);
// Create the recipes controller object that provides recipe data to the application UI.
// The need for a data controller object such as this increases as the amount of data your
// application uses increases. However, for simplicity, this sample stores only two recipes.
RecipesController recipesController = new RecipesController ();
// Load the main table view controller that displays a list of recipes.
mainViewController = new RecipeListTableViewController (UITableViewStyle.Plain, recipesController);
navController = new UINavigationController (mainViewController);
window.AddSubview (navController.View);
window.MakeKeyAndVisible ();
return true;
}
}
}
| mit | C# |
9ef29c41ed3c7b75090048b767a1287d0a663434 | Fix build error in LoggerMock | SAEnergy/Infrastructure,SAEnergy/Superstructure,SAEnergy/Infrastructure | Src/Test/Test.Mocks/LoggerMock.cs | Src/Test/Test.Mocks/LoggerMock.cs | using Core.Interfaces.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
namespace Test.Mocks
{
public class LoggerMock : ILogger
{
public bool IsRunning { get; private set; }
public void AddLogDestination(ILogDestination logDestination)
{
throw new NotImplementedException();
}
public void Log(LogMessage logMessage, [CallerMemberName] string callerName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
throw new NotImplementedException();
}
public void Log(LogMessageSeverity severity, string message, [CallerMemberName] string callerName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
throw new NotImplementedException();
}
public void RemoveLogDestination(ILogDestination logDestination)
{
throw new NotImplementedException();
}
public void Start()
{
throw new NotImplementedException();
}
public void Stop()
{
throw new NotImplementedException();
}
}
}
| using Core.Interfaces.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
namespace Test.Mocks
{
public class LoggerMock : ILogger
{
public bool IsRunning { get; }
public void AddLogDestination(ILogDestination logDestination)
{
throw new NotImplementedException();
}
public void Log(LogMessage logMessage, [CallerMemberName] string callerName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
throw new NotImplementedException();
}
public void Log(LogMessageSeverity severity, string message, [CallerMemberName] string callerName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
{
throw new NotImplementedException();
}
public void RemoveLogDestination(ILogDestination logDestination)
{
throw new NotImplementedException();
}
public void Start()
{
throw new NotImplementedException();
}
public void Stop()
{
throw new NotImplementedException();
}
}
}
| mit | C# |
fb8679a9794d02acc620916dd31c789c2d1ede36 | Update IViewModel.cs | dingjimmy/primer | Primer/IViewModel.cs | Primer/IViewModel.cs | // Copyright (c) James Dingle
using System;
namespace Primer
{
public interface IViewModel
{
bool IsLoaded { get; set; }
string DisplayName { get; set; }
IMessagingChannel Channel { get; private set; }
IValidator Validator { get; private set; }
ILogger Logger { get; private set; }
}
}
| // Copyright (c) James Dingle
using System;
namespace Primer
{
public interface IViewModel
{
bool IsLoaded { get; set; }
string DisplayName { get; set; }
IMessagingChannel Channel { get; private set; }
IValidator Validator { get; private set; }
ILogger { get; private set; }
}
}
| mit | C# |
53c89b0c9b0b9ef93b9eecbe817cde87452d6a23 | update version | RainwayApp/warden | Warden/Properties/AssemblyInfo.cs | Warden/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("Warden")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rainway, Inc.")]
[assembly: AssemblyProduct("Warden")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("69bd1ac4-362a-41d0-8e84-a76064d90b4b")]
// 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.7.0")]
[assembly: AssemblyFileVersion("1.0.7.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("Warden")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rainway, Inc.")]
[assembly: AssemblyProduct("Warden")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("69bd1ac4-362a-41d0-8e84-a76064d90b4b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.5.0")]
[assembly: AssemblyFileVersion("1.0.5.0")]
| apache-2.0 | C# |
3e77d25a2b759f5680a1682e4f4134c9ed538fd1 | save room tool fixes | solfen/Rogue_Cadet | Assets/Editor/SaveRoomPrefab.cs | Assets/Editor/SaveRoomPrefab.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class SaveRoomPrefab {
private static RoomDynamicContent[] lastRoomContents;
[MenuItem("Tools/Save room to prefab _F5", true)]
private static bool Validate() {
return Selection.activeGameObject != null && Selection.activeTransform.root.GetComponent<Room>() != null;
}
[MenuItem("Tools/Save room to prefab _F5")]
private static void AddRoomsToDungeon() {
Room room = Selection.activeTransform.root.GetComponent<Room>();
SaveDynamicContent(room);
SaveEnemiesPacks(room);
PrefabUtility.ReplacePrefab(room.gameObject, PrefabUtility.GetPrefabParent(room.gameObject), ReplacePrefabOptions.ConnectToPrefab);
RestoreSceneRoomPreviousState(room);
}
private static void SaveDynamicContent(Room room) {
lastRoomContents = room.GetComponentsInChildren<RoomDynamicContent>();
Undo.RecordObject(room.gameObject, "Save Room to Prefab");
for (int i = 0; i < lastRoomContents.Length; i++) {
lastRoomContents[i].ContentToList();
lastRoomContents[i].enabled = true;
}
}
private static void SaveEnemiesPacks(Room room) {
room.enemiesContainers.Clear();
for (int i = 0; i < room.enemiesParent.childCount; i++) {
Transform enemiesContainer = room.enemiesParent.GetChild(i);
EnemyPack pack = new EnemyPack();
pack.name = enemiesContainer.name;
pack.container = enemiesContainer.gameObject;
room.enemiesContainers.Add(pack);
enemiesContainer.gameObject.SetActive(false);
}
}
private static void RestoreSceneRoomPreviousState(Room room) {
for (int i = 0; i < lastRoomContents.Length; i++) {
lastRoomContents[i].gameObject.SetActive(true);
}
room.debug = true;
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class SaveRoomPrefab {
private static RoomDynamicContent[] lastRoomContents;
[MenuItem("Tools/Save room to prefab _F5", true)]
private static bool Validate() {
return Selection.activeGameObject != null && Selection.activeTransform.root.GetComponent<Room>() != null;
}
[MenuItem("Tools/Save room to prefab _F5")]
private static void AddRoomsToDungeon() {
Room room = Selection.activeTransform.root.GetComponent<Room>();
SaveDynamicContent(room);
SaveEnemiesPacks(room);
room.debug = false;
PrefabUtility.ReplacePrefab(room.gameObject, PrefabUtility.GetPrefabParent(room.gameObject), ReplacePrefabOptions.ConnectToPrefab);
RestoreSceneRoomPreviousState(room);
}
private static void SaveDynamicContent(Room room) {
lastRoomContents = room.GetComponentsInChildren<RoomDynamicContent>();
Undo.RecordObject(room.gameObject, "Save Room to Prefab");
for (int i = 0; i < lastRoomContents.Length; i++) {
lastRoomContents[i].ContentToList();
lastRoomContents[i].enabled = true;
}
}
private static void SaveEnemiesPacks(Room room) {
room.enemiesContainers.Clear();
for (int i = 0; i < room.enemiesParent.childCount; i++) {
Transform enemiesContainer = room.enemiesParent.GetChild(i);
EnemyPack pack = new EnemyPack();
pack.name = enemiesContainer.name;
pack.container = enemiesContainer.gameObject;
room.enemiesContainers.Add(pack);
enemiesContainer.gameObject.SetActive(false);
}
}
private static void RestoreSceneRoomPreviousState(Room room) {
for (int i = 0; i < lastRoomContents.Length; i++) {
lastRoomContents[i].gameObject.SetActive(true);
lastRoomContents[i].ListToContent();
}
}
} | mit | C# |
e88b0e55875c682987eff45b521f58d6c6391392 | Fix tests | smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu | osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs | osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.6975550434910005d, "diffcalc-test")]
[TestCase(1.4670676815251105d, "zero-length-sliders")]
public void Test(double expected, string name)
=> base.Test(expected, name);
[TestCase(8.9389769779826267d, "diffcalc-test")]
[TestCase(1.7786917985891204d, "zero-length-sliders")]
public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new OsuModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new OsuRuleset();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.6975550434910005d, "diffcalc-test")]
[TestCase(1.4673500058356748d, "zero-length-sliders")]
public void Test(double expected, string name)
=> base.Test(expected, name);
[TestCase(8.938989502378238d, "diffcalc-test")]
[TestCase(1.779323508403831d, "zero-length-sliders")]
public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new OsuModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new OsuRuleset();
}
}
| mit | C# |
039a202809e65fd5e5e7b625d8b6dd0d253de462 | Convert Language enum to value type | Ontica/Empiria.Extended | Cognition/RootTypes/Language.cs | Cognition/RootTypes/Language.cs | /* Empiria Extensions ****************************************************************************************
* *
* Module : Cognitive Services Component : Service provider *
* Assembly : Empiria.Cognition.ESign.dll Pattern : Value Type *
* Type : Language License : Please read LICENSE.txt file *
* *
* Summary : Describes a text translation language. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
namespace Empiria.Cognition {
/// <summary>Describes a text translation language.</summary>
public class Language {
#region Constructors and parsers
private Language(string name, string code) {
this.Name = name;
this.Code = code;
}
static public readonly Language English = new Language("English", "en");
static public readonly Language Spanish = new Language("Spanish", "sp");
#endregion Constructors and parsers
#region Properties
public string Name {
get;
}
public string Code {
get;
}
#endregion Properties
#region Methods
public override bool Equals(object obj) {
if (obj == null || this.GetType() != obj.GetType()) {
return false;
}
return base.Equals(obj) && (this.Code == ((Language) obj).Code);
}
public override int GetHashCode() {
return this.Code.GetHashCode();
}
#endregion Methods
} // class Language
} | /* Empiria Extensions ****************************************************************************************
* *
* Module : Cognitive Services Component : Service provider *
* Assembly : Empiria.Cognition.ESign.dll Pattern : Enumerated Type *
* Type : Language License : Please read LICENSE.txt file *
* *
* Summary : Describes a text translation language. *
* *
************************* Copyright(c) La Vía Óntica SC, Ontica LLC and contributors. All rights reserved. **/
using System;
namespace Empiria.Cognition {
/// <summary>Describes a text translation language.</summary>
public enum Language {
English,
Spanish
}
}
| agpl-3.0 | C# |
9e2cad1a85fd26b55c933a74304e6d70f75b7aec | increase version number | aspnetboilerplate/module-zero-template,aspnetboilerplate/module-zero-template,aspnetboilerplate/module-zero-template | src/AbpCompanyName.AbpProjectName.Core/AppVersionHelper.cs | src/AbpCompanyName.AbpProjectName.Core/AppVersionHelper.cs | using System;
using System.IO;
using Abp.Reflection.Extensions;
namespace AbpCompanyName.AbpProjectName
{
/// <summary>
/// Central point for application version.
/// </summary>
public class AppVersionHelper
{
/// <summary>
/// Gets current version of the application.
/// It's also shown in the web page.
/// </summary>
public const string Version = "4.6.0.0";
/// <summary>
/// Gets release (last build) date of the application.
/// It's shown in the web page.
/// </summary>
public static DateTime ReleaseDate
{
get { return new FileInfo(typeof(AppVersionHelper).GetAssembly().Location).LastWriteTime; }
}
}
}
| using System;
using System.IO;
using Abp.Reflection.Extensions;
namespace AbpCompanyName.AbpProjectName
{
/// <summary>
/// Central point for application version.
/// </summary>
public class AppVersionHelper
{
/// <summary>
/// Gets current version of the application.
/// It's also shown in the web page.
/// </summary>
public const string Version = "4.5.0.0";
/// <summary>
/// Gets release (last build) date of the application.
/// It's shown in the web page.
/// </summary>
public static DateTime ReleaseDate
{
get { return new FileInfo(typeof(AppVersionHelper).GetAssembly().Location).LastWriteTime; }
}
}
}
| mit | C# |
e24cb37ed02c2a8d1b92c2648efd8628d10f9c23 | Test adapted to both translators | ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,fredericDelaporte/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,alobakov/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,ManufacturingIntelligence/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core | src/NHibernate.Test/NHSpecificTest/EmptyMappingsFixture.cs | src/NHibernate.Test/NHSpecificTest/EmptyMappingsFixture.cs | using System;
using System.Collections;
using System.Data;
using NHibernate.Transaction;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest
{
/// <summary>
/// This fixture contains no mappings, it is thus faster and can be used
/// to run tests for basic features that don't require any mapping files
/// to function.
/// </summary>
[TestFixture]
public class EmptyMappingsFixture : TestCase
{
protected override IList Mappings
{
get { return new string[0]; }
}
[Test]
public void BeginWithIsolationLevel()
{
using (ISession s = OpenSession())
using (ITransaction t = s.BeginTransaction(IsolationLevel.ReadCommitted))
{
AdoTransaction at = (AdoTransaction) t;
Assert.AreEqual(IsolationLevel.ReadCommitted, at.IsolationLevel);
}
}
[Test, ExpectedException(typeof(ObjectDisposedException))]
public void ReconnectAfterClose()
{
using (ISession s = OpenSession())
{
s.Close();
s.Reconnect();
}
}
[Test]
public void InvalidQuery()
{
try
{
using (ISession s = OpenSession())
{
s.CreateQuery("from SomeInvalidClass").List();
}
}
catch (QueryException)
{
//
}
}
[Test, ExpectedException(typeof(ArgumentNullException))]
public void NullInterceptor()
{
IInterceptor nullInterceptor = null;
sessions.OpenSession(nullInterceptor).Close();
}
[Test]
public void DisconnectShouldNotCloseUserSuppliedConnection()
{
IDbConnection conn = sessions.ConnectionProvider.GetConnection();
try
{
using (ISession s = OpenSession())
{
s.Disconnect();
s.Reconnect(conn);
Assert.AreSame(conn, s.Disconnect());
Assert.AreEqual(ConnectionState.Open, conn.State);
}
}
finally
{
sessions.ConnectionProvider.CloseConnection(conn);
}
}
}
} | using System;
using System.Collections;
using System.Data;
using NHibernate.Transaction;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest
{
/// <summary>
/// This fixture contains no mappings, it is thus faster and can be used
/// to run tests for basic features that don't require any mapping files
/// to function.
/// </summary>
[TestFixture]
public class EmptyMappingsFixture : TestCase
{
protected override IList Mappings
{
get { return new string[0]; }
}
[Test]
public void BeginWithIsolationLevel()
{
using (ISession s = OpenSession())
using (ITransaction t = s.BeginTransaction(IsolationLevel.ReadCommitted))
{
AdoTransaction at = (AdoTransaction) t;
Assert.AreEqual(IsolationLevel.ReadCommitted, at.IsolationLevel);
}
}
[Test, ExpectedException(typeof(ObjectDisposedException))]
public void ReconnectAfterClose()
{
using (ISession s = OpenSession())
{
s.Close();
s.Reconnect();
}
}
[Test, ExpectedException(typeof(QueryException))]
public void InvalidQuery()
{
using (ISession s = OpenSession())
{
s.CreateQuery("from SomeInvalidClass").List();
}
}
[Test, ExpectedException(typeof(ArgumentNullException))]
public void NullInterceptor()
{
IInterceptor nullInterceptor = null;
sessions.OpenSession(nullInterceptor).Close();
}
[Test]
public void DisconnectShouldNotCloseUserSuppliedConnection()
{
IDbConnection conn = sessions.ConnectionProvider.GetConnection();
try
{
using (ISession s = OpenSession())
{
s.Disconnect();
s.Reconnect(conn);
Assert.AreSame(conn, s.Disconnect());
Assert.AreEqual(ConnectionState.Open, conn.State);
}
}
finally
{
sessions.ConnectionProvider.CloseConnection(conn);
}
}
}
} | lgpl-2.1 | C# |
d4192d45d0760ec7d68cd605adc01240bc988018 | Use new DApplication.SessionBus | mono/dbus-sharp-glib,mono/dbus-sharp-glib | glib/TestExport.cs | glib/TestExport.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using GLib;
using Gtk;
using NDesk.DBus;
using org.freedesktop.DBus;
public class TestGLib
{
public static void OnClick (object o, EventArgs args)
{
demo.Say ("Button clicked");
}
static Bus bus;
static DemoObject demo;
public static void Main ()
{
Application.Init ();
Button btn = new Button ("Click me");
btn.Clicked += OnClick;
VBox vb = new VBox (false, 2);
vb.PackStart (btn, false, true, 0);
Window win = new Window ("DBus#");
win.SetDefaultSize (640, 480);
win.Add (vb);
win.Destroyed += delegate {Application.Quit ();};
win.ShowAll ();
bus = DApplication.SessionBus;
ObjectPath myPath = new ObjectPath ("/org/ndesk/test");
string myNameReq = "org.ndesk.gtest";
if (bus.NameHasOwner (myNameReq)) {
demo = DApplication.Connection.GetObject<DemoObject> (myNameReq, myPath);
} else {
NameReply nameReply = bus.RequestName (myNameReq, NameFlag.None);
Console.WriteLine ("nameReply: " + nameReply);
demo = new DemoObject ();
DApplication.Connection.Marshal (demo, myNameReq, myPath);
}
Application.Run ();
}
}
[Interface ("org.ndesk.gtest")]
public class DemoObject : MarshalByRefObject
{
public void Say (string text)
{
Console.WriteLine (text);
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using GLib;
using Gtk;
using NDesk.DBus;
using org.freedesktop.DBus;
public class TestGLib
{
public static void OnClick (object o, EventArgs args)
{
demo.Say ("Button clicked");
}
static Bus bus;
static DemoObject demo;
public static void Main ()
{
Application.Init ();
Button btn = new Button ("Click me");
btn.Clicked += OnClick;
VBox vb = new VBox (false, 2);
vb.PackStart (btn, false, true, 0);
Window win = new Window ("DBus#");
win.SetDefaultSize (640, 480);
win.Add (vb);
win.Destroyed += delegate {Application.Quit ();};
win.ShowAll ();
ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
string name = "org.freedesktop.DBus";
bus = DApplication.Connection.GetObject<Bus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.Error.WriteLine ("NameAcquired: " + acquired_name);
};
string myName = bus.Hello ();
Console.Error.WriteLine ("myName: " + myName);
ObjectPath myOpath = new ObjectPath ("/org/ndesk/test");
string myNameReq = "org.ndesk.gtest";
if (bus.NameHasOwner (myNameReq)) {
demo = DApplication.Connection.GetObject<DemoObject> (myNameReq, opath);
} else {
NameReply nameReply = bus.RequestName (myNameReq, NameFlag.None);
Console.WriteLine ("nameReply: " + nameReply);
demo = new DemoObject ();
DApplication.Connection.Marshal (demo, myNameReq, myOpath);
}
Application.Run ();
}
}
[Interface ("org.ndesk.gtest")]
public class DemoObject : MarshalByRefObject
{
public void Say (string text)
{
Console.WriteLine (text);
}
}
| mit | C# |
e4c79934707aa1a0aa6c7066941c5b3c6e70ef57 | Update to v0.2 tag | lazear/Libra | Libra/Properties/AssemblyInfo.cs | Libra/Properties/AssemblyInfo.cs | using System.Resources;
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("LIBRA")]
[assembly: AssemblyDescription("The open source user interface for the Gemini Exchange. This is free software. Free as in beer, free as in pizza, free as in speech.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("https://www.pleasehodl.me")]
[assembly: AssemblyProduct("LIBRA Gemini Client")]
[assembly: AssemblyCopyright("Copyright © Michael Lazear 2017")]
[assembly: AssemblyTrademark("Released under the MIT License")]
[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("888a1944-19fd-4c3f-8685-49c4d6953e07")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.*")]
[assembly: NeutralResourcesLanguage("")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Resources;
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("LIBRA")]
[assembly: AssemblyDescription("The open source user interface for the Gemini Exchange. This is free software. Free as in beer, free as in pizza, free as in speech.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("https://www.pleasehodl.me")]
[assembly: AssemblyProduct("LIBRA Gemini Client")]
[assembly: AssemblyCopyright("Copyright © Michael Lazear 2017")]
[assembly: AssemblyTrademark("Released under the MIT License")]
[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("888a1944-19fd-4c3f-8685-49c4d6953e07")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.*")]
[assembly: NeutralResourcesLanguage("")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
171f4452e3d97fe0a207313081e7619a15daa759 | Repair failing functional test | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/WebSites/RoutingWebSite/Controllers/TeamController.cs | test/WebSites/RoutingWebSite/Controllers/TeamController.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Mvc;
namespace RoutingWebSite
{
[Route("/Teams", Order = 1)]
public class TeamController : Controller
{
private readonly TestResponseGenerator _generator;
public TeamController(TestResponseGenerator generator)
{
_generator = generator;
}
[HttpGet("/Team/{teamId}", Order = 2)]
public ActionResult GetTeam(int teamId)
{
return _generator.Generate("/Team/" + teamId);
}
[HttpGet("/Team/{teamId}")]
public ActionResult GetOrganization(int teamId)
{
return _generator.Generate("/Team/" + teamId);
}
[HttpGet("")]
public ActionResult GetTeams()
{
return _generator.Generate("/Teams");
}
[HttpGet("", Order = 0)]
public ActionResult GetOrganizations()
{
return _generator.Generate("/Teams");
}
[HttpGet("/Club/{clubId?}")]
public ActionResult GetClub()
{
return Content(Url.Action(), "text/plain");
}
[HttpGet("/Organization/{clubId?}", Order = 1)]
public ActionResult GetClub(int clubId)
{
return Content(Url.Action(), "text/plain");
}
[HttpGet("AllTeams")]
public ActionResult GetAllTeams()
{
return Content(Url.Action(), "text/plain");
}
[HttpGet("AllOrganizations", Order = 0)]
public ActionResult GetAllTeams(int notRelevant)
{
return Content(Url.Action(), "text/plain");
}
[HttpGet("/TeamName/{*Name=DefaultName}/")]
public ActionResult GetTeam(string name)
{
return _generator.Generate("/TeamName/" + name);
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Mvc;
namespace RoutingWebSite
{
[Route("/Teams", Order = 1)]
public class TeamController : Controller
{
private readonly TestResponseGenerator _generator;
public TeamController(TestResponseGenerator generator)
{
_generator = generator;
}
[HttpGet("/Team/{teamId}", Order = 2)]
public ActionResult GetTeam(int teamId)
{
return _generator.Generate("/Team/" + teamId);
}
[HttpGet("/Team/{teamId}")]
public ActionResult GetOrganization(int teamId)
{
return _generator.Generate("/Team/" + teamId);
}
[HttpGet("")]
public ActionResult GetTeams()
{
return _generator.Generate("/Teams");
}
[HttpGet("", Order = 0)]
public ActionResult GetOrganizations()
{
return _generator.Generate("/Teams");
}
[HttpGet("/Club/{clubId?}")]
public ActionResult GetClub()
{
return Content(Url.Action(), "text/plain");
}
[HttpGet("/Organization/{clubId?}", Order = 1)]
public ActionResult GetClub(int clubId)
{
return Content(Url.Action(), "text/plain");
}
[HttpGet("AllTeams")]
public ActionResult GetAllTeams()
{
return Content(Url.Action(), "text/plain");
}
[HttpGet("AllOrganizations", Order = 0)]
public ActionResult GetAllTeams(int notRelevant)
{
return Content(Url.Action(), "text/plain");
}
[HttpGet("/TeamName/{*Name}/")]
public ActionResult GetTeam(string name = "DefaultName")
{
return _generator.Generate("/TeamName/" + name);
}
}
} | apache-2.0 | C# |
9813aeb7247d91de5abe0bc3da96ba5cbafb1828 | Fix SpillTileReaction errors (#10910) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Server/Chemistry/TileReactions/SpillTileReaction.cs | Content.Server/Chemistry/TileReactions/SpillTileReaction.cs | using Content.Server.Fluids.EntitySystems;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Reaction;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.FixedPoint;
using Content.Shared.Slippery;
using Content.Shared.StepTrigger;
using Content.Shared.StepTrigger.Components;
using Content.Shared.StepTrigger.Systems;
using JetBrains.Annotations;
using Robust.Shared.Map;
namespace Content.Server.Chemistry.TileReactions
{
[UsedImplicitly]
[DataDefinition]
public sealed class SpillTileReaction : ITileReaction
{
[DataField("launchForwardsMultiplier")] private float _launchForwardsMultiplier = 1;
[DataField("requiredSlipSpeed")] private float _requiredSlipSpeed = 6;
[DataField("paralyzeTime")] private float _paralyzeTime = 1;
[DataField("overflow")] private bool _overflow;
public FixedPoint2 TileReact(TileRef tile, ReagentPrototype reagent, FixedPoint2 reactVolume)
{
if (reactVolume < 5) return FixedPoint2.Zero;
var entityManager = IoCManager.Resolve<IEntityManager>();
// TODO Make this not puddle smear.
var puddle = entityManager.EntitySysManager.GetEntitySystem<SpillableSystem>()
.SpillAt(tile, new Solution(reagent.ID, reactVolume), "PuddleSmear", _overflow, false, true);
if (puddle != null)
{
var slippery = entityManager.EnsureComponent<SlipperyComponent>(puddle.Owner);
slippery.LaunchForwardsMultiplier = _launchForwardsMultiplier;
slippery.ParalyzeTime = _paralyzeTime;
var step = entityManager.EnsureComponent<StepTriggerComponent>(puddle.Owner);
entityManager.EntitySysManager.GetEntitySystem<StepTriggerSystem>().SetRequiredTriggerSpeed(puddle.Owner, _requiredSlipSpeed, step);
return reactVolume;
}
return FixedPoint2.Zero;
}
}
}
| using Content.Server.Fluids.EntitySystems;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Reaction;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.FixedPoint;
using Content.Shared.Slippery;
using Content.Shared.StepTrigger;
using Content.Shared.StepTrigger.Systems;
using JetBrains.Annotations;
using Robust.Shared.Map;
namespace Content.Server.Chemistry.TileReactions
{
[UsedImplicitly]
[DataDefinition]
public sealed class SpillTileReaction : ITileReaction
{
[DataField("launchForwardsMultiplier")] private float _launchForwardsMultiplier = 1;
[DataField("requiredSlipSpeed")] private float _requiredSlipSpeed = 6;
[DataField("paralyzeTime")] private float _paralyzeTime = 1;
[DataField("overflow")] private bool _overflow;
public FixedPoint2 TileReact(TileRef tile, ReagentPrototype reagent, FixedPoint2 reactVolume)
{
if (reactVolume < 5) return FixedPoint2.Zero;
// TODO Make this not puddle smear.
var puddle = EntitySystem.Get<SpillableSystem>()
.SpillAt(tile, new Solution(reagent.ID, reactVolume), "PuddleSmear", _overflow, false, true);
if (puddle != null)
{
var entityManager = IoCManager.Resolve<IEntityManager>();
var slippery = entityManager.GetComponent<SlipperyComponent>(puddle.Owner);
slippery.LaunchForwardsMultiplier = _launchForwardsMultiplier;
EntitySystem.Get<StepTriggerSystem>().SetRequiredTriggerSpeed(puddle.Owner, _requiredSlipSpeed);
slippery.ParalyzeTime = _paralyzeTime;
return reactVolume;
}
return FixedPoint2.Zero;
}
}
}
| mit | C# |
94fbba76bf11440c0d97403c4123247b69e31af3 | Fix crash when clearing resetting template | SaberSnail/GoldenAnvil.Utility | GoldenAnvil.Utility.Windows/EnumToDisplayStringConverter.cs | GoldenAnvil.Utility.Windows/EnumToDisplayStringConverter.cs | using System;
using System.Resources;
using System.Windows.Data;
namespace GoldenAnvil.Utility.Windows
{
public sealed class EnumToDisplayStringConverter : IValueConverter
{
public static readonly EnumToDisplayStringConverter Instance = new EnumToDisplayStringConverter();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(parameter is ResourceManager resources))
throw new ArgumentException($"{nameof(parameter)} must be a ResourceManager.");
// sometimes an empty string can be passed instead of a null value
if (value is string stringValue)
{
if (stringValue == "")
return null;
}
var method = typeof(ResourceManagerUtility).GetMethod("EnumToDisplayString");
var generic = method.MakeGenericMethod(value.GetType());
return generic.Invoke(null, new [] { resources, value });
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Resources;
using System.Windows.Data;
namespace GoldenAnvil.Utility.Windows
{
public sealed class EnumToDisplayStringConverter : IValueConverter
{
public static readonly EnumToDisplayStringConverter Instance = new EnumToDisplayStringConverter();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(parameter is ResourceManager resources))
throw new ArgumentException($"{nameof(parameter)} must be a ResourceManager.");
var method = typeof(ResourceManagerUtility).GetMethod("EnumToDisplayString");
var generic = method.MakeGenericMethod(value.GetType());
return generic.Invoke(null, new [] { resources, value });
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
d6adccfd48015cca6443657942392ec54187b7d2 | Disable ubuntu and macos | NJsonSchema/NJsonSchema | build/Build.CI.GitHubActions.cs | build/Build.CI.GitHubActions.cs | using Nuke.Common.CI.GitHubActions;
[GitHubActionsAttribute(
"pr",
GitHubActionsImage.WindowsLatest,
//GitHubActionsImage.UbuntuLatest,
//GitHubActionsImage.MacOsLatest,
OnPullRequestBranches = new [] { "master", "main" },
PublishArtifacts = false,
InvokedTargets = new[] { nameof(Compile), nameof(Test), nameof(Pack) },
CacheKeyFiles = new[] { "global.json", "src/**/*.csproj", "src/**/package.json" }),
]
[GitHubActionsAttribute(
"build",
GitHubActionsImage.WindowsLatest,
//GitHubActionsImage.UbuntuLatest,
//GitHubActionsImage.MacOsLatest,
OnPushBranches = new [] { "master", "main" },
PublishArtifacts = true,
InvokedTargets = new[] { nameof(Compile), nameof(Test), nameof(Pack), nameof(Publish) },
ImportSecrets = new [] { "NUGET_API_KEY", "MYGET_API_KEY" },
CacheKeyFiles = new[] { "global.json", "src/**/*.csproj", "src/**/package.json" })
]
public partial class Build
{
}
| using Nuke.Common.CI.GitHubActions;
[GitHubActionsAttribute(
"pr",
GitHubActionsImage.WindowsLatest,
GitHubActionsImage.UbuntuLatest,
GitHubActionsImage.MacOsLatest,
OnPullRequestBranches = new [] { "master", "main" },
PublishArtifacts = false,
InvokedTargets = new[] { nameof(Compile), nameof(Test), nameof(Pack) },
CacheKeyFiles = new[] { "global.json", "src/**/*.csproj", "src/**/package.json" }),
]
[GitHubActionsAttribute(
"build",
GitHubActionsImage.WindowsLatest,
GitHubActionsImage.UbuntuLatest,
GitHubActionsImage.MacOsLatest,
OnPushBranches = new [] { "master", "main" },
PublishArtifacts = true,
InvokedTargets = new[] { nameof(Compile), nameof(Test), nameof(Pack), nameof(Publish) },
ImportSecrets = new [] { "NUGET_API_KEY", "MYGET_API_KEY" },
CacheKeyFiles = new[] { "global.json", "src/**/*.csproj", "src/**/package.json" })
]
public partial class Build
{
}
| mit | C# |
ea4e4e03dbf38d81573b2afb94e3d13b1b1b71cf | Trim any strings before comparision to fix #382 | tfsaggregator/tfsaggregator | Aggregator.Core/Aggregator.Core/Extensions/StringExtensions.cs | Aggregator.Core/Aggregator.Core/Extensions/StringExtensions.cs | using System;
namespace Aggregator.Core.Extensions
{
public static class StringExtensions
{
/// <summary>
/// Case insensitive comparison plus '*' wildcard matching
/// </summary>
/// <param name="lhs">The LHS.</param>
/// <param name="rhs">The RHS.</param>
/// <returns></returns>
public static bool SameAs(this string lhs, string rhs)
{
return lhs.Trim() == "*" || rhs.Trim() == "*" || string.Equals(lhs.Trim(), rhs.Trim(), StringComparison.OrdinalIgnoreCase);
}
public static string Truncate(this string value, int maxLength)
{
return string.IsNullOrEmpty(value) ? value : value.Substring(0, Math.Min(value.Length, maxLength));
}
}
}
| using System;
namespace Aggregator.Core.Extensions
{
public static class StringExtensions
{
/// <summary>
/// Case insensitive comparison plus '*' wildcard matching
/// </summary>
/// <param name="lhs">The LHS.</param>
/// <param name="rhs">The RHS.</param>
/// <returns></returns>
public static bool SameAs(this string lhs, string rhs)
{
return lhs == "*" || rhs == "*" || string.Equals(lhs, rhs, StringComparison.OrdinalIgnoreCase);
}
public static string Truncate(this string value, int maxLength)
{
return string.IsNullOrEmpty(value) ? value : value.Substring(0, Math.Min(value.Length, maxLength));
}
}
}
| apache-2.0 | C# |
65a7c5e1226b82c8bc1d57effd6a7e22f3d27a8e | Remove obsolete methods and add sumary texts. | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/IDbFactory.cs | src/Smooth.IoC.Dapper.Repository.UnitOfWork/Data/IDbFactory.cs | using System;
using System.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public interface IDbFactory
{
/// <summary>
/// Creates an instance of your ISession expanded interface
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>ISession</returns>
T Create<T>() where T : class, ISession;
/// <summary>
/// Creates a UnitOfWork and Session at same time. The session has the same scope as the unit of work.
/// </summary>
/// <param name="isolationLevel"></param>
/// <typeparam name="TUnitOfWork"></typeparam>
/// <typeparam name="TSession"></typeparam>
/// <returns></returns>
TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel= IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession;
/// <summary>
/// Used for Session base to create UnitOfWork. Not recommeded to use in other code
/// </summary>
/// <param name="factory"></param>
/// <param name="session"></param>
/// <param name="isolationLevel"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork;
/// <summary>
/// Release the component. Done by Sessnion and UnitOfWork on there own.
/// </summary>
/// <param name="instance"></param>
void Release(IDisposable instance);
}
}
| using System;
using System.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Data
{
public interface IDbFactory
{
/// <summary>
/// Creates an instance of your ISession expanded interface
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>ISession</returns>
T Create<T>() where T : class, ISession;
[Obsolete]
T CreateSession<T>() where T : class, ISession;
TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel= IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession;
T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork;
void Release(IDisposable instance);
}
}
| mit | C# |
5ccd3550197ad3fc46c0aca7f45b6a5da09a86d1 | Index has the same display whether logged in or not. (#73) | VenusInterns/BlogTemplate,VenusInterns/BlogTemplate,VenusInterns/BlogTemplate | BlogTemplate/Pages/Index.cshtml.cs | BlogTemplate/Pages/Index.cshtml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BlogTemplate.Models;
using System.IO;
namespace BlogTemplate.Pages
{
public class IndexModel : PageModel
{
const string StorageFolder = "BlogFiles";
private BlogDataStore _dataStore;
public IEnumerable<PostSummaryModel> PostSummaries { get; private set; }
public IndexModel(BlogDataStore dataStore)
{
_dataStore = dataStore;
}
public void OnGet()
{
Func<Post, bool> postFilter = p => p.IsPublic;
IEnumerable<Post> postModels = _dataStore.GetAllPosts().Where(postFilter);
PostSummaries = postModels.Select(p => new PostSummaryModel {
Slug = p.Slug,
Title = p.Title,
Excerpt = p.Excerpt,
PublishTime = p.PubDate,
CommentCount = p.Comments.Count,
});
}
public class PostSummaryModel
{
public string Slug { get; set; }
public string Title { get; set; }
public DateTime PublishTime { get; set; }
public string Excerpt { get; set; }
public int CommentCount { get; set; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BlogTemplate.Models;
using System.IO;
namespace BlogTemplate.Pages
{
public class IndexModel : PageModel
{
const string StorageFolder = "BlogFiles";
private BlogDataStore _dataStore;
public IEnumerable<PostSummaryModel> PostSummaries { get; private set; }
public IndexModel(BlogDataStore dataStore)
{
_dataStore = dataStore;
}
public void OnGet()
{
Func<Post, bool> postFilter = p => p.IsPublic;
if(User.Identity.IsAuthenticated)
{
postFilter = p => true;
}
IEnumerable<Post> postModels = _dataStore.GetAllPosts().Where(postFilter);
PostSummaries = postModels.Select(p => new PostSummaryModel {
Slug = p.Slug,
Title = p.Title,
Excerpt = p.Excerpt,
PublishTime = p.PubDate,
CommentCount = p.Comments.Count,
});
}
public class PostSummaryModel
{
public string Slug { get; set; }
public string Title { get; set; }
public DateTime PublishTime { get; set; }
public string Excerpt { get; set; }
public int CommentCount { get; set; }
}
}
}
| mit | C# |
fbb96c5a18c4be7a654808879726b1bd7ec3706f | Add parser error messages to implmap. | Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver | src/AsmResolver.DotNet/Serialized/SerializedImplementationMap.cs | src/AsmResolver.DotNet/Serialized/SerializedImplementationMap.cs | using System;
using AsmResolver.PE.DotNet.Metadata.Strings;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
namespace AsmResolver.DotNet.Serialized
{
/// <summary>
/// Represents a lazily initialized implementation of <see cref="ImplementationMap"/> that is read from a
/// .NET metadata image.
/// </summary>
public class SerializedImplementationMap : ImplementationMap
{
private readonly ModuleReaderContext _context;
private readonly ImplementationMapRow _row;
/// <summary>
/// Creates a member reference from an implementation map metadata row.
/// </summary>
/// <param name="context">The reader context.</param>
/// <param name="token">The token to initialize the mapping for.</param>
/// <param name="row">The metadata table row to base the mapping on.</param>
public SerializedImplementationMap(
ModuleReaderContext context,
MetadataToken token,
in ImplementationMapRow row)
: base(token)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_row = row;
Attributes = _row.Attributes;
}
/// <inheritdoc />
protected override IMemberForwarded GetMemberForwarded()
{
var ownerToken = _context.ParentModule.GetImplementationMapOwner(MetadataToken.Rid);
return _context.ParentModule.TryLookupMember(ownerToken, out var member)
? member as IMemberForwarded
: _context.BadImageAndReturn<IMemberForwarded>(
$"Invalid forwarded member in implementation map {MetadataToken.ToString()}.");;
}
/// <inheritdoc />
protected override string GetName() => _context.Image.DotNetDirectory.Metadata
.GetStream<StringsStream>()
.GetStringByIndex(_row.ImportName);
/// <inheritdoc />
protected override ModuleReference GetScope()
{
return _context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.ModuleRef, _row.ImportScope),
out var member)
? member as ModuleReference
: _context.BadImageAndReturn<ModuleReference>(
$"Invalid import scope in implementation map {MetadataToken.ToString()}.");
}
}
}
| using System;
using AsmResolver.PE.DotNet.Metadata.Strings;
using AsmResolver.PE.DotNet.Metadata.Tables;
using AsmResolver.PE.DotNet.Metadata.Tables.Rows;
namespace AsmResolver.DotNet.Serialized
{
/// <summary>
/// Represents a lazily initialized implementation of <see cref="ImplementationMap"/> that is read from a
/// .NET metadata image.
/// </summary>
public class SerializedImplementationMap : ImplementationMap
{
private readonly ModuleReaderContext _context;
private readonly ImplementationMapRow _row;
/// <summary>
/// Creates a member reference from an implementation map metadata row.
/// </summary>
/// <param name="context">The reader context.</param>
/// <param name="token">The token to initialize the mapping for.</param>
/// <param name="row">The metadata table row to base the mapping on.</param>
public SerializedImplementationMap(
ModuleReaderContext context,
MetadataToken token,
in ImplementationMapRow row)
: base(token)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_row = row;
Attributes = _row.Attributes;
}
/// <inheritdoc />
protected override IMemberForwarded GetMemberForwarded()
{
var ownerToken = _context.ParentModule.GetImplementationMapOwner(MetadataToken.Rid);
return _context.ParentModule.TryLookupMember(ownerToken, out var member)
? member as IMemberForwarded
: null;
}
/// <inheritdoc />
protected override string GetName() => _context.Image.DotNetDirectory.Metadata
.GetStream<StringsStream>()
.GetStringByIndex(_row.ImportName);
/// <inheritdoc />
protected override ModuleReference GetScope()
{
return _context.ParentModule.TryLookupMember(new MetadataToken(TableIndex.ModuleRef, _row.ImportScope),
out var member)
? member as ModuleReference
: null;
}
}
} | mit | C# |
1d6d9b082efa5cfcbaf8842281000d80130c042a | Fix the DataContextTypeAttribute | quartz-software/kephas,quartz-software/kephas,raimu/kephas | src/Kephas.Data/Commands/Composition/DataContextTypeAttribute.cs | src/Kephas.Data/Commands/Composition/DataContextTypeAttribute.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataContextTypeAttribute.cs" company="Quartz Software SRL">
// Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
// Implements the data context type attribute class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Data.Commands.Composition
{
using System;
using System.Diagnostics.Contracts;
using Kephas.Composition.Metadata;
/// <summary>
/// Attribute indicating the supported.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class DataContextTypeAttribute : Attribute, IMetadataValue<Type>
{
/// <summary>
/// Initializes a new instance of the <see cref="DataContextTypeAttribute"/> class.
/// </summary>
/// <param name="dataContextType">Type of the data context.</param>
public DataContextTypeAttribute(Type dataContextType)
{
Contract.Requires(dataContextType != null);
this.Value = dataContextType;
}
/// <summary>
/// Gets the associated data context type.
/// </summary>
public Type Value { get; }
/// <summary>
/// Gets the associated data context type.
/// </summary>
object IMetadataValue.Value => this.Value;
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataContextTypeAttribute.cs" company="Quartz Software SRL">
// Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
// Implements the data context type attribute class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Data.Commands.Composition
{
using System;
using System.Diagnostics.Contracts;
using Kephas.Composition.Metadata;
/// <summary>
/// Attribute indicating the supported.
/// </summary>
public class DataContextTypeAttribute : IMetadataValue<Type>
{
/// <summary>
/// Initializes a new instance of the <see cref="DataContextTypeAttribute"/> class.
/// </summary>
/// <param name="dataContextType">Type of the data context.</param>
public DataContextTypeAttribute(Type dataContextType)
{
Contract.Requires(dataContextType != null);
this.Value = dataContextType;
}
/// <summary>
/// Gets the associated data context type.
/// </summary>
public Type Value { get; }
/// <summary>
/// Gets the associated data context type.
/// </summary>
object IMetadataValue.Value => this.Value;
}
} | mit | C# |
8ec6970e17232a47d7baffee355eb966a16c247d | Update GetRelativeTime.cs | BlarghLabs/MoarUtils | commands/time/GetRelativeTime.cs | commands/time/GetRelativeTime.cs | using System;
namespace MoarUtils.commands.time {
public static class GetRelativeTime {
public static string Execute(DateTime dt) {
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
var delta = Math.Abs(ts.TotalSeconds);
if (ts.TotalSeconds < 0)
return " just now";
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH) {
var months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
} else {
var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
}
public static string ExecuteFromNullable(DateTime? dt) {
if (!dt.HasValue) {
return "";
}
return Execute(dt.Value);
}
}
}
| using System;
namespace MoarUtils.commands.time {
public static class GetRelativeTime {
public static string Execute(DateTime dt) {
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
var delta = Math.Abs(ts.TotalSeconds);
if (ts.TotalSeconds < 0)
return " just now";
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH) {
var months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
} else {
var years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
}
}
}
| mit | C# |
81f004f0aeedd4d241f23f9e7aee35de2d9bae5a | Change default user agent for web views | JosefNemec/Playnite,JosefNemec/Playnite,JosefNemec/Playnite | source/Playnite/CefTools.cs | source/Playnite/CefTools.cs | using CefSharp;
using CefSharp.Wpf;
using Playnite.Common;
using Playnite.Settings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Playnite
{
public class CefTools
{
public static bool IsInitialized { get; private set; }
public static void ConfigureCef()
{
FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath);
var settings = new CefSettings();
settings.WindowlessRenderingEnabled = true;
if (settings.CefCommandLineArgs.ContainsKey("disable-gpu"))
{
settings.CefCommandLineArgs.Remove("disable-gpu");
}
if (settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing"))
{
settings.CefCommandLineArgs.Remove("disable-gpu-compositing");
}
settings.CefCommandLineArgs.Add("disable-gpu", "1");
settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
settings.CachePath = PlaynitePaths.BrowserCachePath;
settings.PersistSessionCookies = true;
settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log");
settings.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0";
IsInitialized = Cef.Initialize(settings);
}
public static void Shutdown()
{
Cef.Shutdown();
IsInitialized = false;
}
}
}
| using CefSharp;
using CefSharp.Wpf;
using Playnite.Common;
using Playnite.Settings;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Playnite
{
public class CefTools
{
public static bool IsInitialized { get; private set; }
public static void ConfigureCef()
{
FileSystem.CreateDirectory(PlaynitePaths.BrowserCachePath);
var settings = new CefSettings();
settings.WindowlessRenderingEnabled = true;
if (settings.CefCommandLineArgs.ContainsKey("disable-gpu"))
{
settings.CefCommandLineArgs.Remove("disable-gpu");
}
if (settings.CefCommandLineArgs.ContainsKey("disable-gpu-compositing"))
{
settings.CefCommandLineArgs.Remove("disable-gpu-compositing");
}
settings.CefCommandLineArgs.Add("disable-gpu", "1");
settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
settings.CachePath = PlaynitePaths.BrowserCachePath;
settings.PersistSessionCookies = true;
settings.LogFile = Path.Combine(PlaynitePaths.ConfigRootPath, "cef.log");
IsInitialized = Cef.Initialize(settings);
}
public static void Shutdown()
{
Cef.Shutdown();
IsInitialized = false;
}
}
}
| mit | C# |
6891f4d76b8cfc2f7fd5c64fbdc5759eb1a05e3e | Update Slot.cs | kristjank/ark-net,sharkdev-j/ark-net | ark-net/Core/Slot.cs | ark-net/Core/Slot.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Slot.cs" company="Ark">
// MIT License
// //
// // Copyright (c) 2017 Kristjan Košič
// //
// // 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
namespace ArkNet.Core
{
// References:
// - TransactionApi.cs
/// <summary>
/// Provides a timer for timestamping created transactions.
/// </summary>
///
public class Slot
{
#region Fields
/// <summary>
/// The initial epoch to calculate the elapsed time from.
/// </summary>
///
private static readonly DateTime beginEpoch = new DateTime(2017, 3, 21, 13, 00, 0, DateTimeKind.Utc);
#endregion
#region Methods
/// <summary>
/// Returns the elapsed time up to the current epoch.
/// </summary>
///
/// <returns>Returns the number of seconds elapsed an <see cref="System.Int32"/>.</returns>
///
public static int GetTime()
{
//DateTime date = DateTime.Now;
return Convert.ToInt32((DateTime.UtcNow - beginEpoch).TotalMilliseconds / 1000);
}
#endregion
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Slot.cs" company="Ark Labs">
// MIT License
// //
// // Copyright (c) 2017 Kristjan Košič
// //
// // 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
namespace ArkNet.Core
{
// References:
// - TransactionApi.cs
/// <summary>
/// Provides a timer for timestamping created transactions.
/// </summary>
///
public class Slot
{
#region Fields
/// <summary>
/// The initial epoch to calculate the elapsed time from.
/// </summary>
///
private static readonly DateTime beginEpoch = new DateTime(2017, 3, 21, 13, 00, 0, DateTimeKind.Utc);
#endregion
#region Methods
/// <summary>
/// Returns the elapsed time up to the current epoch.
/// </summary>
///
/// <returns>Returns the number of seconds elapsed an <see cref="System.Int32"/>.</returns>
///
public static int GetTime()
{
//DateTime date = DateTime.Now;
return Convert.ToInt32((DateTime.UtcNow - beginEpoch).TotalMilliseconds / 1000);
}
#endregion
}
} | mit | C# |
b8e9deedcf77e26830f83a44e855d1cd79ec8e6f | Bump version to 0.9.6 | ar3cka/Journalist | src/SolutionInfo.cs | src/SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.9.6")]
[assembly: AssemblyInformationalVersionAttribute("0.9.6")]
[assembly: AssemblyFileVersionAttribute("0.9.6")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.9.6";
}
}
| // <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.9.5")]
[assembly: AssemblyInformationalVersionAttribute("0.9.5")]
[assembly: AssemblyFileVersionAttribute("0.9.5")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.9.5";
}
}
| apache-2.0 | C# |
df29ece012129a641855708f7fadd47c9f9baa04 | Remove unused property | mstrother/BmpListener | BmpListener/Bgp/OptionalParameter.cs | BmpListener/Bgp/OptionalParameter.cs | using System;
using System.Linq;
namespace BmpListener.Bgp
{
public abstract class OptionalParameter
{
public enum Type
{
Capabilities = 2
}
protected OptionalParameter(ref ArraySegment<byte> data)
{
ParameterType = (Type) data.First();
var length = data.ElementAt(1);
data = new ArraySegment<byte>(data.Array, data.Offset + 2, length);
}
public Type ParameterType { get; }
public static OptionalParameter GetOptionalParameter(ArraySegment<byte> data)
{
if ((Type) data.First() == Type.Capabilities)
return new OptionalParameterCapability(data);
return new OptionParameterUnknown(data);
}
}
} | using System;
using System.Linq;
namespace BmpListener.Bgp
{
public abstract class OptionalParameter
{
public enum Type : byte
{
Capabilities = 2
}
protected OptionalParameter(ArraySegment<byte> data)
{
ParameterType = (Type) data.First();
ParameterLength = data.ElementAt(1);
}
public Type ParameterType { get; }
public byte ParameterLength { get; }
public static OptionalParameter GetOptionalParameter(ArraySegment<byte> data)
{
if ((Type) data.First() == Type.Capabilities)
return new OptionalParameterCapability(data);
return new OptionParameterUnknown(data);
}
}
} | mit | C# |
ed264518b7dfea6d7f7366b2c03eca9baf24ec50 | Delete override keyword from Equals method to indicate that this method implement interface | witoong623/TirkxDownloader,witoong623/TirkxDownloader | Framework/Pair.cs | Framework/Pair.cs | using System;
using System.Collections.Generic;
namespace TirkxDownloader.Framework
{
public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First
{
get { return first; }
}
public TSecond Second
{
get { return second; }
}
public bool Equals(Pair<TFirst, TSecond> other)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default.Equals(first, other.first) &&
EqualityComparer<TSecond>.Default.Equals(second, other.second);
}
public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default.GetHashCode(second);
}
}
}
| using System;
using System.Collections.Generic;
namespace TirkxDownloader.Framework
{
public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First
{
get { return first; }
}
public TSecond Second
{
get { return second; }
}
public override bool Equals(Pair<TFirst, TSecond> other)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default.Equals(first, other.first) &&
EqualityComparer<TSecond>.Default.Equals(second, other.second);
}
public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default.GetHashCode(second);
}
}
}
| mit | C# |
fcc0093ffd87fab750979c342868bf7933cccd6f | Add proper constant for maximum mouse grid LEDs | WolfspiritM/Colore,CoraleStudios/Colore | Corale.Colore/Razer/Mouse/Constants.cs | Corale.Colore/Razer/Mouse/Constants.cs | // ---------------------------------------------------------------------------------------
// <copyright file="Constants.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Razer.Mouse
{
/// <summary>
/// Mouse constants.
/// </summary>
public static class Constants
{
/// <summary>
/// Maximum number of custom LEDs.
/// </summary>
public const int MaxLeds = 30;
/// <summary>
/// Maximum number of LED rows.
/// </summary>
public const int MaxRows = 9;
/// <summary>
/// Maximum number of LED columns.
/// </summary>
public const int MaxColumns = 7;
/// <summary>
/// Maximum number of LEDs on the grid layout.
/// </summary>
public const int MaxGridLeds = MaxRows * MaxColumns;
}
}
| // ---------------------------------------------------------------------------------------
// <copyright file="Constants.cs" company="Corale">
// Copyright © 2015 by Adam Hellberg and Brandon Scott.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// "Razer" is a trademark of Razer USA Ltd.
// </copyright>
// ---------------------------------------------------------------------------------------
namespace Corale.Colore.Razer.Mouse
{
/// <summary>
/// Mouse constants.
/// </summary>
public static class Constants
{
/// <summary>
/// Maximum number of custom LEDs.
/// </summary>
public const int MaxLeds = 30;
/// <summary>
/// Maximum number of LED rows.
/// </summary>
public const int MaxRows = 9;
/// <summary>
/// Maximum number of LED columns.
/// </summary>
public const int MaxColumns = 7;
}
}
| mit | C# |
3b83d3cdc1865438fec3c9109117eb115d0323db | drop pieces on a timer | JayBazuzi/BazuziTetris | Source/Program.cs | Source/Program.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BazuziTetris
{
class Program
{
static void Main(string[] args)
{
Game game = new Game();
Console.Clear();
Console.WriteLine(game);
var keyThread = new Thread(
() =>
{
do
{
var consoleKeyInfo = Console.ReadKey();
switch (consoleKeyInfo.Key)
{
case ConsoleKey.DownArrow:
game.CurrentPieceDropOneStep();
break;
case ConsoleKey.Spacebar:
game.DropAllTheWay();
break;
case ConsoleKey.UpArrow:
game.CurrentPieceRotate();
break;
case ConsoleKey.LeftArrow:
game.MoveLeft();
break;
case ConsoleKey.RightArrow:
game.MoveRight();
break;
}
Console.Clear();
Console.WriteLine(game);
} while (true);
}
);
keyThread.Start();
do
{
Thread.Sleep(1000);
game.OnTick();
Console.Clear();
Console.WriteLine(game);
} while (true);
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BazuziTetris
{
class Program
{
static void Main(string[] args)
{
Game game = new Game();
do
{
Console.Clear();
Console.WriteLine(game);
var consoleKeyInfo = Console.ReadKey();
switch (consoleKeyInfo.Key)
{
case ConsoleKey.DownArrow:
game.CurrentPieceDropOneStep();
break;
case ConsoleKey.Spacebar:
game.DropAllTheWay();
break;
case ConsoleKey.UpArrow:
game.CurrentPieceRotate();
break;
case ConsoleKey.LeftArrow:
game.MoveLeft();
break;
case ConsoleKey.RightArrow:
game.MoveRight();
break;
}
} while (true);
}
}
}
| mit | C# |
fc9daf36112bc68a3437ed34f941f3ca0f735db1 | Fix ImpersonationHandle so that it survives multiple disposes. | antiduh/nsspi | Contexts/ImpersonationHandle.cs | Contexts/ImpersonationHandle.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Contexts
{
public class ImpersonationHandle : IDisposable
{
// Notes:
// Impersonate:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa375497(v=vs.85).aspx
//
// Revert:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa379446(v=vs.85).aspx
//
// QuerySecurityPkgInfo (to learn if it supports impersonation):
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa379359(v=vs.85).aspx
private bool disposed;
private ServerContext server;
internal ImpersonationHandle(ServerContext server)
{
this.server = server;
this.disposed = false;
}
~ImpersonationHandle()
{
Dispose( false );
}
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
if( disposing && this.disposed == false && this.server != null && this.server.Disposed == false )
{
this.server.RevertImpersonate();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSspi.Contexts
{
public class ImpersonationHandle : IDisposable
{
// Notes:
// Impersonate:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa375497(v=vs.85).aspx
//
// Revert:
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa379446(v=vs.85).aspx
//
// QuerySecurityPkgInfo (to learn if it supports impersonation):
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa379359(v=vs.85).aspx
private bool disposed;
private ServerContext server;
internal ImpersonationHandle(ServerContext server)
{
this.server = server;
}
~ImpersonationHandle()
{
Dispose( false );
}
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
if( disposing && this.server != null && this.server.Disposed == false )
{
this.server.RevertImpersonate();
}
}
}
}
| bsd-2-clause | C# |
bfe37b5316e6c2cfa43f3f440820917860d3725c | Add WIP and Labels to MergeRequest model | Xarlot/NGitLab,maikebing/NGitLab | NGitLab/NGitLab/Models/MergeRequest.cs | NGitLab/NGitLab/Models/MergeRequest.cs | using System;
using System.Runtime.Serialization;
namespace NGitLab.Models
{
[DataContract]
public class MergeRequest
{
public const string Url = "/merge_requests";
[DataMember(Name = "id")]
public int Id;
[DataMember(Name = "iid")]
public int Iid;
[DataMember(Name = "state")]
public string State;
[DataMember(Name = "title")]
public string Title;
[DataMember(Name = "assignee")]
public User Assignee;
[DataMember(Name = "author")]
public User Author;
[DataMember(Name = "created_at")]
public DateTime CreatedAt;
[DataMember(Name = "description")]
public string Description;
[DataMember(Name = "downvotes")]
public int Downvotes;
[DataMember(Name = "upvotes")]
public int Upvotes;
[DataMember(Name = "updated_at")]
public DateTime UpvotedAt;
[DataMember(Name="target_branch")]
public string TargetBranch;
[DataMember(Name="source_branch")]
public string SourceBranch;
[DataMember(Name="project_id")]
public int ProjectId;
[DataMember(Name="source_project_id")]
public int SourceProjectId;
[DataMember(Name = "target_project_id")]
public int TargetProjectId;
[DataMember(Name = "work_in_progress")]
public bool? WorkInProgress;
[DataMember(Name = "labels")]
public Collection<string> Labels;
}
} | using System;
using System.Runtime.Serialization;
namespace NGitLab.Models
{
[DataContract]
public class MergeRequest
{
public const string Url = "/merge_requests";
[DataMember(Name = "id")]
public int Id;
[DataMember(Name = "iid")]
public int Iid;
[DataMember(Name = "state")]
public string State;
[DataMember(Name = "title")]
public string Title;
[DataMember(Name = "assignee")]
public User Assignee;
[DataMember(Name = "author")]
public User Author;
[DataMember(Name = "created_at")]
public DateTime CreatedAt;
[DataMember(Name = "description")]
public string Description;
[DataMember(Name = "downvotes")]
public int Downvotes;
[DataMember(Name = "upvotes")]
public int Upvotes;
[DataMember(Name = "updated_at")]
public DateTime UpvotedAt;
[DataMember(Name="target_branch")]
public string TargetBranch;
[DataMember(Name="source_branch")]
public string SourceBranch;
[DataMember(Name="project_id")]
public int ProjectId;
[DataMember(Name="source_project_id")]
public int SourceProjectId;
[DataMember(Name = "target_project_id")]
public int TargetProjectId;
}
} | mit | C# |
882611602117e6acb83a0f39595ddb01f215c7e9 | fix structure | noto0648/OrangeNBT | OrangeNBT.Data/Format/StructureBase.cs | OrangeNBT.Data/Format/StructureBase.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using OrangeNBT.NBT;
namespace OrangeNBT.Data.Format
{
public abstract class StructureBase
{
protected readonly int _width;
protected readonly int _height;
protected readonly int _length;
public int Width => _width;
public int Height => _height;
public int Length => _length;
public StructureBase(int width, int height, int length)
{
_width = width;
_height = height;
_length = length;
}
public StructureBase(Cuboid cuboid)
: this(cuboid.Width, cuboid.Height, cuboid.Length)
{ }
public class EntityCollection : IEntityCollection, ITagProvider<TagList>
{
private TagList _entities;
public EntityCollection(TagList tagList)
{
_entities = tagList;
}
public EntityCollection()
{
_entities = new TagList("Entities");
}
public void Add(TagCompound tag)
{
_entities.Add(tag);
}
public void Add(TagCompound tag, bool safe)
{
if ((safe && Entity.IsEntityTag(tag)) || !safe)
Add(tag);
}
public TagList BuildTag()
{
return _entities;
}
public IEnumerator<TagCompound> GetEnumerator()
{
foreach(TagBase t in _entities)
{
TagCompound c = t as TagCompound;
if (c != null)
yield return t as TagCompound;
}
}
public IEnumerable<TagCompound> GetWithin(Cuboid area)
{
foreach (TagCompound e in _entities)
{
Position pos = Entity.GetPosition(e);
if (area.Contains(pos.X, pos.Y, pos.Z))
{
yield return e;
}
}
}
public void Remove(TagCompound tag)
{
_entities.Remove(tag);
}
IEnumerator IEnumerable.GetEnumerator()
{
return _entities.GetEnumerator();
}
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using OrangeNBT.NBT;
namespace OrangeNBT.Data.Format
{
public abstract class StructureBase
{
protected readonly int _width;
protected readonly int _height;
protected readonly int _length;
public int Width => _width;
public int Height => _height;
public int Length => _length;
public StructureBase(int width, int height, int length)
{
_width = width;
_height = height;
_length = length;
}
public StructureBase(Cuboid cuboid)
: this(cuboid.Width, cuboid.Height, cuboid.Length)
{ }
public class EntityCollection : IEntityCollection, ITagProvider<TagList>
{
private TagList _entities;
public EntityCollection(TagList tagList)
{
_entities = tagList;
}
public EntityCollection()
{
_entities = new TagList("Entities");
}
public void Add(TagCompound tag)
{
_entities.Add(tag);
}
public void Add(TagCompound tag, bool safe)
{
if ((safe && Entity.IsEntityTag(tag)) || !safe)
Add(tag);
}
public TagList BuildTag()
{
return _entities;
}
public IEnumerator<TagCompound> GetEnumerator()
{
return (IEnumerator<TagCompound>)_entities.GetEnumerator();
}
public IEnumerable<TagCompound> GetWithin(Cuboid area)
{
foreach (TagCompound e in _entities)
{
Position pos = Entity.GetPosition(e);
if (area.Contains(pos.X, pos.Y, pos.Z))
{
yield return e;
}
}
}
public void Remove(TagCompound tag)
{
_entities.Remove(tag);
}
IEnumerator IEnumerable.GetEnumerator()
{
return _entities.GetEnumerator();
}
}
}
}
| mit | C# |
01244010c2b390913e2b94807a91e340c9237916 | Handle null move used when the pokemon must skip the turn | NextLight/PokeBattle_Server | PokeBattle/PokeBattle/Battle.cs | PokeBattle/PokeBattle/Battle.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PokeBattle
{
class Battle
{
Pokemon[] pokemons;
Random rand;
// TODO: use in-battle stats
public Battle(Pokemon p1, Pokemon p2)
{
this.pokemons = new Pokemon[] { p1, p2 };
rand = new Random();
}
public void ExecuteMoves(int? m1, int? m2)
{
if (m2 == null || m1 != null && pokemons[0].Speed > pokemons[1].Speed)
ExecuteMove(0, m1.Value);
else
ExecuteMove(1, m2.Value);
}
private void ExecuteMove(int p, int m)
{
Move move = pokemons[p].Moves[m];
if ((move.Accuracy ?? 100) >= rand.Next(101))
{
if (move.DamageClass != DamageClass.None && move.Power != null)
{
bool critical = rand.Next(16) == 0;
int damage = CalculateDamage(pokemons[p].Level, move.Power.Value,
move.DamageClass == DamageClass.Physical ? pokemons[p].Attack : pokemons[p].SpecialAttack,
move.DamageClass == DamageClass.Physical ? pokemons[p ^ 1].Defense : pokemons[p ^ 1].SpecialDefense);
if (pokemons[p].Types.Item1 == move.TypeId || pokemons[p].Types.Item2 == move.TypeId)
damage = damage * 3 / 2;
if (critical)
damage = damage * 3 / 2;
damage = (int)(damage * PokeBox.TypeEfficacy(move.TypeId, pokemons[p ^ 1].Types));
pokemons[p ^ 1].InBattle.Hp -= damage;
}
}
}
private int CalculateDamage(int level, int power, int offensive, int defensive)
{
return (2 * level / 5 + 2) * offensive * power / defensive / 50 + 2;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PokeBattle
{
class Battle
{
Pokemon[] pokemons;
Random rand;
public Battle(Pokemon p1, Pokemon p2)
{
this.pokemons = new Pokemon[] { p1, p2 };
rand = new Random();
}
public void ExecuteMoves(int m1, int m2)
{
if (pokemons[0].Speed > pokemons[1].Speed)
ExecuteMove(0, m1);
else
ExecuteMove(1, m2);
}
private void ExecuteMove(int p, int m)
{
Move move = pokemons[p].Moves[m];
if ((move.Accuracy ?? 100) >= rand.Next(101))
{
if (move.DamageClass != DamageClass.None && move.Power != null)
{
bool critical = rand.Next(16) == 0;
int damage = CalculateDamage(pokemons[p].Level, move.Power.Value,
move.DamageClass == DamageClass.Physical ? pokemons[p].Attack : pokemons[p].SpecialAttack,
move.DamageClass == DamageClass.Physical ? pokemons[p ^ 1].Defense : pokemons[p ^ 1].SpecialDefense);
if (pokemons[p].Types.Item1 == move.TypeId || pokemons[p].Types.Item2 == move.TypeId)
damage = damage * 3 / 2;
if (critical)
damage = damage * 3 / 2;
damage = (int)(damage * PokeBox.TypeEfficacy(move.TypeId, pokemons[p ^ 1].Types));
pokemons[p ^ 1].InBattle.Hp -= damage;
}
}
}
private int CalculateDamage(int level, int power, int offensive, int defensive)
{
return (2 * level / 5 + 2) * offensive * power / defensive / 50 + 2;
}
}
}
| mit | C# |
1ccf616cdeb520dfae32a4bb92fd133a0be65472 | remove warning | zericco/Elite-Insight,zericco/Elite-Insight | RegulatedNoise.Test/EddnTest.cs | RegulatedNoise.Test/EddnTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RegulatedNoise.Core.DomainModel;
using RegulatedNoise.Enums_and_Utility_Classes;
namespace RegulatedNoise.Test
{
[TestClass]
public class EddnTest
{
[TestMethod]
[Ignore]
// activate only when build with NO_PATH_INIT set
public void i_can_instantiate()
{
using (var eddn = NewEddn()) { }
}
[TestMethod]
[Ignore]
// activate only when build with NO_PATH_INIT set
// have to delay dispose to wait 10s eddn message queue polling
// test will be upgraded when dispatcher queue will be used
public void i_can_send_a_marketdata()
{
using (var eddn = NewEddn())
{
eddn.SendToEddn(new MarketDataRow() { CommodityName = "Tea", BuyPrice = 1234, SampleDate = DateTime.Now, StationName = "myStation", SystemName = "mySystem"});
}
}
private static Eddn NewEddn()
{
return new Eddn(ApplicationContext.CommoditiesLocalisation, ApplicationContext.RegulatedNoiseSettings) { TestMode = true };
}
}
} | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RegulatedNoise.Core.DomainModel;
using RegulatedNoise.Enums_and_Utility_Classes;
namespace RegulatedNoise.Test
{
[TestClass]
public class EddnTest
{
[TestMethod]
[Ignore]
// activate only when build with NO_PATH_INIT set
public void i_can_instantiate()
{
using (var eddn = NewEddn()) ;
}
[TestMethod]
[Ignore]
// activate only when build with NO_PATH_INIT set
// have to delay dispose to wait 10s eddn message queue polling
// test will be upgraded when dispatcher queue will be used
public void i_can_send_a_marketdata()
{
using (var eddn = NewEddn())
{
eddn.SendToEddn(new MarketDataRow() { CommodityName = "Tea", BuyPrice = 1234, SampleDate = DateTime.Now, StationName = "myStation", SystemName = "mySystem"});
}
}
private static Eddn NewEddn()
{
return new Eddn(ApplicationContext.CommoditiesLocalisation, ApplicationContext.RegulatedNoiseSettings) { TestMode = true };
}
}
} | mit | C# |
06e92f7e92dc026c255d329404017ac2d8c24872 | Return instead of using a variable. | airbrake/SharpBrake,kayoom/SharpBrake,cbtnuggets/SharpBrake,airbrake/SharpBrake | Tests/AirbrakeValidator.cs | Tests/AirbrakeValidator.cs | using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using NUnit.Framework;
namespace SharpBrake.Tests
{
public class AirbrakeValidator
{
public static void ValidateSchema(string xml)
{
var schema = GetXmlSchema();
XmlReaderSettings settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema,
};
var errorBuffer = new StringBuilder();
settings.ValidationEventHandler += (sender, args) => errorBuffer.AppendLine(args.Message);
settings.Schemas.Add(schema);
using (var reader = new StringReader(xml))
{
using (var xmlReader = new XmlTextReader(reader))
{
using (var validator = XmlReader.Create(xmlReader, settings))
{
while (validator.Read())
{
}
}
}
}
if (errorBuffer.Length > 0)
Assert.Fail(errorBuffer.ToString());
}
private static XmlSchema GetXmlSchema()
{
Type clientType = typeof(AirbrakeClient);
const string xsd = "hoptoad_2_1.xsd";
using (Stream schemaStream = clientType.Assembly.GetManifestResourceStream(clientType, xsd))
{
if (schemaStream == null)
Assert.Fail("{0}.{1} not found.", clientType.Namespace, xsd);
return XmlSchema.Read(schemaStream, (sender, args) => { });
}
}
}
} | using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using NUnit.Framework;
namespace SharpBrake.Tests
{
public class AirbrakeValidator
{
public static void ValidateSchema(string xml)
{
var schema = GetXmlSchema();
XmlReaderSettings settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema,
};
var errorBuffer = new StringBuilder();
settings.ValidationEventHandler += (sender, args) => errorBuffer.AppendLine(args.Message);
settings.Schemas.Add(schema);
using (var reader = new StringReader(xml))
{
using (var xmlReader = new XmlTextReader(reader))
{
using (var validator = XmlReader.Create(xmlReader, settings))
{
while (validator.Read())
{
}
}
}
}
if (errorBuffer.Length > 0)
Assert.Fail(errorBuffer.ToString());
}
private static XmlSchema GetXmlSchema()
{
const string xsd = "hoptoad_2_1.xsd";
Type clientType = typeof(AirbrakeClient);
XmlSchema schema;
using (Stream schemaStream = clientType.Assembly.GetManifestResourceStream(clientType, xsd))
{
if (schemaStream == null)
Assert.Fail("{0}.{1} not found.", clientType.Namespace, xsd);
schema = XmlSchema.Read(schemaStream, (sender, args) => { });
}
return schema;
}
}
} | mit | C# |
9a3abe3e714ce41b3918ef0bd4ce705d635cd86b | Revert "Dictionary Initializer setup" | BillWagner/TourOfCSharp6 | TourOfCSharp6/Program.cs | TourOfCSharp6/Program.cs | using System;
using System.Linq.Enumerable;
namespace TourOfCSharp6
{
class Program
{
static void Main(string[] args)
{
var random = new System.Random();
var range = Range(1, 100);
var sequence = from n in range
select new Point(
random.NextDouble() * 1000,
random.NextDouble() * 1000
);
var sequence2 = range
.Select(n => new Point
(
random.NextDouble() * 1000,
random.NextDouble() * 1000
));
// Should not compile, but does with VS2015 14.0.22310.1
var sequence3 = Select(range, n => new Point
(
random.NextDouble() * 1000,
random.NextDouble() * 1000
));
foreach (var item in sequence)
Console.WriteLine(item);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq.Enumerable;
namespace TourOfCSharp6
{
class Program
{
static void Main(string[] args)
{
var vector = new Dictionary<string, Point>();
vector["start"] = new Point(0, 0);
vector["end"] = new Point(3, 4);
//PartOne();
}
private static void PartOne()
{
var random = new System.Random();
var range = Range(1, 100);
var sequence = from n in range
select new Point(
random.NextDouble() * 1000,
random.NextDouble() * 1000
);
var sequence2 = range
.Select(n => new Point
(
random.NextDouble() * 1000,
random.NextDouble() * 1000
));
// Should not compile, but does with VS2015 14.0.22310.1
var sequence3 = Select(range, n => new Point
(
random.NextDouble() * 1000,
random.NextDouble() * 1000
));
foreach (var item in sequence)
Console.WriteLine(item);
}
}
}
| mit | C# |
01d290491c2773b420e18552bd1243479e9af263 | Fix Util indentation | ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot,ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot,ukahoot/ukahoot.github.io | TokenServer/src/Util.cs | TokenServer/src/Util.cs | using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace UKahoot {
public static class Util {
public const string TOKEN_ENDPOINT = "https://kahoot.it/reserve/session/";
public const string ENDPOINT_URI = "https://kahoot.it/";
public const string ENDPOINT_HOST = "kahoot.it";
public static int UsageLog = 0;
public static byte[] GetBytes(string txt) {
return Encoding.ASCII.GetBytes(txt);
}
public static class Responses {
public static byte[] InvalidMethod = GetBytes("<html><body><h1>Invalid HTTP Method</h1></body></html>");
public static byte[] RequestError = GetBytes("<html><body><h1>Request Processing Error</h1></body></html>");
public static byte[] InvalidQueryString = GetBytes("<html><body><h1>Invalid Query String</h1></body></html>");
public static byte[] InvalidRequest = GetBytes("<html><body><h1>Invalid Request</h1></body></html>");
}
public static int GetKahootTime() {
var TimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (int)TimeSpan.TotalSeconds;
}
public static string GetTokenRequestUri(int PID) {
return TOKEN_ENDPOINT + "/" + PID + "/?" + GetKahootTime();
}
public static string GetTokenResponse(string TokenHeader, string ResponseBody) {
// Replace and escape quotes to make valid JSON
ResponseBody = ResponseBody.Replace("\\\"", "%ESCAPED_QUOT%");
ResponseBody = ResponseBody.Replace("\"", "\\\"");
ResponseBody = ResponseBody.Replace("%ESCAPED_QUOT%", "\\\"");
// Build the JSON string
StringBuilder TokenBuilder = new StringBuilder("");
TokenBuilder.Append("{\"tokenHeader\":\"");
TokenBuilder.Append(TokenHeader);
TokenBuilder.Append("\"");
TokenBuilder.Append(",\"responseBody\":");
TokenBuilder.Append("\"");
TokenBuilder.Append(ResponseBody);
TokenBuilder.Append("\"}");
return TokenBuilder.ToString();
}
public static string GetErrorResponse(string ResponseCode) {
StringBuilder ErrorBuilder = new StringBuilder("");
ErrorBuilder.Append("{\"error\":true,");
ErrorBuilder.Append("\"responseCode\":");
ErrorBuilder.Append("\"");
ErrorBuilder.Append(ResponseCode);
ErrorBuilder.Append("\"}");
return ErrorBuilder.ToString();
}
public static void LogMemUsage() {
// For tests and debugging
double Memory = (double)GC.GetTotalMemory(false) * 0.000001;
Console.WriteLine("MemLog" + UsageLog + ": Current Memory Usage: " + Memory + "MB");
UsageLog++;
}
}
}
| using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace UKahoot {
public static class Util {
public const string TOKEN_ENDPOINT = "https://kahoot.it/reserve/session/";
public const string ENDPOINT_URI = "https://kahoot.it/";
public const string ENDPOINT_HOST = "kahoot.it";
public static int UsageLog = 0;
public static byte[] GetBytes(string txt) {
return Encoding.ASCII.GetBytes(txt);
}
public static class Responses {
public static byte[] InvalidMethod = GetBytes("<html><body><h1>Invalid HTTP Method</h1></body></html>");
public static byte[] RequestError = GetBytes("<html><body><h1>Request Processing Error</h1></body></html>");
public static byte[] InvalidQueryString = GetBytes("<html><body><h1>Invalid Query String</h1></body></html>");
public static byte[] InvalidRequest = GetBytes("<html><body><h1>Invalid Request</h1></body></html>");
}
public static int GetKahootTime() {
var TimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (int)TimeSpan.TotalSeconds;
}
public static string GetTokenRequestUri(int PID) {
return TOKEN_ENDPOINT + "/" + PID + "/?" + GetKahootTime();
}
public static string GetTokenResponse(string TokenHeader, string ResponseBody) {
// Replace and escape quotes to make valid JSON
ResponseBody = ResponseBody.Replace("\\\"", "%ESCAPED_QUOT%");
ResponseBody = ResponseBody.Replace("\"", "\\\"");
ResponseBody = ResponseBody.Replace("%ESCAPED_QUOT%", "\\\"");
// Build the JSON string
StringBuilder TokenBuilder = new StringBuilder("");
TokenBuilder.Append("{\"tokenHeader\":\"");
TokenBuilder.Append(TokenHeader);
TokenBuilder.Append("\"");
TokenBuilder.Append(",\"responseBody\":");
TokenBuilder.Append("\"");
TokenBuilder.Append(ResponseBody);
TokenBuilder.Append("\"}");
return TokenBuilder.ToString();
}
public static string GetErrorResponse(string ResponseCode) {
StringBuilder ErrorBuilder = new StringBuilder("");
ErrorBuilder.Append("{\"error\":true,");
ErrorBuilder.Append("\"responseCode\":");
ErrorBuilder.Append("\"");
ErrorBuilder.Append(ResponseCode);
ErrorBuilder.Append("\"}");
return ErrorBuilder.ToString();
}
public static void LogMemUsage() {
// For tests and debugging
double Memory = (double)GC.GetTotalMemory(false) * 0.000001;
Console.WriteLine("MemLog" + UsageLog + ": Current Memory Usage: " + Memory + "MB");
UsageLog++;
}
}
} | mit | C# |
2e6fe588cbafb60a6e66d2233ca54e10d0e84482 | Change log file dir | LibertyLocked/webscripthook,LibertyLocked/webscripthook,LibertyLocked/webscripthook,LibertyLocked/webscripthook | VStats-plugin/Logger.cs | VStats-plugin/Logger.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace VStats_plugin
{
public static class Logger
{
public static void Log(object message)
{
#if DEBUG
File.AppendAllText(@".\scripts\VStats.log", DateTime.Now + " : " + message + Environment.NewLine);
#endif
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace VStats_plugin
{
public static class Logger
{
public static void Log(object message)
{
#if DEBUG
File.AppendAllText(@"VStats.log", DateTime.Now + " : " + message + Environment.NewLine);
#endif
}
}
}
| mit | C# |
c6ade0dbdc7756ecb18928d7adf6e26634ff7c34 | Remove unused construdtor. | modulexcite/msgpack-cli,msgpack/msgpack-cli,scopely/msgpack-cli,msgpack/msgpack-cli,undeadlabs/msgpack-cli,modulexcite/msgpack-cli,undeadlabs/msgpack-cli,scopely/msgpack-cli | cli/src/MsgPack/StreamPacker.cs | cli/src/MsgPack/StreamPacker.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.IO;
namespace MsgPack
{
/// <summary>
/// Basic <see cref="Packer"/> implementation using managed <see cref="Stream"/>.
/// </summary>
internal class StreamPacker : Packer
{
private readonly Stream _stream;
private readonly bool _ownsStream;
public sealed override bool CanSeek
{
get { return this._stream.CanSeek; }
}
public sealed override long Position
{
get { return this._stream.Position; }
}
public StreamPacker( Stream output, bool ownsStream )
{
this._stream = output;
this._ownsStream = ownsStream;
}
protected sealed override void Dispose( bool disposing )
{
if ( this._ownsStream )
{
this._stream.Dispose();
}
base.Dispose( disposing );
}
protected sealed override void SeekTo( long offset )
{
if ( !this.CanSeek )
{
throw new NotSupportedException();
}
this._stream.Seek( offset, SeekOrigin.Current );
}
protected sealed override void WriteByte( byte value )
{
this._stream.WriteByte( value );
}
protected sealed override void WriteBytes( byte[] asArray, bool isImmutable )
{
this._stream.Write( asArray, 0, asArray.Length );
}
}
}
| #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.IO;
namespace MsgPack
{
/// <summary>
/// Basic <see cref="Packer"/> implementation using managed <see cref="Stream"/>.
/// </summary>
internal class StreamPacker : Packer
{
private readonly Stream _stream;
private readonly bool _ownsStream;
public sealed override bool CanSeek
{
get { return this._stream.CanSeek; }
}
public sealed override long Position
{
get { return this._stream.Position; }
}
public StreamPacker( Stream output ) : this( output, true ) { }
public StreamPacker( Stream output, bool ownsStream )
{
this._stream = output;
this._ownsStream = ownsStream;
}
protected sealed override void Dispose( bool disposing )
{
if ( this._ownsStream )
{
this._stream.Dispose();
}
base.Dispose( disposing );
}
protected sealed override void SeekTo( long offset )
{
if ( !this.CanSeek )
{
throw new NotSupportedException();
}
this._stream.Seek( offset, SeekOrigin.Current );
}
protected sealed override void WriteByte( byte value )
{
this._stream.WriteByte( value );
}
protected sealed override void WriteBytes( byte[] asArray, bool isImmutable )
{
this._stream.Write( asArray, 0, asArray.Length );
}
}
}
| apache-2.0 | C# |
cd10af633cdab398e9cf443c1677d087288ae769 | Remove unused private method | ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu | osu.Game/Configuration/SessionStatics.cs | osu.Game/Configuration/SessionStatics.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays;
namespace osu.Game.Configuration
{
/// <summary>
/// Stores global per-session statics. These will not be stored after exiting the game.
/// </summary>
public class SessionStatics : InMemoryConfigManager<Static>
{
protected override void InitialiseDefaults()
{
SetDefault(Static.LoginOverlayDisplayed, false);
SetDefault(Static.MutedAudioNotificationShownOnce, false);
SetDefault(Static.LowBatteryNotificationShownOnce, false);
SetDefault(Static.LastHoverSoundPlaybackTime, (double?)null);
SetDefault<APISeasonalBackgrounds>(Static.SeasonalBackgrounds, null);
}
/// <summary>
/// Revert statics to their defaults after being idle for appropriate amount of time.
/// </summary>
/// <remarks>
/// This only affects a subset of statics which the user would expect to have reset after a break.
/// </remarks>
public void ResetAfterInactivity()
{
GetBindable<bool>(Static.LoginOverlayDisplayed).SetDefault();
GetBindable<bool>(Static.MutedAudioNotificationShownOnce).SetDefault();
GetBindable<bool>(Static.LowBatteryNotificationShownOnce).SetDefault();
GetBindable<double?>(Static.LastHoverSoundPlaybackTime).SetDefault();
}
}
public enum Static
{
LoginOverlayDisplayed,
MutedAudioNotificationShownOnce,
LowBatteryNotificationShownOnce,
/// <summary>
/// Info about seasonal backgrounds available fetched from API - see <see cref="APISeasonalBackgrounds"/>.
/// Value under this lookup can be <c>null</c> if there are no backgrounds available (or API is not reachable).
/// </summary>
SeasonalBackgrounds,
/// <summary>
/// The last playback time in milliseconds of a hover sample (from <see cref="HoverSounds"/>).
/// Used to debounce hover sounds game-wide to avoid volume saturation, especially in scrolling views with many UI controls like <see cref="SettingsOverlay"/>.
/// </summary>
LastHoverSoundPlaybackTime
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays;
namespace osu.Game.Configuration
{
/// <summary>
/// Stores global per-session statics. These will not be stored after exiting the game.
/// </summary>
public class SessionStatics : InMemoryConfigManager<Static>
{
protected override void InitialiseDefaults()
{
SetDefault(Static.LoginOverlayDisplayed, false);
SetDefault(Static.MutedAudioNotificationShownOnce, false);
SetDefault(Static.LowBatteryNotificationShownOnce, false);
SetDefault(Static.LastHoverSoundPlaybackTime, (double?)null);
SetDefault<APISeasonalBackgrounds>(Static.SeasonalBackgrounds, null);
}
/// <summary>
/// Revert statics to their defaults after being idle for appropriate amount of time.
/// </summary>
/// <remarks>
/// This only affects a subset of statics which the user would expect to have reset after a break.
/// </remarks>
public void ResetAfterInactivity()
{
GetBindable<bool>(Static.LoginOverlayDisplayed).SetDefault();
GetBindable<bool>(Static.MutedAudioNotificationShownOnce).SetDefault();
GetBindable<bool>(Static.LowBatteryNotificationShownOnce).SetDefault();
GetBindable<double?>(Static.LastHoverSoundPlaybackTime).SetDefault();
}
private void ensureDefault<T>(Bindable<T> bindable) => bindable.SetDefault();
}
public enum Static
{
LoginOverlayDisplayed,
MutedAudioNotificationShownOnce,
LowBatteryNotificationShownOnce,
/// <summary>
/// Info about seasonal backgrounds available fetched from API - see <see cref="APISeasonalBackgrounds"/>.
/// Value under this lookup can be <c>null</c> if there are no backgrounds available (or API is not reachable).
/// </summary>
SeasonalBackgrounds,
/// <summary>
/// The last playback time in milliseconds of a hover sample (from <see cref="HoverSounds"/>).
/// Used to debounce hover sounds game-wide to avoid volume saturation, especially in scrolling views with many UI controls like <see cref="SettingsOverlay"/>.
/// </summary>
LastHoverSoundPlaybackTime
}
}
| mit | C# |
5a1654893223486ca082e6456c8994a25c377ae4 | Update vendor api to ensure task returned | stoiveyp/Alexa.NET.Management | Alexa.NET.Management/IVendorApi.cs | Alexa.NET.Management/IVendorApi.cs | using System.Threading.Tasks;
using Alexa.NET.Management.Vendors;
using Refit;
namespace Alexa.NET.Management
{
[Headers("Authorization: Bearer")]
public interface IVendorApi
{
[Get("/vendors")]
Task<Vendor[]> Get();
}
}
| using Alexa.NET.Management.Vendors;
using Refit;
namespace Alexa.NET.Management
{
[Headers("Authorization: Bearer")]
public interface IVendorApi
{
[Get("/vendors")]
Vendor[] Get();
}
}
| mit | C# |
c4d5b31f43973a5b963757324aa472a0e4ba4691 | Create v0.5 package. | Steve-Fenton/CAPTTIA,Steve-Fenton/CAPTTIA | Capttia/Properties/AssemblyInfo.cs | Capttia/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Capttia")]
[assembly: AssemblyDescription("CAPTTIA - Completely Automated Public Turing test That Isn't Annoying.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Capttia")]
[assembly: AssemblyCopyright("Copyright © Steve Fenton 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("6465f2ec-ed0c-4986-a740-bb2aba3eac9f")]
[assembly: AssemblyVersion("0.5.0.0")]
[assembly: AssemblyFileVersion("0.5.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Capttia")]
[assembly: AssemblyDescription("CAPTTIA - Completely Automated Public Turing test That Isn't Annoying.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Capttia")]
[assembly: AssemblyCopyright("Copyright © Steve Fenton 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("6465f2ec-ed0c-4986-a740-bb2aba3eac9f")]
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]
| apache-2.0 | C# |
893fdcd524fa379e21c16c7bba201ac706f6f206 | remove required attribute for ExpectedPreviousToken in AudioItemStream | stoiveyp/alexa-skills-dotnet,timheuer/alexa-skills-dotnet | Alexa.NET/Response/Directive/AudioItemStream.cs | Alexa.NET/Response/Directive/AudioItemStream.cs | using Newtonsoft.Json;
namespace Alexa.NET.Response.Directive
{
public class AudioItemStream
{
[JsonRequired]
[JsonProperty("url")]
public string Url { get; set; }
[JsonRequired]
[JsonProperty("token")]
public string Token { get; set; }
[JsonProperty("expectedPreviousToken")]
public string ExpectedPreviousToken { get; set; }
[JsonRequired]
[JsonProperty("offsetInMilliseconds")]
public int OffsetInMilliseconds { get; set; }
}
}
| using Newtonsoft.Json;
namespace Alexa.NET.Response.Directive
{
public class AudioItemStream
{
[JsonRequired]
[JsonProperty("url")]
public string Url { get; set; }
[JsonRequired]
[JsonProperty("token")]
public string Token { get; set; }
[JsonRequired]
[JsonProperty("expectedPreviousToken")]
public string ExpectedPreviousToken { get; set; }
[JsonRequired]
[JsonProperty("offsetInMilliseconds")]
public int OffsetInMilliseconds { get; set; }
}
}
| mit | C# |
1f3a453c1ec7cda8f8595285d2062e5052b83f92 | Fix a bug where procedural model panel crashes app when effects are loaded | effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer,effekseer/Effekseer | Dev/Editor/Effekseer/GUI/Dock/ProcedualModel.cs | Dev/Editor/Effekseer/GUI/Dock/ProcedualModel.cs | using System;
using Effekseer.Data;
namespace Effekseer.GUI.Dock
{
class ProcedualModel : DockPanel
{
readonly Component.ParameterList paramerterList = null;
public ProcedualModel()
{
Label = Icons.PanelDynamicParams + Resources.GetString("ProcedualModel_Name") + "###ProcedualModel";
paramerterList = new Component.ParameterList();
Core.OnAfterLoad += OnAfterLoad;
Core.OnAfterNew += OnAfterLoad;
Core.OnBeforeLoad += Core_OnBeforeLoad;
Read();
TabToolTip = Resources.GetString("ProcedualModel_Name");
}
public void FixValues()
{
paramerterList.FixValues();
}
public override void OnDisposed()
{
FixValues();
Core.OnAfterLoad -= OnAfterLoad;
Core.OnAfterNew -= OnAfterLoad;
Core.OnBeforeLoad -= Core_OnBeforeLoad;
}
protected override void UpdateInternal()
{
float width = Manager.NativeManager.GetContentRegionAvail().X;
Manager.NativeManager.PushItemWidth(width - Manager.NativeManager.GetTextLineHeight() * 5.5f);
var nextParam = Component.ObjectCollection.Select("", "", Core.ProcedualModel.ProcedualModels.Selected, false, Core.ProcedualModel.ProcedualModels);
if (Core.ProcedualModel.ProcedualModels.Selected != nextParam)
{
Core.ProcedualModel.ProcedualModels.Selected = nextParam;
}
Manager.NativeManager.PopItemWidth();
Manager.NativeManager.SameLine();
if (Manager.NativeManager.Button(Resources.GetString("DynamicAdd") + "###DynamicAdd"))
{
Core.ProcedualModel.ProcedualModels.New();
}
Manager.NativeManager.SameLine();
if (Manager.NativeManager.Button(Resources.GetString("DynamicDelete") + "###DynamicDelete"))
{
Core.ProcedualModel.ProcedualModels.Delete(Core.ProcedualModel.ProcedualModels.Selected);
}
paramerterList.Update();
}
private void Read()
{
paramerterList.SetValue(Core.ProcedualModel.ProcedualModels);
}
private void OnAfterLoad(object sender, EventArgs e)
{
Read();
}
private void Core_OnBeforeLoad(object sender, EventArgs e)
{
paramerterList.SetValue(null);
}
}
}
| using System;
using Effekseer.Data;
namespace Effekseer.GUI.Dock
{
class ProcedualModel : DockPanel
{
readonly Component.ParameterList paramerterList = null;
public ProcedualModel()
{
Label = Icons.PanelDynamicParams + Resources.GetString("ProcedualModel_Name") + "###ProcedualModel";
paramerterList = new Component.ParameterList();
Core.OnAfterLoad += OnAfterLoad;
Core.OnAfterNew += OnAfterLoad;
Read();
TabToolTip = Resources.GetString("ProcedualModel_Name");
}
public void FixValues()
{
paramerterList.FixValues();
}
public override void OnDisposed()
{
FixValues();
Core.OnAfterLoad -= OnAfterLoad;
Core.OnAfterNew -= OnAfterLoad;
}
protected override void UpdateInternal()
{
float width = Manager.NativeManager.GetContentRegionAvail().X;
Manager.NativeManager.PushItemWidth(width - Manager.NativeManager.GetTextLineHeight() * 5.5f);
var nextParam = Component.ObjectCollection.Select("", "", Core.ProcedualModel.ProcedualModels.Selected, false, Core.ProcedualModel.ProcedualModels);
if (Core.ProcedualModel.ProcedualModels.Selected != nextParam)
{
Core.ProcedualModel.ProcedualModels.Selected = nextParam;
}
Manager.NativeManager.PopItemWidth();
Manager.NativeManager.SameLine();
if (Manager.NativeManager.Button(Resources.GetString("DynamicAdd") + "###DynamicAdd"))
{
Core.ProcedualModel.ProcedualModels.New();
}
Manager.NativeManager.SameLine();
if (Manager.NativeManager.Button(Resources.GetString("DynamicDelete") + "###DynamicDelete"))
{
Core.ProcedualModel.ProcedualModels.Delete(Core.ProcedualModel.ProcedualModels.Selected);
}
paramerterList.Update();
}
private void Read()
{
paramerterList.SetValue(Core.ProcedualModel.ProcedualModels);
}
private void OnAfterLoad(object sender, EventArgs e)
{
Read();
}
}
}
| mit | C# |
a6efcc866fd11c0861c11fbbc87bfbf21fb80929 | Remove old XNAControls code from initialization. Crash & burn if old XNAControls are used. | ethanmoffat/EndlessClient | EndlessClient/XNAControlsDependencyContainer.cs | EndlessClient/XNAControlsDependencyContainer.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 EndlessClient.GameExecution;
using EOLib.DependencyInjection;
using Microsoft.Practices.Unity;
using Microsoft.Xna.Framework;
namespace EndlessClient
{
public class XNAControlsDependencyContainer : IInitializableContainer
{
public void RegisterDependencies(IUnityContainer container)
{
}
public void InitializeDependencies(IUnityContainer container)
{
var game = (Game)container.Resolve<IEndlessGame>();
XNAControls.GameRepository.SetGame(game);
}
}
}
| // 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 EndlessClient.GameExecution;
using EOLib.DependencyInjection;
using Microsoft.Practices.Unity;
using Microsoft.Xna.Framework;
namespace EndlessClient
{
public class XNAControlsDependencyContainer : IInitializableContainer
{
public void RegisterDependencies(IUnityContainer container)
{
}
public void InitializeDependencies(IUnityContainer container)
{
var game = (Game)container.Resolve<IEndlessGame>();
XNAControls.GameRepository.SetGame(game);
//todo: remove this once converted to new XNAControls code
XNAControls.Old.XNAControls.Initialize(game);
XNAControls.Old.XNAControls.IgnoreEnterForDialogs = true;
XNAControls.Old.XNAControls.IgnoreEscForDialogs = true;
}
}
}
| mit | C# |
cedf61878d037a84cd8582b3b2d7ea80a42e646c | fix integraion tests execution folder | Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek | Engine.Tests/TestDrivers/CouchbaseTestDriver.cs | Engine.Tests/TestDrivers/CouchbaseTestDriver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Engine.DataTypes;
using Engine.Drivers.Context;
using Engine.Drivers.Rules;
using Couchbase;
using Tweek.Drivers.CouchbaseDriver;
using Engine.Drivers.Rules.Git;
using System.IO;
using Couchbase.Core;
namespace Engine.Tests.TestDrivers
{
class CouchbaseTestDriver : ITestDriver
{
readonly Cluster _cluster;
readonly CouchBaseDriver _driver;
public IContextDriver Context => _driver;
public Func<Task> cleanup = async ()=> {};
public CouchbaseTestDriver(Cluster cluster, string bucket)
{
_cluster = cluster;
_driver = new CouchBaseDriver(cluster, bucket);
}
async Task InsertRuleData(GitDriver driver, Dictionary<string, RuleDefinition> rules)
{
await
Task.WhenAll(
rules.Select(
x => driver.CommitRuleset(x.Key, x.Value, "tweekintegrationtests", "tweek@soluto.com", DateTimeOffset.UtcNow)));
}
async Task InsertContextRows(Dictionary<Identity, Dictionary<string, string>> contexts)
{
cleanup = () => Task.WhenAll(contexts.Select(x => x.Key).Select(_driver.RemoveIdentityContext));
await Task.WhenAll(
contexts.Map(x => _driver.AppendContext(x.Key, x.Value)
));
}
async Task Flush()
{
await cleanup();
_driver.Dispose();
}
public TestScope SetTestEnviornment(Dictionary<Identity, Dictionary<string, string>> contexts, string[] keys, Dictionary<string, RuleDefinition> rules)
{
var gitDriver = new GitDriver(Path.Combine(Path.GetTempPath(), "tweek-rules-tests" + Guid.NewGuid()));
return new TestScope(rules: gitDriver, context: Context,
init: () => Task.WhenAll(InsertContextRows(contexts), InsertRuleData(gitDriver, rules)),
dispose: Flush);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Engine.DataTypes;
using Engine.Drivers.Context;
using Engine.Drivers.Rules;
using Couchbase;
using Tweek.Drivers.CouchbaseDriver;
using Engine.Drivers.Rules.Git;
using System.IO;
using Couchbase.Core;
namespace Engine.Tests.TestDrivers
{
class CouchbaseTestDriver : ITestDriver
{
readonly Cluster _cluster;
readonly CouchBaseDriver _driver;
public IContextDriver Context => _driver;
public Func<Task> cleanup = async ()=> {};
public CouchbaseTestDriver(Cluster cluster, string bucket)
{
_cluster = cluster;
_driver = new CouchBaseDriver(cluster, bucket);
}
async Task InsertRuleData(GitDriver driver, Dictionary<string, RuleDefinition> rules)
{
await
Task.WhenAll(
rules.Select(
x => driver.CommitRuleset(x.Key, x.Value, "tweekintegrationtests", "tweek@soluto.com", DateTimeOffset.UtcNow)));
}
async Task InsertContextRows(Dictionary<Identity, Dictionary<string, string>> contexts)
{
cleanup = () => Task.WhenAll(contexts.Select(x => x.Key).Select(_driver.RemoveIdentityContext));
await Task.WhenAll(
contexts.Map(x => _driver.AppendContext(x.Key, x.Value)
));
}
async Task Flush()
{
await cleanup();
_driver.Dispose();
}
public TestScope SetTestEnviornment(Dictionary<Identity, Dictionary<string, string>> contexts, string[] keys, Dictionary<string, RuleDefinition> rules)
{
var gitDriver = new GitDriver(Path.Combine(Environment.CurrentDirectory, "tweek-rules-tests" + Guid.NewGuid()));
return new TestScope(rules: gitDriver, context: Context,
init: () => Task.WhenAll(InsertContextRows(contexts), InsertRuleData(gitDriver, rules)),
dispose: Flush);
}
}
}
| mit | C# |
eeb8850a71058148c695a052acbe55ca55bf8a21 | Fix AggregationResult error | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | InfinniPlatform.Core/Index/AggregationResult.cs | InfinniPlatform.Core/Index/AggregationResult.cs | using System.Collections.Generic;
using InfinniPlatform.Sdk.Dynamic;
using InfinniPlatform.Sdk.Registers;
namespace InfinniPlatform.Core.Index
{
/// <summary>
/// Результат выполнения агрегации по одному измерению
/// </summary>
public class AggregationResult
{
private readonly List<AggregationResult> _backets;
public AggregationResult()
{
_backets = new List<AggregationResult>();
}
/// <summary>
/// Gets an aggregation name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets measure type of aggregation
/// </summary>
public AggregationType[] MeasureTypes { get; set; }
/// <summary>
/// Measured aggregation values
/// </summary>
public double[] Values { get; set; }
/// <summary>
/// Count of documents in the aggregation
/// </summary>
public long? DocCount { get; set; }
/// <summary>
/// Gets the inner aggregation result
/// </summary>
public List<AggregationResult> Buckets
{
get { return _backets; }
}
//TODO Избавиться в процессе рефакторинга регистров.
/// <remarks>
/// Раньше появлялось только в динамическом контексте. Поведение до конца не изучено.
/// </remarks>
public DynamicWrapper DenormalizationResult { get; set; }
}
} | using System.Collections.Generic;
using InfinniPlatform.Sdk.Registers;
namespace InfinniPlatform.Core.Index
{
/// <summary>
/// Результат выполнения агрегации по одному измерению
/// </summary>
public class AggregationResult
{
private readonly List<AggregationResult> _backets;
public AggregationResult()
{
_backets = new List<AggregationResult>();
}
/// <summary>
/// Gets an aggregation name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets measure type of aggregation
/// </summary>
public AggregationType[] MeasureTypes { get; set; }
/// <summary>
/// Measured aggregation values
/// </summary>
public double[] Values { get; set; }
/// <summary>
/// Count of documents in the aggregation
/// </summary>
public long? DocCount { get; set; }
/// <summary>
/// Gets the inner aggregation result
/// </summary>
public List<AggregationResult> Buckets
{
get { return _backets; }
}
//TODO Избавиться в процессе рефакторинга регистров.
/// <remarks>
/// Раньше появлялось только в динамическом контексте. Поведение до конца не изучено.
/// </remarks>
public List<AggregationResult> DenormalizationResult { get; set; }
}
} | agpl-3.0 | C# |
9eb203a63c58151011b838df5a17af0a46c5e37c | Add console output | pvdstel/cgppm | src/cgppm/Launcher.cs | src/cgppm/Launcher.cs | using cgppm.Netpbm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace cgppm
{
public class Launcher
{
private static List<Image> _convertedImages = new List<Image>();
[STAThread]
public static void Main(string[] args)
{
Console.WriteLine("Starting...");
Console.Write("Parsing arguments... ");
List<string> switches = args.Where(s => s[0] == '-' || s[0] == '/').Select(s => s.Substring(1)).ToList();
List<string> files = args.Where(s => File.Exists(s)).ToList();
Console.WriteLine("done.");
Console.Write("Parsing Netpbm files... ");
Parser parser = new Parser();
List<RawImage> rawImages = files.Select(f => parser.Read(f)).ToList();
Console.WriteLine("done.");
if (switches.Contains("8") || switches.Contains("8bit") || switches.Contains("8-bit"))
{
Console.Write("Generating 8-bit images... ");
_convertedImages.AddRange(Convert8Bit(rawImages));
Console.WriteLine("done.");
}
if (switches.Contains("ui") || switches.Contains("show") || switches.Contains("showui") || switches.Contains("show-ui"))
{
Console.WriteLine("Starting UI...");
Console.Write("Waiting for all UI windows to close...");
UI.App.Main();
Console.WriteLine("UI closed.");
}
}
public static List<Image> ConvertedImages
{
get
{
return _convertedImages;
}
}
private static List<Image> Convert8Bit(List<RawImage> rawImages)
{
List<Image> images = new List<Image>();
ImageConverter ic = new ImageConverter();
foreach (RawImage image in rawImages)
{
images.Add(new Image(ic.ConvertNetpbmTo8Bit(image), "8 bit image"));
}
return images;
}
}
}
| using cgppm.Netpbm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace cgppm
{
public class Launcher
{
private static List<Image> _convertedImages = new List<Image>();
[STAThread]
public static void Main(string[] args)
{
List<string> switches = args.Where(s => s[0] == '-' || s[0] == '/').Select(s => s.Substring(1)).ToList();
List<string> files = args.Where(s => File.Exists(s)).ToList();
Parser parser = new Parser();
List<RawImage> rawImages = files.Select(f => parser.Read(f)).ToList();
if (switches.Contains("8") || switches.Contains("8bit") || switches.Contains("8-bit"))
{
_convertedImages.AddRange(Convert8Bit(rawImages));
}
if (switches.Contains("ui") || switches.Contains("show") || switches.Contains("showui") || switches.Contains("show-ui"))
{
UI.App.Main();
}
}
public static List<Image> ConvertedImages
{
get
{
return _convertedImages;
}
}
private static List<Image> Convert8Bit(List<RawImage> rawImages)
{
List<Image> images = new List<Image>();
ImageConverter ic = new ImageConverter();
foreach (RawImage image in rawImages)
{
images.Add(new Image(ic.ConvertNetpbmTo8Bit(image), "8 bit image"));
}
return images;
}
}
}
| mpl-2.0 | C# |
f62d06507567001b2464939f928be748f0399493 | hide text on start. | SIE-VR/demo1,SIE-VR/demo1,SIE-VR/demo1 | Assets/Scripts/SafeZoneDetect.cs | Assets/Scripts/SafeZoneDetect.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SafeZoneDetect : MonoBehaviour {
public GameObject GUI_text;
private Text text;
private bool LeftHand_inside, RightHand_inside;
// Use this for initialization
void Start () {
text = GUI_text.GetComponent<Text> ();
text.enabled = false;
LeftHand_inside = true;
RightHand_inside = true;
}
void OnTriggerEnter(Collider col)
{
if (col.name.Equals ("LeftHand"))
LeftHand_inside = false;
else if (col.name.Equals ("RightHand"))
RightHand_inside = false;
if(!LeftHand_inside || !RightHand_inside)
text.enabled = true;
}
void OnTriggerStay(Collider col)
{
}
void OnTriggerExit(Collider col)
{
if (col.name.Equals ("LeftHand"))
LeftHand_inside = true;
else if (col.name.Equals ("RightHand"))
RightHand_inside = true;
if(LeftHand_inside && RightHand_inside)
text.enabled = false;
}
// Update is called once per frame
void Update () {
//Debug.Log ("working");
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SafeZoneDetect : MonoBehaviour {
public GameObject GUI_text;
private Text text;
private bool LeftHand_inside, RightHand_inside;
// Use this for initialization
void Start () {
text = GUI_text.GetComponent<Text> ();
LeftHand_inside = true;
RightHand_inside = true;
}
void OnTriggerEnter(Collider col)
{
if (col.name.Equals ("LeftHand"))
LeftHand_inside = false;
else if (col.name.Equals ("RightHand"))
RightHand_inside = false;
if(!LeftHand_inside || !RightHand_inside)
text.enabled = true;
}
void OnTriggerStay(Collider col)
{
}
void OnTriggerExit(Collider col)
{
if (col.name.Equals ("LeftHand"))
LeftHand_inside = true;
else if (col.name.Equals ("RightHand"))
RightHand_inside = true;
if(LeftHand_inside && RightHand_inside)
text.enabled = false;
}
// Update is called once per frame
void Update () {
//Debug.Log ("working");
}
}
| mit | C# |
34b5234285f7986abf0cb76f488bf617016330fc | Fix warnings. | JohanLarsson/Gu.Persist,JohanLarsson/Gu.Settings | Gu.Persist.Demo/RepositoryVm.cs | Gu.Persist.Demo/RepositoryVm.cs | namespace Gu.Persist.Demo
{
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Gu.Persist.Core;
using Gu.Persist.Git;
using Gu.Persist.NewtonsoftJson;
using RepositorySettings = Gu.Persist.NewtonsoftJson.RepositorySettings;
public sealed class RepositoryVm : INotifyPropertyChanged
{
private RepositoryVm()
{
this.Repository = CreateJsonRepositoryWithGitBackuper();
this.ManualSaveSetting = this.Repository.ReadOrCreate(() => (ManualSaveSetting)Activator.CreateInstance(typeof(ManualSaveSetting), nonPublic: true)!);
this.AutoSaveSetting = this.Repository.ReadOrCreate(() => (AutoSaveSetting)Activator.CreateInstance(typeof(AutoSaveSetting), nonPublic: true)!);
this.AutoSaveSetting.PropertyChanged += (o, e) => this.Save((AutoSaveSetting)o);
}
public event PropertyChangedEventHandler? PropertyChanged;
public static RepositoryVm Instance { get; } = new RepositoryVm();
public IRepository Repository { get; }
public ManualSaveSetting ManualSaveSetting { get; }
public AutoSaveSetting AutoSaveSetting { get; }
public ObservableCollection<string> Log { get; } = new ObservableCollection<string>();
internal void Save<T>(T item)
{
this.Repository?.Save(item);
this.Log.Add($"Saved: {typeof(T).Name}");
}
private static SingletonRepository CreateJsonRepositoryWithGitBackuper()
{
var jsonSerializerSettings = RepositorySettings.CreateDefaultJsonSettings();
var settings = new RepositorySettings(
directory: Directories.Default.FullName,
jsonSerializerSettings: jsonSerializerSettings,
isTrackingDirty: false,
backupSettings: null);
var gitBackuper = new GitBackuper(settings.Directory);
return new SingletonRepository(settings, gitBackuper);
}
}
}
| namespace Gu.Persist.Demo
{
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Gu.Persist.Core;
using Gu.Persist.Git;
using Gu.Persist.NewtonsoftJson;
using RepositorySettings = Gu.Persist.NewtonsoftJson.RepositorySettings;
public sealed class RepositoryVm : INotifyPropertyChanged
{
private RepositoryVm()
{
this.Repository = CreateJsonRepositoryWithGitBackuper();
this.ManualSaveSetting = this.Repository.ReadOrCreate(() => (ManualSaveSetting)Activator.CreateInstance(typeof(ManualSaveSetting), nonPublic: true)!);
this.AutoSaveSetting = this.Repository.ReadOrCreate(() => (AutoSaveSetting)Activator.CreateInstance(typeof(AutoSaveSetting), nonPublic: true)!);
this.AutoSaveSetting.PropertyChanged += (o, e) => this.Save((AutoSaveSetting)o);
}
public event PropertyChangedEventHandler? PropertyChanged;
public static RepositoryVm Instance { get; } = new RepositoryVm();
public IRepository Repository { get; }
public ManualSaveSetting ManualSaveSetting { get; }
public AutoSaveSetting AutoSaveSetting { get; }
public ObservableCollection<string> Log { get; } = new ObservableCollection<string>();
internal void Save<T>(T item)
{
this.Repository?.Save(item);
this.Log.Add($"Saved: {typeof(T).Name}");
}
private static SingletonRepository CreateJsonRepositoryWithGitBackuper()
{
var jsonSerializerSettings = RepositorySettings.CreateDefaultJsonSettings();
var settings = new RepositorySettings(
directory: Directories.Default.FullName,
jsonSerializerSettings: jsonSerializerSettings,
isTrackingDirty: false,
backupSettings: null);
var gitBackuper = new GitBackuper(settings.Directory);
return new SingletonRepository(settings, gitBackuper);
}
private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| mit | C# |
5de7d91681fd624ca16ab0173e3bb3a517cd6003 | fix copy and paste boo-boo | khellang/octokit.net,TattsGroup/octokit.net,SamTheDev/octokit.net,dlsteuer/octokit.net,mminns/octokit.net,fake-organization/octokit.net,dampir/octokit.net,cH40z-Lord/octokit.net,M-Zuber/octokit.net,geek0r/octokit.net,shiftkey-tester/octokit.net,khellang/octokit.net,M-Zuber/octokit.net,editor-tools/octokit.net,shana/octokit.net,shiftkey/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,magoswiat/octokit.net,SmithAndr/octokit.net,hitesh97/octokit.net,ChrisMissal/octokit.net,yonglehou/octokit.net,rlugojr/octokit.net,eriawan/octokit.net,takumikub/octokit.net,hahmed/octokit.net,shana/octokit.net,naveensrinivasan/octokit.net,octokit-net-test-org/octokit.net,gabrielweyer/octokit.net,kolbasov/octokit.net,hahmed/octokit.net,yonglehou/octokit.net,ivandrofly/octokit.net,darrelmiller/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,gabrielweyer/octokit.net,michaKFromParis/octokit.net,SamTheDev/octokit.net,rlugojr/octokit.net,octokit-net-test-org/octokit.net,alfhenrik/octokit.net,octokit/octokit.net,mminns/octokit.net,editor-tools/octokit.net,daukantas/octokit.net,Red-Folder/octokit.net,ivandrofly/octokit.net,chunkychode/octokit.net,shiftkey-tester/octokit.net,bslliw/octokit.net,thedillonb/octokit.net,nsrnnnnn/octokit.net,TattsGroup/octokit.net,nsnnnnrn/octokit.net,kdolan/octokit.net,devkhan/octokit.net,gdziadkiewicz/octokit.net,thedillonb/octokit.net,alfhenrik/octokit.net,octokit/octokit.net,gdziadkiewicz/octokit.net,fffej/octokit.net,Sarmad93/octokit.net,adamralph/octokit.net,eriawan/octokit.net,shiftkey/octokit.net,Sarmad93/octokit.net,devkhan/octokit.net,dampir/octokit.net,SLdragon1989/octokit.net,brramos/octokit.net,forki/octokit.net,SmithAndr/octokit.net,octokit-net-test/octokit.net,chunkychode/octokit.net | Octokit/IMiscellaneousClient.cs | Octokit/IMiscellaneousClient.cs | using System;
#if NET_45
using System.Collections.Generic;
#endif
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// A client for GitHub's miscellaneous APIs.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/misc/">miscellaneous API documentation</a> for more details.
/// </remarks>
public interface IMiscellaneousClient
{
/// <summary>
/// Gets all the emojis available to use on GitHub.
/// </summary>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>An <see cref="IReadOnlyDictionary{TKey,TValue}"/> of emoji and their URI.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
Task<IReadOnlyDictionary<string, Uri>> GetEmojis();
/// <summary>
/// Gets the rendered Markdown for the specified plain-text Markdown document.
/// </summary>
/// <param name="markdown">A plain-text Markdown document.</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>The rendered Markdown.</returns>
Task<string> RenderRawMarkdown(string markdown);
}
}
| using System;
#if NET_45
using System.Collections.ObjectModel;
#endif
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// A client for GitHub's miscellaneous APIs.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/misc/">miscellaneous API documentation</a> for more details.
/// </remarks>
public interface IMiscellaneousClient
{
/// <summary>
/// Gets all the emojis available to use on GitHub.
/// </summary>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>An <see cref="IReadOnlyDictionary{TKey,TValue}"/> of emoji and their URI.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
Task<IReadOnlyDictionary<string, Uri>> GetEmojis();
/// <summary>
/// Gets the rendered Markdown for the specified plain-text Markdown document.
/// </summary>
/// <param name="markdown">A plain-text Markdown document.</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>The rendered Markdown.</returns>
Task<string> RenderRawMarkdown(string markdown);
}
}
| mit | C# |
b2df0a0d29e94d1decd5c6be9cce94585ff1497e | Set preUpdate to null with the rest of the hooks. | Nopezal/Prism,Nopezal/Prism | Prism/Mods/Hooks/ModDefHooks.cs | Prism/Mods/Hooks/ModDefHooks.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Prism.API;
namespace Prism.Mods.Hooks
{
class ModDefHooks : IHookManager
{
IEnumerable<Action>
onAllModsLoaded,
onUnload ,
preUpdate ,
postUpdate ;
public void Create()
{
onAllModsLoaded = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnAllModsLoaded");
onUnload = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnUnload" );
preUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PreUpdate" );
postUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PostUpdate" );
}
public void Clear ()
{
onAllModsLoaded = null;
onUnload = null;
preUpdate = null;
postUpdate = null;
}
public void OnAllModsLoaded()
{
HookManager.Call(onAllModsLoaded);
}
public void OnUnload ()
{
HookManager.Call(onUnload);
}
public void PreUpdate ()
{
HookManager.Call(preUpdate);
}
public void PostUpdate ()
{
HookManager.Call(postUpdate);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Prism.API;
namespace Prism.Mods.Hooks
{
class ModDefHooks : IHookManager
{
IEnumerable<Action>
onAllModsLoaded,
onUnload ,
preUpdate ,
postUpdate ;
public void Create()
{
onAllModsLoaded = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnAllModsLoaded");
onUnload = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "OnUnload" );
preUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PreUpdate" );
postUpdate = HookManager.CreateHooks<ModDef, Action>(ModData.mods.Values, "PostUpdate" );
}
public void Clear ()
{
onAllModsLoaded = null;
onUnload = null;
postUpdate = null;
}
public void OnAllModsLoaded()
{
HookManager.Call(onAllModsLoaded);
}
public void OnUnload ()
{
HookManager.Call(onUnload);
}
public void PreUpdate ()
{
HookManager.Call(preUpdate);
}
public void PostUpdate ()
{
HookManager.Call(postUpdate);
}
}
}
| artistic-2.0 | C# |
136c9153fab9aa82c2ac4df915c5119d88cee0d0 | add tests for jsonView | barld/project5_6,barld/project5_6,barld/project5_6 | MVCTests/View/JsonDataViewTests.cs | MVCTests/View/JsonDataViewTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using MVC.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVC.View.Tests
{
[TestClass()]
public class JsonDataViewTests
{
[TestMethod()]
public void JsonDataViewTestStatusCode()
{
var view = new JsonDataView(new { });
Assert.AreEqual(view.StatusCode, 200);
}
[TestMethod()]
public void JsonDataViewTestContent()
{
var view = new JsonDataView(new { test = "test" });
Assert.IsTrue(!String.IsNullOrEmpty(view.Content));
}
[TestMethod()]
public void JsonDataViewTestContentType()
{
var view = new JsonDataView(new { test = "test" });
Assert.IsTrue(view.ContentType.Contains("application/json"));
}
}
} | using Microsoft.VisualStudio.TestTools.UnitTesting;
using MVC.View;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVC.View.Tests
{
[TestClass()]
public class JsonDataViewTests
{
[TestMethod()]
public void JsonDataViewTestStatusCode()
{
var view = new JsonDataView(new { });
Assert.AreEqual(view.StatusCode, 200);
}
}
} | mit | C# |
3da596eedffd3d891b3a423b4e53027729cc1bfb | Fix PublishedSnapshotAccessor to not throw but return null | tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,tompipe/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,madsoulswe/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,NikRimington/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,tompipe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,lars-erik/Umbraco-CMS,lars-erik/Umbraco-CMS,WebCentrum/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,lars-erik/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,WebCentrum/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,WebCentrum/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tompipe/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS | src/Umbraco.Web/PublishedCache/UmbracoContextPublishedSnapshotAccessor.cs | src/Umbraco.Web/PublishedCache/UmbracoContextPublishedSnapshotAccessor.cs | using System;
namespace Umbraco.Web.PublishedCache
{
public class UmbracoContextPublishedSnapshotAccessor : IPublishedSnapshotAccessor
{
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
public UmbracoContextPublishedSnapshotAccessor(IUmbracoContextAccessor umbracoContextAccessor)
{
_umbracoContextAccessor = umbracoContextAccessor;
}
public IPublishedSnapshot PublishedSnapshot
{
get
{
var umbracoContext = _umbracoContextAccessor.UmbracoContext;
return umbracoContext?.PublishedSnapshot;
}
set => throw new NotSupportedException(); // not ok to set
}
}
}
| using System;
namespace Umbraco.Web.PublishedCache
{
public class UmbracoContextPublishedSnapshotAccessor : IPublishedSnapshotAccessor
{
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
public UmbracoContextPublishedSnapshotAccessor(IUmbracoContextAccessor umbracoContextAccessor)
{
_umbracoContextAccessor = umbracoContextAccessor;
}
public IPublishedSnapshot PublishedSnapshot
{
get
{
var umbracoContext = _umbracoContextAccessor.UmbracoContext;
if (umbracoContext == null) throw new Exception("The IUmbracoContextAccessor could not provide an UmbracoContext.");
return umbracoContext.PublishedSnapshot;
}
set
{
throw new NotSupportedException(); // not ok to set
}
}
}
}
| mit | C# |
43555b0f7a8caa56b0e86678927ff83be8db7d45 | delete commented code. | ytabuchi/NetStandard | NetStandardLibrary/TranslateLib.cs | NetStandardLibrary/TranslateLib.cs | /* This class get a result of Translator API
* http://docs.microsofttranslator.com/text-translate.html#!/default/get_Translate
*/
using System;
using System.Net.Http;
using System.Xml.Linq;
using System.Threading.Tasks;
namespace NetStandardLibrary
{
public class TranslateLib
{
const string url = "https://api.microsofttranslator.com/v2/http.svc/Translate";
public static async Task<string> TranslateTextAsync(string rowText)
{
var token = await AuthenticationToken.GetBearerTokenAsync(Secrets.TranslatorApiKey);
using (var client = new HttpClient())
{
var data = $"{url}?appid={token}&text={rowText}&from=ja&to=en&category=generalnn";
var stream = await client.GetStreamAsync(data);
var doc = XElement.Load(stream);
return doc.Value;
}
}
}
}
| /* This class get a result of Translator API
* http://docs.microsofttranslator.com/text-translate.html#!/default/get_Translate
*/
using System;
using System.Net.Http;
using System.Xml.Linq;
using System.Threading.Tasks;
namespace NetStandardLibrary
{
public class TranslateLib
{
const string url = "https://api.microsofttranslator.com/v2/http.svc/Translate";
public static async Task<string> TranslateTextAsync(string rowText)
{
var token = await AuthenticationToken.GetBearerTokenAsync(Secrets.TranslatorApiKey);
using (var client = new HttpClient())
{
var data = $"{url}?appid={token}&text={rowText}&from=ja&to=en&category=generalnn";
var stream = await client.GetStreamAsync(data);
var doc = XElement.Load(stream);
return doc.Value;
}
//return null;
}
}
}
| mit | C# |
437b7dac2fc026813f8c3c1e63f346ce14de4f6d | Revert "cosmetic" | stormsw/ladm.rrr | Example1/Program.cs | Example1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ladm.DataModel;
namespace Example1
{
class Program
{
static void Main(string[] args)
{
using (var ctx = new Ladm.DataModel.LadmDbContext())
{
Transaction transaction = new Transaction() { TransactionNumber = "TRN-0001", TransactionType = new TransactionMetaData() { Code="TRN" } };
ctx.Transactions.Add(transaction);
ctx.SaveChanges();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ladm.DataModel;
namespace Example1
{
class Program
{
static void Main(string[] args)
{
using (var context = new Ladm.DataModel.LadmDbContext())
{
Transaction transaction = new Transaction() { TransactionNumber = "TRN-0001", TransactionType = new TransactionMetaData() { Code="TRN" } };
context.Transactions.Add(transaction);
context.SaveChanges();
}
}
}
}
| mit | C# |
5d2d0b815f981a67b1b840dd4be0980792f0e6eb | Revert "prototype: GfxObjCache + WeakReference (#1692)" (#2216) | LtRipley36706/ACE,LtRipley36706/ACE,LtRipley36706/ACE,ACEmulator/ACE,ACEmulator/ACE,ACEmulator/ACE | Source/ACE.Server/Physics/Entity/GfxObjCache.cs | Source/ACE.Server/Physics/Entity/GfxObjCache.cs | // Uncomment this if you want to use weak reference cache. It could save 10's of MB and might be useful on a micro-server
//#define USE_WEAK_REFERENCE_CACHE
using System;
using System.Collections.Concurrent;
using ACE.Server.Physics.Collision;
using ACE.Server.Physics.Common;
namespace ACE.Server.Physics.Entity
{
public static class GfxObjCache
{
#if !USE_WEAK_REFERENCE_CACHE
public static readonly ConcurrentDictionary<uint, GfxObj> GfxObjs = new ConcurrentDictionary<uint, GfxObj>();
#else
public static readonly ConcurrentDictionary<uint, WeakReference<GfxObj>> GfxObjs = new ConcurrentDictionary<uint, WeakReference<GfxObj>>();
#endif
public static int Requests;
public static int Hits;
public static int Count => GfxObjs.Count;
public static void Clear()
{
GfxObjs.Clear();
}
public static GfxObj Get(uint gfxObjID)
{
Requests++;
//if (Requests % 100 == 0)
//Console.WriteLine($"GfxObjCache: Requests={Requests}, Hits={Hits}");
if (GfxObjs.TryGetValue(gfxObjID, out var result))
{
#if !USE_WEAK_REFERENCE_CACHE
Hits++;
return result;
#else
if (result.TryGetTarget(out var target))
{
Hits++;
return target;
}
#endif
}
var _gfxObj = DBObj.GetGfxObj(gfxObjID);
// not cached, add it
var gfxObj = new GfxObj(_gfxObj);
#if !USE_WEAK_REFERENCE_CACHE
gfxObj = GfxObjs.GetOrAdd(_gfxObj.Id, gfxObj);
#else
GfxObjs[_gfxObj.Id] = new WeakReference<GfxObj>(gfxObj);
#endif
return gfxObj;
}
}
}
| using System;
using System.Collections.Concurrent;
using ACE.Server.Physics.Collision;
using ACE.Server.Physics.Common;
namespace ACE.Server.Physics.Entity
{
public static class GfxObjCache
{
//public static readonly ConcurrentDictionary<uint, GfxObj> GfxObjs = new ConcurrentDictionary<uint, GfxObj>();
public static readonly ConcurrentDictionary<uint, WeakReference<GfxObj>> GfxObjs = new ConcurrentDictionary<uint, WeakReference<GfxObj>>();
public static int Requests;
public static int Hits;
public static int Count => GfxObjs.Count;
public static void Clear()
{
GfxObjs.Clear();
}
public static GfxObj Get(uint gfxObjID)
{
Requests++;
//if (Requests % 100 == 0)
//Console.WriteLine($"GfxObjCache: Requests={Requests}, Hits={Hits}");
if (GfxObjs.TryGetValue(gfxObjID, out var result))
{
if (result.TryGetTarget(out var target))
{
Hits++;
return target;
}
}
var _gfxObj = DBObj.GetGfxObj(gfxObjID);
// not cached, add it
var gfxObj = new GfxObj(_gfxObj);
//gfxObj = GfxObjs.GetOrAdd(_gfxObj.Id, gfxObj);
GfxObjs[_gfxObj.Id] = new WeakReference<GfxObj>(gfxObj);
return gfxObj;
}
}
}
| agpl-3.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.