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 |
|---|---|---|---|---|---|---|---|---|
a610bca37b7690b73f3fcf926935176a4bc8d796
|
Fix dark background on widgets using XWT backend
|
hwthomas/xwt,residuum/xwt,lytico/xwt,hamekoz/xwt,cra0zy/xwt,TheBrainTech/xwt,antmicro/xwt,mono/xwt,akrisiun/xwt
|
Xwt.Gtk/Xwt.GtkBackend/CustomWidgetBackend.cs
|
Xwt.Gtk/Xwt.GtkBackend/CustomWidgetBackend.cs
|
//
// CustomWidgetBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
namespace Xwt.GtkBackend
{
public class CustomWidgetBackend: WidgetBackend, ICustomWidgetBackend
{
public CustomWidgetBackend ()
{
}
public override void Initialize ()
{
var w = new Gtk.EventBox ();
w.VisibleWindow = false;
Widget = w;
Widget.Show ();
}
WidgetBackend childBackend;
protected new Gtk.EventBox Widget {
get { return (Gtk.EventBox)base.Widget; }
set { base.Widget = value; }
}
public override Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
{
if (childBackend == null)
return base.GetPreferredSize (widthConstraint, heightConstraint);
var size = childBackend.Frontend.Surface.GetPreferredSize (widthConstraint, heightConstraint, true);
return size;
}
public void SetContent (IWidgetBackend widget)
{
childBackend = (WidgetBackend)widget;
var newWidget = GetWidgetWithPlacement (widget);
var oldWidget = Widget.Child;
if (oldWidget == null)
Widget.Child = newWidget;
else {
GtkEngine.ReplaceChild (oldWidget, newWidget);
RemoveChildPlacement (oldWidget);
}
}
}
}
|
//
// CustomWidgetBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
namespace Xwt.GtkBackend
{
public class CustomWidgetBackend: WidgetBackend, ICustomWidgetBackend
{
public CustomWidgetBackend ()
{
}
public override void Initialize ()
{
Widget = new Gtk.EventBox ();
Widget.Show ();
}
WidgetBackend childBackend;
protected new Gtk.EventBox Widget {
get { return (Gtk.EventBox)base.Widget; }
set { base.Widget = value; }
}
public override Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
{
if (childBackend == null)
return base.GetPreferredSize (widthConstraint, heightConstraint);
var size = childBackend.Frontend.Surface.GetPreferredSize (widthConstraint, heightConstraint, true);
return size;
}
public void SetContent (IWidgetBackend widget)
{
childBackend = (WidgetBackend)widget;
var newWidget = GetWidgetWithPlacement (widget);
var oldWidget = Widget.Child;
if (oldWidget == null)
Widget.Child = newWidget;
else {
GtkEngine.ReplaceChild (oldWidget, newWidget);
RemoveChildPlacement (oldWidget);
}
}
}
}
|
mit
|
C#
|
2a2af95b7e8998661fc37ef06616b69a9f3a924a
|
Fix VarArray type on create.
|
xamarin/WebSharp,xamarin/WebSharp,xamarin/WebSharp,xamarin/WebSharp,xamarin/WebSharp,xamarin/WebSharp
|
PepperSharp/src/VarArray.cs
|
PepperSharp/src/VarArray.cs
|
using System;
using System.Runtime.InteropServices;
namespace PepperSharp
{
public partial class VarArray : Var
{
public VarArray() : base(PPVarType.Null)
{
ppvar = PPBVarArray.Create();
}
public VarArray(Var var) : base(var)
{
if (!var.IsArray)
ppvar = Var.Empty;
}
/// <summary>
/// Retrieves the length of the ArrayBuffer that is referenced
/// </summary>
public uint Length
{
get
{
if (IsArray)
return PPBVarArray.GetLength(ppvar);
return 0;
}
set
{
if (IsArray)
PPBVarArray.SetLength(ppvar, value);
}
}
public Var this[uint index]
{
get
{
return Get(index);
}
set
{
if (IsArray)
Set(index, value);
}
}
public Var Get(uint index)
{
if (IsArray)
return PPBVarArray.Get(ppvar, index);
return Var.Empty;
}
public bool Set(uint index, Var value)
{
if (IsArray)
return PPBVarArray.Set(ppvar, index, value) == PPBool.True;
return false;
}
public bool Set(uint index, object value)
{
if (IsArray)
return PPBVarArray.Set(ppvar, index, new Var(value)) == PPBool.True;
return false;
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace PepperSharp
{
public partial class VarArray : Var
{
public VarArray() : base(Var.Empty)
{
ppvar = PPBVarDictionary.Create();
}
public VarArray(Var var) : base(var)
{
if (!var.IsArray)
ppvar = Var.Empty;
}
/// <summary>
/// Retrieves the length of the ArrayBuffer that is referenced
/// </summary>
public uint Length
{
get
{
if (IsArray)
return PPBVarArray.GetLength(ppvar);
return 0;
}
set
{
if (IsArray)
PPBVarArray.SetLength(ppvar, value);
}
}
public Var this[uint index]
{
get
{
return Get(index);
}
set
{
if (IsArray)
Set(index, value);
}
}
public Var Get(uint index)
{
if (IsArray)
return PPBVarArray.Get(ppvar, index);
return Var.Empty;
}
public bool Set(uint index, Var value)
{
if (IsArray)
return PPBVarArray.Set(ppvar, index, value) == PPBool.True;
return false;
}
public bool Set(uint index, object value)
{
if (IsArray)
return PPBVarArray.Set(ppvar, index, new Var(value)) == PPBool.True;
return false;
}
}
}
|
mit
|
C#
|
6705cb84a03e88db0c7f59d9abdc80afa1292a6d
|
bump version
|
SimonCropp/NServiceBus.Serilog
|
CommonAssemblyInfo.cs
|
CommonAssemblyInfo.cs
|
using System.Reflection;
[assembly: AssemblyVersion("3.0.2")]
[assembly: AssemblyFileVersion("3.0.2")]
|
using System.Reflection;
[assembly: AssemblyVersion("3.0.1")]
[assembly: AssemblyFileVersion("3.0.1")]
|
mit
|
C#
|
6049ef5ec0e6732f502c78332d46c9516dce245b
|
Update IResources.cs
|
YAFNET/YAFNET,YAFNET/YAFNET,YAFNET/YAFNET,YAFNET/YAFNET
|
yafsrc/YAF.Types/Interfaces/IResources.cs
|
yafsrc/YAF.Types/Interfaces/IResources.cs
|
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Types.Interfaces
{
using System.Web;
/// <summary>
/// The Resources interface.
/// </summary>
public interface IResources
{
/// <summary>
/// Gets the forum user info as JSON string for the hover cards
/// </summary>
/// <param name="context">The context.</param>
void GetUserInfo([NotNull] HttpContext context);
/// <summary>
/// Get all Mentioned Users
/// </summary>
/// <param name="context">
/// The context.
/// </param>
void GetMentionUsers([NotNull] HttpContext context);
/// <summary>
/// Gets the twitter user info as JSON string for the hover cards
/// </summary>
/// <param name="context">The context.</param>
void GetTwitterUserInfo([NotNull] HttpContext context);
/// <summary>
/// The get response local avatar.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
void GetResponseLocalAvatar([NotNull] HttpContext context);
/// <summary>
/// The get response captcha.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
void GetResponseCaptcha([NotNull] HttpContext context);
/// <summary>
/// The get response remote avatar.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
void GetResponseRemoteAvatar([NotNull] HttpContext context);
}
}
|
/* Yet Another Forum.NET
* Copyright (C) 2003-2005 Bjørnar Henden
* Copyright (C) 2006-2013 Jaben Cargman
* Copyright (C) 2014-2020 Ingo Herbote
* https://www.yetanotherforum.net/
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace YAF.Types.Interfaces
{
using System.Web;
/// <summary>
/// The Resources interface.
/// </summary>
public interface IResources
{
/// <summary>
/// Gets the forum user info as JSON string for the hover cards
/// </summary>
/// <param name="context">The context.</param>
void GetUserInfo([NotNull] HttpContext context);
/// <summary>
/// Gets the list of all Custom BB Codes
/// </summary>
/// <param name="context">The context.</param>
void GetCustomBBCodes([NotNull] HttpContext context);
/// <summary>
/// Get all Mentioned Users
/// </summary>
/// <param name="context">
/// The context.
/// </param>
void GetMentionUsers([NotNull] HttpContext context);
/// <summary>
/// Gets the twitter user info as JSON string for the hover cards
/// </summary>
/// <param name="context">The context.</param>
void GetTwitterUserInfo([NotNull] HttpContext context);
/// <summary>
/// The get response local avatar.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
void GetResponseLocalAvatar([NotNull] HttpContext context);
/// <summary>
/// The get response captcha.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
void GetResponseCaptcha([NotNull] HttpContext context);
/// <summary>
/// The get response remote avatar.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
void GetResponseRemoteAvatar([NotNull] HttpContext context);
}
}
|
apache-2.0
|
C#
|
36977f5f944222540ff0a58eb0cecba6c74c3d13
|
Enable PreLoadImages
|
Launchify/Launchify,danisein/Wox,jondaniels/Wox,zlphoenix/Wox,dstiert/Wox,kayone/Wox,Megasware128/Wox,kayone/Wox,kayone/Wox,yozora-hitagi/Saber,danisein/Wox,dstiert/Wox,Launchify/Launchify,dstiert/Wox,JohnTheGr8/Wox,yozora-hitagi/Saber,medoni/Wox,jondaniels/Wox,medoni/Wox,Megasware128/Wox,JohnTheGr8/Wox,zlphoenix/Wox
|
Wox/App.xaml.cs
|
Wox/App.xaml.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using Wox.CommandArgs;
using Wox.Core.Plugin;
using Wox.Helper;
using Wox.Infrastructure;
namespace Wox
{
public partial class App : Application, ISingleInstanceApp
{
private const string Unique = "Wox_Unique_Application_Mutex";
public static MainWindow Window { get; private set; }
[STAThread]
public static void Main()
{
if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
{
var application = new App();
application.InitializeComponent();
application.Run();
SingleInstance<App>.Cleanup();
}
}
protected override void OnStartup(StartupEventArgs e)
{
using (new Timeit("Startup Time"))
{
base.OnStartup(e);
DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle;
ThreadPool.QueueUserWorkItem(o => { ImageLoader.ImageLoader.PreloadImages(); });
Window = new MainWindow();
PluginManager.Init(Window);
CommandArgsFactory.Execute(e.Args.ToList());
}
}
public bool OnActivate(IList<string> args)
{
CommandArgsFactory.Execute(args);
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using Wox.CommandArgs;
using Wox.Core.Plugin;
using Wox.Helper;
using Wox.Infrastructure;
namespace Wox
{
public partial class App : Application, ISingleInstanceApp
{
private const string Unique = "Wox_Unique_Application_Mutex";
public static MainWindow Window { get; private set; }
[STAThread]
public static void Main()
{
if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
{
var application = new App();
application.InitializeComponent();
application.Run();
SingleInstance<App>.Cleanup();
}
}
protected override void OnStartup(StartupEventArgs e)
{
using (new Timeit("Startup Time"))
{
base.OnStartup(e);
DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle;
//ThreadPool.QueueUserWorkItem(o => { ImageLoader.ImageLoader.PreloadImages(); });
Window = new MainWindow();
PluginManager.Init(Window);
CommandArgsFactory.Execute(e.Args.ToList());
}
}
public bool OnActivate(IList<string> args)
{
CommandArgsFactory.Execute(args);
return true;
}
}
}
|
mit
|
C#
|
ca914334eadccfeb4cdfa0137d4fe0d890d8fcd4
|
revert logger colon change
|
livarcocc/cli-1,johnbeisner/cli,harshjain2/cli,Faizan2304/cli,svick/cli,EdwardBlair/cli,ravimeda/cli,blackdwarf/cli,Faizan2304/cli,EdwardBlair/cli,EdwardBlair/cli,ravimeda/cli,harshjain2/cli,ravimeda/cli,livarcocc/cli-1,johnbeisner/cli,svick/cli,blackdwarf/cli,dasMulli/cli,dasMulli/cli,svick/cli,livarcocc/cli-1,dasMulli/cli,Faizan2304/cli,blackdwarf/cli,blackdwarf/cli,johnbeisner/cli,harshjain2/cli
|
build_projects/dotnet-cli-build/DotNetTest.cs
|
build_projects/dotnet-cli-build/DotNetTest.cs
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DotNet.Cli.Build
{
public class DotNetTest : DotNetMSBuildTool
{
protected override string Command
{
get { return "test"; }
}
protected override string Args
{
get { return $"{base.Args} {GetProjectPath()} {GetConfiguration()} {GetLogger()} {GetNoBuild()}"; }
}
public string Configuration { get; set; }
public string Logger { get; set; }
public string ProjectPath { get; set; }
public bool NoBuild { get; set; }
private string GetConfiguration()
{
if (!string.IsNullOrEmpty(Configuration))
{
return $"--configuration {Configuration}";
}
return null;
}
private string GetLogger()
{
if (!string.IsNullOrEmpty(Logger))
{
return $"--logger:{Logger}";
}
return null;
}
private string GetProjectPath()
{
if (!string.IsNullOrEmpty(ProjectPath))
{
return $"{ProjectPath}";
}
return null;
}
private string GetNoBuild()
{
if (NoBuild)
{
return "--no-build";
}
return null;
}
}
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DotNet.Cli.Build
{
public class DotNetTest : DotNetMSBuildTool
{
protected override string Command
{
get { return "test"; }
}
protected override string Args
{
get { return $"{base.Args} {GetProjectPath()} {GetConfiguration()} {GetLogger()} {GetNoBuild()}"; }
}
public string Configuration { get; set; }
public string Logger { get; set; }
public string ProjectPath { get; set; }
public bool NoBuild { get; set; }
private string GetConfiguration()
{
if (!string.IsNullOrEmpty(Configuration))
{
return $"--configuration {Configuration}";
}
return null;
}
private string GetLogger()
{
if (!string.IsNullOrEmpty(Logger))
{
return $"--logger {Logger}";
}
return null;
}
private string GetProjectPath()
{
if (!string.IsNullOrEmpty(ProjectPath))
{
return $"{ProjectPath}";
}
return null;
}
private string GetNoBuild()
{
if (NoBuild)
{
return "--no-build";
}
return null;
}
}
}
|
mit
|
C#
|
d3e170e2dff4c86fc4b1954cf47e76408995576e
|
Add overloads for GlobalDI.GetService
|
Keboo/AutoDI
|
AutoDI/GlobalDI.cs
|
AutoDI/GlobalDI.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutoDI
{
public static class GlobalDI
{
private static readonly List<IServiceProvider> Providers = new List<IServiceProvider>();
public static T GetService<T>(object[] parameters)
{
lock (Providers)
{
if (Providers.Count == 0)
throw new NotInitializedException();
return Providers.Select(provider => provider.GetService<T>(parameters))
.FirstOrDefault(service => service != null);
}
}
public static T GetService<T>()
{
return GetService<T>(new object[] { });
}
public static object GetService(Type serviceType, object[] parameters)
{
lock(Providers)
{
if (Providers.Count == 0)
throw new NotInitializedException();
return Providers.Select(provider => provider.GetService(serviceType, parameters))
.FirstOrDefault(service => service != null);
}
}
public static object GetService(Type serviceType)
{
return GetService(serviceType, new object[] { });
}
public static void Register(IServiceProvider provider)
{
lock (Providers)
{
Providers.Add(provider);
}
}
public static bool Unregister(IServiceProvider provider)
{
lock (Providers)
{
return Providers.Remove(provider);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutoDI
{
public static class GlobalDI
{
private static readonly List<IServiceProvider> Providers = new List<IServiceProvider>();
public static T GetService<T>(object[] parameters)
{
lock (Providers)
{
if (Providers.Count == 0)
throw new NotInitializedException();
return Providers.Select(provider => provider.GetService<T>(parameters))
.FirstOrDefault(service => service != null);
}
}
public static void Register(IServiceProvider provider)
{
lock (Providers)
{
Providers.Add(provider);
}
}
public static bool Unregister(IServiceProvider provider)
{
lock (Providers)
{
return Providers.Remove(provider);
}
}
}
}
|
mit
|
C#
|
2c4a31e8cd3a4f32a04e466823628318899c5fb4
|
add numbers
|
autumn009/TanoCSharpSamples
|
chap36/GetEnumerator/GetEnumerator/Program.cs
|
chap36/GetEnumerator/GetEnumerator/Program.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
class X
{
internal int A { get; set; }
internal int B { get; set; }
}
internal static class MyExtensions
{
internal static IEnumerator GetEnumerator(this X x)
{
yield return x.A;
yield return x.B;
}
}
class Program
{
static void Main()
{
var x = new X();
x.A = 123;
x.B = 456;
foreach (var item in x) Console.WriteLine(item);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
class X
{
internal int A { get; set; }
internal int B { get; set; }
}
internal static class MyExtensions
{
internal static IEnumerator GetEnumerator(this X x)
{
yield return x.A;
yield return x.B;
}
}
class Program
{
static void Main()
{
var x = new X();
foreach (var item in x) Console.WriteLine(item);
}
}
|
mit
|
C#
|
9fc2459b5578c2981045409eead75f859918534d
|
Add CustomAttributeCollection Find/FindAll methods
|
0xd4d/dnlib,ZixiangBoy/dnlib,ilkerhalil/dnlib,modulexcite/dnlib,kiootic/dnlib,yck1509/dnlib,picrap/dnlib,Arthur2e5/dnlib,jorik041/dnlib
|
src/DotNet/CustomAttributeCollection.cs
|
src/DotNet/CustomAttributeCollection.cs
|
using System.Collections.Generic;
namespace dot10.DotNet {
/// <summary>
/// Stores <see cref="CustomAttribute"/>s
/// </summary>
public class CustomAttributeCollection : LazyList<CustomAttribute> {
/// <summary>
/// Default constructor
/// </summary>
public CustomAttributeCollection() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="length">Initial length of the list</param>
/// <param name="context">Context passed to <paramref name="readOriginalValue"/></param>
/// <param name="readOriginalValue">Delegate instance that returns original values</param>
internal CustomAttributeCollection(int length, object context, MFunc<object, uint, CustomAttribute> readOriginalValue)
: base(length, context, readOriginalValue) {
}
/// <summary>
/// Checks whether a custom attribute is present
/// </summary>
/// <param name="fullName">Full name of custom attribute type</param>
/// <returns><c>true</c> if the custom attribute type is present, <c>false</c> otherwise</returns>
public bool IsDefined(string fullName) {
return Find(fullName) != null;
}
/// <summary>
/// Finds a custom attribute
/// </summary>
/// <param name="fullName">Full name of custom attribute type</param>
/// <returns>A <see cref="CustomAttribute"/> or <c>null</c> if it wasn't found</returns>
public CustomAttribute Find(string fullName) {
foreach (var ca in this) {
if (ca != null && ca.TypeFullName == fullName)
return ca;
}
return null;
}
/// <summary>
/// Finds all custom attributes of a certain type
/// </summary>
/// <param name="fullName">Full name of custom attribute type</param>
/// <returns>All <see cref="CustomAttribute"/>s of the requested type</returns>
public IEnumerable<CustomAttribute> FindAll(string fullName) {
foreach (var ca in this) {
if (ca != null && ca.TypeFullName == fullName)
yield return ca;
}
}
/// <summary>
/// Finds a custom attribute
/// </summary>
/// <param name="attrType">Custom attribute type</param>
/// <returns>The first <see cref="CustomAttribute"/> found or <c>null</c> if none found</returns>
public CustomAttribute Find(IType attrType) {
return Find(attrType, 0);
}
/// <summary>
/// Finds a custom attribute
/// </summary>
/// <param name="attrType">Custom attribute type</param>
/// <param name="options">Attribute type comparison flags</param>
/// <returns>The first <see cref="CustomAttribute"/> found or <c>null</c> if none found</returns>
public CustomAttribute Find(IType attrType, SigComparerOptions options) {
var comparer = new SigComparer(options);
foreach (var ca in this) {
if (comparer.Equals(ca.AttributeType, attrType))
return ca;
}
return null;
}
/// <summary>
/// Finds all custom attributes of a certain type
/// </summary>
/// <param name="attrType">Custom attribute type</param>
/// <returns>All <see cref="CustomAttribute"/>s of the requested type</returns>
public IEnumerable<CustomAttribute> FindAll(IType attrType) {
return FindAll(attrType, 0);
}
/// <summary>
/// Finds all custom attributes of a certain type
/// </summary>
/// <param name="attrType">Custom attribute type</param>
/// <param name="options">Attribute type comparison flags</param>
/// <returns>All <see cref="CustomAttribute"/>s of the requested type</returns>
public IEnumerable<CustomAttribute> FindAll(IType attrType, SigComparerOptions options) {
var comparer = new SigComparer(options);
foreach (var ca in this) {
if (comparer.Equals(ca.AttributeType, attrType))
yield return ca;
}
}
}
}
|
using System.Collections.Generic;
namespace dot10.DotNet {
/// <summary>
/// Stores <see cref="CustomAttribute"/>s
/// </summary>
public class CustomAttributeCollection : LazyList<CustomAttribute> {
/// <summary>
/// Default constructor
/// </summary>
public CustomAttributeCollection() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="length">Initial length of the list</param>
/// <param name="context">Context passed to <paramref name="readOriginalValue"/></param>
/// <param name="readOriginalValue">Delegate instance that returns original values</param>
internal CustomAttributeCollection(int length, object context, MFunc<object, uint, CustomAttribute> readOriginalValue)
: base(length, context, readOriginalValue) {
}
/// <summary>
/// Checks whether a custom attribute is present
/// </summary>
/// <param name="fullName">Full name of custom attribute type</param>
/// <returns><c>true</c> if the custom attribute type is present, <c>false</c> otherwise</returns>
public bool IsDefined(string fullName) {
return Find(fullName) != null;
}
/// <summary>
/// Finds a custom attribute
/// </summary>
/// <param name="fullName">Full name of custom attribute type</param>
/// <returns>A <see cref="CustomAttribute"/> or <c>null</c> if it wasn't found</returns>
public CustomAttribute Find(string fullName) {
foreach (var ca in this) {
if (ca != null && ca.TypeFullName == fullName)
return ca;
}
return null;
}
/// <summary>
/// Finds all custom attributes of a certain type
/// </summary>
/// <param name="fullName">Full name of custom attribute type</param>
/// <returns>All <see cref="CustomAttribute"/>s of the requested type</returns>
public IEnumerable<CustomAttribute> FindAll(string fullName) {
foreach (var ca in this) {
if (ca != null && ca.TypeFullName == fullName)
yield return ca;
}
}
}
}
|
mit
|
C#
|
f8b2835c81e7655285718a387642314e6544c7bd
|
Update AdamBertram.cs removing stray backtick
|
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
|
src/Firehose.Web/Authors/AdamBertram.cs
|
src/Firehose.Web/Authors/AdamBertram.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AdamBertram : IAmAMicrosoftMVP
{
public string FirstName => "Adam";
public string LastName => "Bertram";
public string ShortBioOrTagLine => "Automation Engineer, writer, trainer, Microsoft MVP, fiercely independent, laid back guy that loves sharing.";
public string StateOrRegion => "Evansville, IN";
public string EmailAddress => string.Empty;
public string TwitterHandle => "adbertram";
public string GravatarHash => "f21b5adac336b3678098de870efcf994";
public string GitHubHandle => "adbertram";
public GeoPosition Position => new GeoPosition(37.996239,-87.54378);
public Uri WebSite => new Uri("http://www.adamtheautomator.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("http://www.adamtheautomator.com/feed/"); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AdamBertram : IAmAMicrosoftMVP
{
public string FirstName => "Adam";
public string LastName => "Bertram`";
public string ShortBioOrTagLine => "Automation Engineer, writer, trainer, Microsoft MVP, fiercely independent, laid back guy that loves sharing.";
public string StateOrRegion => "Evansville, IN";
public string EmailAddress => string.Empty;
public string TwitterHandle => "adbertram";
public string GravatarHash => "f21b5adac336b3678098de870efcf994";
public string GitHubHandle => "adbertram";
public GeoPosition Position => new GeoPosition(37.996239,-87.54378);
public Uri WebSite => new Uri("http://www.adamtheautomator.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("http://www.adamtheautomator.com/feed/"); }
}
}
}
|
mit
|
C#
|
b2093201b95f09ca5f60ccc914979da331020804
|
Add Computed Expression in ColumnDefinition for Computed Columns
|
SimpleStack/simplestack.orm,SimpleStack/simplestack.orm
|
src/SimpleStack.Orm/ColumnDefinition.cs
|
src/SimpleStack.Orm/ColumnDefinition.cs
|
using System.Data;
namespace SimpleStack.Orm
{
public interface IColumnDefinition
{
/// <summary>
/// Column Name
/// </summary>
string Name { get; }
/// <summary>
/// Is nullable or not
/// </summary>
bool Nullable { get; }
/// <summary>
/// Column Length
/// </summary>
int? Length { get; }
/// <summary>
/// Numeric precision
/// </summary>
int? Precision { get; }
/// <summary>
/// Numeric Scale
/// </summary>
int? Scale { get; }
/// <summary>
/// Columns definition as returned by database server
/// </summary>
string Definition { get; }
/// <summary>
/// Columns type
/// </summary>
DbType DbType { get; }
/// <summary>
/// True if column is part of the primary key
/// </summary>
bool PrimaryKey { get; }
/// <summary>
/// True if there is a unique index on that column
/// </summary>
bool Unique { get; }
/// <summary>
/// Column default value
/// </summary>
string DefaultValue { get; }
/// <summary>
/// Computed Column Expression
/// </summary>
string ComputedExpression { get; }
}
public class ColumnType
{
public int? Length { get; set; }
public int? Precision { get; set; }
public int? Scale { get; set; }
public string Definition { get; set; }
public DbType DbType { get; set; }
}
public class ColumnDefinition : ColumnType, IColumnDefinition
{
/// <inheritdoc />
public string Name { get; set; }
/// <inheritdoc />
public bool Nullable { get; set; }
/// <inheritdoc />
public bool PrimaryKey { get; set; }
public bool Unique { get; set; }
/// <inheritdoc />
public string DefaultValue { get; set; }
/// <inheritdoc />
public string ComputedExpression { get; set; }
}
}
|
using System.Data;
namespace SimpleStack.Orm
{
public interface IColumnDefinition
{
/// <summary>
/// Column Name
/// </summary>
string Name { get; }
/// <summary>
/// Is nullable or not
/// </summary>
bool Nullable { get; }
/// <summary>
/// Column Length
/// </summary>
int? Length { get; }
/// <summary>
/// Numeric precision
/// </summary>
int? Precision { get; }
/// <summary>
/// Numeric Scale
/// </summary>
int? Scale { get; }
/// <summary>
/// Columns definition as returned by database server
/// </summary>
string Definition { get; }
/// <summary>
/// Columns type
/// </summary>
DbType DbType { get; }
/// <summary>
/// True if column is part of the primary key
/// </summary>
bool PrimaryKey { get; }
/// <summary>
/// True if there is a unique index on that column
/// </summary>
bool Unique { get; }
/// <summary>
/// Column default value
/// </summary>
string DefaultValue { get; }
}
public class ColumnType
{
public int? Length { get; set; }
public int? Precision { get; set; }
public int? Scale { get; set; }
public string Definition { get; set; }
public DbType DbType { get; set; }
}
public class ColumnDefinition : ColumnType, IColumnDefinition
{
/// <inheritdoc />
public string Name { get; set; }
/// <inheritdoc />
public bool Nullable { get; set; }
/// <inheritdoc />
public bool PrimaryKey { get; set; }
public bool Unique { get; set; }
/// <inheritdoc />
public string DefaultValue { get; set; }
}
}
|
bsd-3-clause
|
C#
|
b107fdd7c0bba584b72b5601454816546d8f4b4e
|
Improve MissingCtorException message.
|
Gankov/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,antoniusriha/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp
|
glib/ObjectManager.cs
|
glib/ObjectManager.cs
|
// GLib.ObjectManager.cs - GLib ObjectManager class implementation
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright <c> 2001-2002 Mike Kestner
// Copyright <c> 2004-2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
using System.Reflection;
public class ObjectManager {
static BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
public static GLib.Object CreateObject (IntPtr raw)
{
if (raw == IntPtr.Zero)
return null;
Type type = GetTypeOrParent (raw);
if (type == null)
return null;
GLib.Object obj;
try {
obj = Activator.CreateInstance (type, flags, null, new object[] {raw}, null) as GLib.Object;
} catch (MissingMethodException) {
throw new GLib.MissingIntPtrCtorException ("Unable to construct instance of type " + type + " from native object handle. Instance of managed subclass may have been prematurely disposed.");
}
return obj;
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (string native_name, string managed_name, string assembly)
{
RegisterType (native_name, managed_name + "," + assembly);
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (string native_name, string mangled)
{
RegisterType (GType.FromName (native_name), Type.GetType (mangled));
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (GType native_type, System.Type type)
{
GType.Register (native_type, type);
}
static Type GetTypeOrParent (IntPtr obj)
{
IntPtr typeid = GType.ValFromInstancePtr (obj);
if (typeid == GType.Invalid.Val)
return null;
Type result = GType.LookupType (typeid);
while (result == null) {
typeid = g_type_parent (typeid);
if (typeid == IntPtr.Zero)
return null;
result = GType.LookupType (typeid);
}
return result;
}
[DllImport ("libgobject-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr g_type_parent (IntPtr typ);
}
}
|
// GLib.ObjectManager.cs - GLib ObjectManager class implementation
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright <c> 2001-2002 Mike Kestner
// Copyright <c> 2004-2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace GLib {
using System;
using System.Runtime.InteropServices;
using System.Reflection;
public class ObjectManager {
static BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
public static GLib.Object CreateObject (IntPtr raw)
{
if (raw == IntPtr.Zero)
return null;
Type type = GetTypeOrParent (raw);
if (type == null)
return null;
GLib.Object obj;
try {
obj = Activator.CreateInstance (type, flags, null, new object[] {raw}, null) as GLib.Object;
} catch (MissingMethodException) {
throw new GLib.MissingIntPtrCtorException ("GLib.Object subclass " + type + " must provide a protected or public IntPtr ctor to support wrapping of native object handles.");
}
return obj;
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (string native_name, string managed_name, string assembly)
{
RegisterType (native_name, managed_name + "," + assembly);
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (string native_name, string mangled)
{
RegisterType (GType.FromName (native_name), Type.GetType (mangled));
}
[Obsolete ("Replaced by GType.Register (GType, Type)")]
public static void RegisterType (GType native_type, System.Type type)
{
GType.Register (native_type, type);
}
static Type GetTypeOrParent (IntPtr obj)
{
IntPtr typeid = GType.ValFromInstancePtr (obj);
if (typeid == GType.Invalid.Val)
return null;
Type result = GType.LookupType (typeid);
while (result == null) {
typeid = g_type_parent (typeid);
if (typeid == IntPtr.Zero)
return null;
result = GType.LookupType (typeid);
}
return result;
}
[DllImport ("libgobject-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr g_type_parent (IntPtr typ);
}
}
|
lgpl-2.1
|
C#
|
01b75499df3ce520d5117a0f968f20db8a26226c
|
Update ScheduleTomorrowController.cs
|
dkitchen/bpcc,dkitchen/bpcc
|
src/BPCCScheduler.Web/Controllers/ScheduleTomorrowController.cs
|
src/BPCCScheduler.Web/Controllers/ScheduleTomorrowController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BPCCScheduler.Controllers.BaseControllers;
using BPCCScheduler.Models;
using Twilio;
namespace BPCCScheduler.Controllers
{
public class ScheduleTomorrowController : AppointmentContextApiController
{
public IEnumerable<Appointment> Get()
{
//any appointment after tonight midnight, but before tomorrow midnight
var tonightMidnight = base.EasternStandardTimeNow.AddDays(1);
var tomorrowMidnight = tonightMidnight.AddHours(20);
var appts = base.AppointmentContext.Appointments.ToList() //materialize for date conversion
.Where(i => base.ToEST(i.Date) > tonightMidnight
&& base.ToEST(i.Date) < tomorrowMidnight);
return appts;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BPCCScheduler.Controllers.BaseControllers;
using BPCCScheduler.Models;
using Twilio;
namespace BPCCScheduler.Controllers
{
public class ScheduleTomorrowController : AppointmentContextApiController
{
public IEnumerable<Appointment> Get()
{
//any appointment after tonight midnight, but before tomorrow midnight
var tonightMidnight = base.EasternStandardTimeNow.AddDays(1);
var tomorrowMidnight = tonightMidnight.AddDays(1);
var appts = base.AppointmentContext.Appointments.ToList() //materialize for date conversion
.Where(i => base.ToEST(i.Date) > tonightMidnight
&& base.ToEST(i.Date) < tomorrowMidnight);
return appts;
}
}
}
|
mit
|
C#
|
303dda9737cb64981417211d2badc95fbcfa1d7f
|
Check if the project names (new and old one) are the same.
|
fdeitelhoff/Twainsoft.SimpleRenamer
|
src/VSX/Twainsoft.SolutionRenamer.VSPackage/GUI/RenameProjectDialog.xaml.cs
|
src/VSX/Twainsoft.SolutionRenamer.VSPackage/GUI/RenameProjectDialog.xaml.cs
|
using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using EnvDTE;
using MessageBox = System.Windows.Forms.MessageBox;
namespace Twainsoft.SolutionRenamer.VSPackage.GUI
{
public partial class RenameProjectDialog
{
private Project CurrentProject { get; set; }
public RenameProjectDialog(Project project)
{
InitializeComponent();
CurrentProject = project;
ProjectName.Text = project.Name;
ProjectName.Focus();
ProjectName.SelectAll();
}
public string GetProjectName()
{
return ProjectName.Text.Trim();
}
private void Rename_Click(object sender, RoutedEventArgs e)
{
var directory = new FileInfo(CurrentProject.FullName).Directory;
if (directory == null)
{
throw new InvalidOperationException();
}
var parentDirectory = directory.Parent;
if (parentDirectory == null)
{
throw new InvalidOperationException();
}
// Projects with the same name cannot be in the same folder due to the same folder names.
// Within the same solution it is no problem!
if (Directory.Exists(Path.Combine(parentDirectory.FullName, GetProjectName())))
{
MessageBox.Show(
string.Format(
"The project '{0}' already exists in the solution respectively the file system. Please choose another project name.",
GetProjectName()),
"Project already exists", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (CurrentProject.Name != GetProjectName())
{
DialogResult = true;
Close();
}
else
{
Close();
}
}
}
}
|
using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using EnvDTE;
using MessageBox = System.Windows.Forms.MessageBox;
namespace Twainsoft.SolutionRenamer.VSPackage.GUI
{
public partial class RenameProjectDialog
{
private Project CurrentProject { get; set; }
public RenameProjectDialog(Project project)
{
InitializeComponent();
CurrentProject = project;
ProjectName.Text = project.Name;
ProjectName.Focus();
ProjectName.SelectAll();
}
public string GetProjectName()
{
return ProjectName.Text.Trim();
}
private void Rename_Click(object sender, RoutedEventArgs e)
{
var directory = new FileInfo(CurrentProject.FullName).Directory;
if (directory == null)
{
throw new InvalidOperationException();
}
var parentDirectory = directory.Parent;
if (parentDirectory == null)
{
throw new InvalidOperationException();
}
// Projects with the same name cannot be in the same folder due to the same folder names.
// Within the same solution it is no problem!
if (Directory.Exists(Path.Combine(parentDirectory.FullName, GetProjectName())))
{
MessageBox.Show(
string.Format(
"The project '{0}' already exists in the solution respectively the file system. Please choose another project name.",
GetProjectName()),
"Project already exists", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
DialogResult = true;
Close();
}
}
}
}
|
mit
|
C#
|
b1f44a2ee2e94b732856fd195ce3c4c9fe1b9f8f
|
Fix state not propagating to FrameStatisticDisplays
|
RedNesto/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,default0/osu-framework,EVAST9919/osu-framework,paparony03/osu-framework,naoey/osu-framework,peppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,default0/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,paparony03/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,RedNesto/osu-framework,DrabWeb/osu-framework,naoey/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework
|
osu.Framework/Graphics/Performance/PerformanceOverlay.cs
|
osu.Framework/Graphics/Performance/PerformanceOverlay.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL;
using osu.Framework.Graphics.Textures;
using OpenTK.Graphics.ES30;
using osu.Framework.Threading;
using System.Collections.Generic;
namespace osu.Framework.Graphics.Performance
{
internal class PerformanceOverlay : FillFlowContainer<FrameStatisticsDisplay>, IStateful<FrameStatisticsMode>
{
private readonly TextureAtlas atlas;
private FrameStatisticsMode state;
public FrameStatisticsMode State
{
get { return state; }
set
{
if (state == value) return;
state = value;
switch (state)
{
case FrameStatisticsMode.None:
FadeOut(100);
break;
case FrameStatisticsMode.Minimal:
case FrameStatisticsMode.Full:
FadeIn(100);
break;
}
foreach (FrameStatisticsDisplay d in Children)
d.State = state;
}
}
public List<GameThread> Threads = new List<GameThread>();
public void CreateDisplays()
{
foreach (GameThread t in Threads)
Add(new FrameStatisticsDisplay(t, atlas) { State = state });
}
public PerformanceOverlay()
{
Direction = FillDirection.Vertical;
atlas = new TextureAtlas(GLWrapper.MaxTextureSize, GLWrapper.MaxTextureSize, true, All.Nearest);
}
}
public enum FrameStatisticsMode
{
None,
Minimal,
Full
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL;
using osu.Framework.Graphics.Textures;
using OpenTK.Graphics.ES30;
using osu.Framework.Threading;
using System.Collections.Generic;
namespace osu.Framework.Graphics.Performance
{
internal class PerformanceOverlay : FillFlowContainer<FrameStatisticsDisplay>, IStateful<FrameStatisticsMode>
{
private readonly TextureAtlas atlas;
private FrameStatisticsMode state;
public FrameStatisticsMode State
{
get { return state; }
set
{
if (state == value) return;
state = value;
switch (state)
{
case FrameStatisticsMode.None:
FadeOut(100);
break;
case FrameStatisticsMode.Minimal:
case FrameStatisticsMode.Full:
FadeIn(100);
break;
}
foreach (FrameStatisticsDisplay d in Children)
d.State = state;
}
}
public List<GameThread> Threads = new List<GameThread>();
public void CreateDisplays()
{
foreach (GameThread t in Threads)
Add(new FrameStatisticsDisplay(t, atlas));
}
public PerformanceOverlay()
{
Direction = FillDirection.Vertical;
atlas = new TextureAtlas(GLWrapper.MaxTextureSize, GLWrapper.MaxTextureSize, true, All.Nearest);
}
}
public enum FrameStatisticsMode
{
None,
Minimal,
Full
}
}
|
mit
|
C#
|
9b83207eb5e18dd1ee6d69450154a43869b29fc6
|
fix Assmebly name header name in Excel report
|
mjrousos/dotnet-apiport,Microsoft/dotnet-apiport,mjrousos/dotnet-apiport,Microsoft/dotnet-apiport,Microsoft/dotnet-apiport
|
src/lib/Microsoft.Fx.Portability/Reporting/ObjectModel/MissingMemberInfo.cs
|
src/lib/Microsoft.Fx.Portability/Reporting/ObjectModel/MissingMemberInfo.cs
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Fx.Portability.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Fx.Portability.Reporting.ObjectModel
{
public class MissingMemberInfo : MissingInfo
{
private readonly HashSet<AssemblyInfo> _usedInAssemblies;
public IEnumerable<AssemblyInfo> UsedIn
{
get { return _usedInAssemblies; }
}
public int Uses
{
get { return _usedInAssemblies.Count; }
}
public string MemberName { get; set; }
public IEnumerable<string> TargetStatus { get; set; }
public IEnumerable<Version> TargetVersionStatus { get; set; }
public void IncrementUsage(AssemblyInfo sourceAssembly)
{
_usedInAssemblies.Add(sourceAssembly);
}
public MissingMemberInfo(AssemblyInfo sourceAssembly, string docId, List<Version> targetStatus, string recommendedChanges)
: base(docId)
{
RecommendedChanges = recommendedChanges;
MemberName = docId;
TargetStatus = targetStatus?.Select(GenerateTargetStatusMessage).ToList() ?? Enumerable.Empty<string>();
TargetVersionStatus = new List<Version>(targetStatus ?? Enumerable.Empty<Version>());
_usedInAssemblies = new HashSet<AssemblyInfo>();
if (sourceAssembly != null)
{
_usedInAssemblies.Add(sourceAssembly);
}
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Fx.Portability.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Fx.Portability.Reporting.ObjectModel
{
public class MissingMemberInfo : MissingInfo
{
private readonly HashSet<AssemblyInfo> _usedInAssemblies;
public IEnumerable<AssemblyInfo> UsedIn { get; }
public int Uses
{
get { return _usedInAssemblies.Count; }
}
public string MemberName { get; set; }
public IEnumerable<string> TargetStatus { get; set; }
public IEnumerable<Version> TargetVersionStatus { get; set; }
public void IncrementUsage(AssemblyInfo sourceAssembly)
{
_usedInAssemblies.Add(sourceAssembly);
}
public MissingMemberInfo(AssemblyInfo sourceAssembly, string docId, List<Version> targetStatus, string recommendedChanges)
: base(docId)
{
RecommendedChanges = recommendedChanges;
MemberName = docId;
TargetStatus = targetStatus?.Select(GenerateTargetStatusMessage).ToList() ?? Enumerable.Empty<string>();
TargetVersionStatus = new List<Version>(targetStatus ?? Enumerable.Empty<Version>());
_usedInAssemblies = new HashSet<AssemblyInfo>();
if (sourceAssembly != null)
{
_usedInAssemblies.Add(sourceAssembly);
}
}
}
}
|
mit
|
C#
|
821607c0def266d8dd73a6e742079f175a4869c0
|
Fix an issue Tooltip does not show on the bottom right edge of the primary display
|
rubyu/CreviceApp,rubyu/CreviceApp
|
CreviceApp/Core.Config.UserInterfaceConfig.cs
|
CreviceApp/Core.Config.UserInterfaceConfig.cs
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CreviceApp.Core.Config
{
public class UserInterfaceConfig
{
public Func<Point, Point> TooltipPositionBinding;
public int TooltipTimeout = 2000;
public int BaloonTimeout = 10000;
public UserInterfaceConfig()
{
this.TooltipPositionBinding = (point) =>
{
var rect = Screen.FromPoint(point).WorkingArea;
return new Point(rect.X + rect.Width - 10, rect.Y + rect.Height - 10);
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CreviceApp.Core.Config
{
public class UserInterfaceConfig
{
public Func<Point, Point> TooltipPositionBinding;
public int TooltipTimeout = 2000;
public int BaloonTimeout = 10000;
public UserInterfaceConfig()
{
this.TooltipPositionBinding = (point) =>
{
var rect = Screen.FromPoint(point).WorkingArea;
return new Point(rect.X + rect.Width, rect.Y + rect.Height);
};
}
}
}
|
mit
|
C#
|
46c4a40feff8cc039324a81891c922bb8714fda0
|
Fix add notes, when notes are large
|
michael-reichenauer/GitMind
|
GitMind/Utils/Git/Private/GitNotesService2.cs
|
GitMind/Utils/Git/Private/GitNotesService2.cs
|
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using GitMind.Utils.OsSystem;
namespace GitMind.Utils.Git.Private
{
internal class GitNotesService2 : IGitNotesService2
{
private readonly IGitCmdService gitCmdService;
public GitNotesService2(IGitCmdService gitCmdService)
{
this.gitCmdService = gitCmdService;
}
public async Task<R<string>> GetNoteAsync(string sha, string notesRef, CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync(
$"-c core.notesRef={notesRef} notes show {sha}", ct);
if (result.IsFaulted)
{
if (result.ExitCode == 1 && result.Error.StartsWith($"error: no note found for object {sha}"))
{
return Error.NoValue;
}
return Error.From("Failed to get note", result.AsError());
}
string notes = result.Output;
Log.Info($"Got note {notes.Length} length");
return notes;
}
public async Task<R> AddNoteAsync(
string sha, string notesRef, string note, CancellationToken ct)
{
Log.Debug($"Adding {note.Length}chars on {sha} {notesRef} ...");
string filePath = Path.GetTempFileName();
File.WriteAllText(filePath, note);
CmdResult2 result = await gitCmdService.RunCmdAsync(
$"-c core.notesRef={notesRef} notes add -f --allow-empty -F \"{filePath}\" {sha}", ct);
DeleteNotesFile(filePath);
if (result.IsFaulted)
{
return Error.From("Failed to add note", result.AsError());
}
Log.Info($"Added note {note.Length} length");
return R.Ok;
}
public async Task<R> AppendNoteAsync(
string sha, string notesRef, string note, CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync(
$"-c core.notesRef={notesRef} notes append --allow-empty -m\"{note}\" {sha}", ct);
if (result.IsFaulted)
{
return Error.From("Failed to add note", result.AsError());
}
Log.Info($"Added note {note.Length} length");
return R.Ok;
}
public async Task<R> RemoveNoteAsync(string sha, string notesRef, CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync(
$"-c core.notesRef={notesRef} notes remove --ignore-missing {sha}", ct);
if (result.IsFaulted)
{
return Error.From("Failed to remove note", result.AsError());
}
Log.Info($"Removed note");
return R.Ok;
}
private static void DeleteNotesFile(string filePath)
{
try
{
File.Delete(filePath);
}
catch (Exception e)
{
Log.Warn($"Failed to delete temp notes file {filePath}, {e.Message}");
}
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using GitMind.Utils.OsSystem;
namespace GitMind.Utils.Git.Private
{
internal class GitNotesService2 : IGitNotesService2
{
private readonly IGitCmdService gitCmdService;
public GitNotesService2(IGitCmdService gitCmdService)
{
this.gitCmdService = gitCmdService;
}
public async Task<R<string>> GetNoteAsync(string sha, string notesRef, CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync(
$"-c core.notesRef={notesRef} notes show {sha}", ct);
if (result.IsFaulted)
{
if (result.ExitCode == 1 && result.Error.StartsWith($"error: no note found for object {sha}"))
{
return Error.NoValue;
}
return Error.From("Failed to get note", result.AsError());
}
string notes = result.Output;
Log.Info($"Got note {notes.Length} length");
return notes;
}
public async Task<R> AddNoteAsync(
string sha, string notesRef, string note, CancellationToken ct)
{
Log.Debug($"Adding {note.Length}chars on {sha} {notesRef} ...");
CmdResult2 result = await gitCmdService.RunCmdAsync(
$"-c core.notesRef={notesRef} notes add -f --allow-empty -m\"{note}\" {sha}", ct);
if (result.IsFaulted)
{
return Error.From("Failed to add note", result.AsError());
}
Log.Info($"Added note {note.Length} length");
return R.Ok;
}
public async Task<R> AppendNoteAsync(
string sha, string notesRef, string note, CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync(
$"-c core.notesRef={notesRef} notes append --allow-empty -m\"{note}\" {sha}", ct);
if (result.IsFaulted)
{
return Error.From("Failed to add note", result.AsError());
}
Log.Info($"Added note {note.Length} length");
return R.Ok;
}
public async Task<R> RemoveNoteAsync(string sha, string notesRef, CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync(
$"-c core.notesRef={notesRef} notes remove --ignore-missing {sha}", ct);
if (result.IsFaulted)
{
return Error.From("Failed to remove note", result.AsError());
}
Log.Info($"Removed note");
return R.Ok;
}
}
}
|
mit
|
C#
|
ee4ca4109b4950359c1ab680801aef36e707aa76
|
Use GoogleCredential.CreateScoped to create test credentials
|
GoogleCloudPlatform/iap-desktop,GoogleCloudPlatform/iap-desktop
|
Google.Solutions.Compute.Test/Env/Defaults.cs
|
Google.Solutions.Compute.Test/Env/Defaults.cs
|
//
// Copyright 2019 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using Google.Apis.Auth.OAuth2;
using System;
using System.IO;
namespace Google.Solutions.Compute.Test.Env
{
public static class Defaults
{
private const string CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform";
public static readonly string ProjectId = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT");
public static readonly string Zone = "us-central1-a";
public static GoogleCredential GetCredential()
{
var credential = GoogleCredential.GetApplicationDefault();
return credential.IsCreateScopedRequired
? credential.CreateScoped(CloudPlatformScope)
: credential;
}
}
}
|
//
// Copyright 2019 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using Google.Apis.Auth.OAuth2;
using System;
using System.IO;
namespace Google.Solutions.Compute.Test.Env
{
public static class Defaults
{
private const string CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform";
public static readonly string ProjectId = Environment.GetEnvironmentVariable("GOOGLE_CLOUD_PROJECT");
public static readonly string Zone = "us-central1-a";
public static GoogleCredential GetCredential()
{
var keyFile = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
if (keyFile != null && File.Exists(keyFile))
{
return GoogleCredential.FromFile(keyFile).CreateScoped(CloudPlatformScope);
}
else
{
return GoogleCredential.GetApplicationDefault();
}
}
}
}
|
apache-2.0
|
C#
|
74869983f4adf6e660afd713e56a50bfe491f468
|
Fix null refs
|
RichiCoder1/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,fishg/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,sriramgd/omnisharp-roslyn,nabychan/omnisharp-roslyn,hitesh97/omnisharp-roslyn,sriramgd/omnisharp-roslyn,sreal/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,nabychan/omnisharp-roslyn,hach-que/omnisharp-roslyn,hach-que/omnisharp-roslyn,khellang/omnisharp-roslyn,filipw/omnisharp-roslyn,jtbm37/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,jtbm37/omnisharp-roslyn,hal-ler/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,haled/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,khellang/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,fishg/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,sreal/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,filipw/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,hitesh97/omnisharp-roslyn,haled/omnisharp-roslyn,hal-ler/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
|
src/OmniSharp/Api/Navigation/OmnisharpController.GotoDefinition.cs
|
src/OmniSharp/Api/Navigation/OmnisharpController.GotoDefinition.cs
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
namespace OmniSharp
{
public partial class OmnisharpController
{
[HttpPost("gotodefinition")]
public async Task<IActionResult> GotoDefinition([FromBody]Request request)
{
_workspace.EnsureBufferUpdated(request);
var quickFixes = new List<QuickFix>();
var document = _workspace.GetDocument(request.FileName);
var response = new GotoDefinitionResponse();
if (document != null)
{
var semanticModel = await document.GetSemanticModelAsync();
var syntaxTree = semanticModel.SyntaxTree;
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, _workspace);
if (symbol != null)
{
var lineSpan = symbol.Locations.First().GetMappedLineSpan();
response = new GotoDefinitionResponse
{
FileName = lineSpan.Path,
Line = lineSpan.StartLinePosition.Line + 1,
Column = lineSpan.StartLinePosition.Character + 1
};
}
}
return new ObjectResult(response);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Models;
namespace OmniSharp
{
public partial class OmnisharpController
{
[HttpPost("gotodefinition")]
public async Task<IActionResult> GotoDefinition([FromBody]Request request)
{
_workspace.EnsureBufferUpdated(request);
var quickFixes = new List<QuickFix>();
var document = _workspace.GetDocument(request.FileName);
var response = new GotoDefinitionResponse();
if (document != null)
{
var semanticModel = await document.GetSemanticModelAsync();
var syntaxTree = semanticModel.SyntaxTree;
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(request.Line - 1, request.Column - 1));
var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, _workspace);
var lineSpan = symbol.Locations.First().GetMappedLineSpan();
response = new GotoDefinitionResponse
{
FileName = lineSpan.Path,
Line = lineSpan.StartLinePosition.Line + 1,
Column = lineSpan.StartLinePosition.Character + 1
};
}
return new ObjectResult(response);
}
}
}
|
mit
|
C#
|
31c7b80723189591166eb7e1b38f70124793f3de
|
Update PlayerBehaviour.cs
|
booiljoung/unitywallclimb
|
Assets/Scripts/PlayerBehaviour.cs
|
Assets/Scripts/PlayerBehaviour.cs
|
/*
* Unity3d Wall Climbing Demo
*
* Author: Booil Ted Joung
* Email : tedfromskyy@gmail.com
*
* */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*
* Wall Climbing Player Behaviour
*
* */
public class PlayerBehaviour
: MonoBehaviour
{
// Sense wall
public Transform hand;
public float handDistance = 0.2f;
// true if the character is on wall
private bool climbing = false;
void Start()
{
}
void Update()
{
float vinput = Input.GetAxis("Vertical");
float hinput = Input.GetAxis("Horizontal");
// detect wall with hand
RaycastHit handHit = new RaycastHit();
this.DetectHit(ref handHit, this.hand);
// detect new wall for climbling
if (!this.climbing && handHit.collider != null && Input.GetButton("Climb"))
{
this.climbing = true;
this.rigidbody.useGravity = false;
}
// no wall or stop climbing
else if (this.climbing && handHit.collider == null || !Input.GetButton("Climb"))
{
this.climbing = false;
this.rigidbody.useGravity = true;
}
// Jump
if (Input.GetButtonDown("Jump"))
{
this.climbing = false;
this.rigidbody.useGravity = true;
this.rigidbody.AddForce(0f, 300f, 0f);
}
// climbling action.
if (this.climbing)
{
this.rigidbody.velocity = this.transform.up * vinput * 5f + this.transform.right * hinput * 5f;
this.rigidbody.angularVelocity = Vector3.zero;
this.transform.rotation = Quaternion.LookRotation(handHit.normal*-1f);
}
// walking or jump action
else
{
this.rigidbody.velocity = this.rigidbody.velocity.y * this.transform.up + this.transform.forward * vinput * 5f;
this.rigidbody.angularVelocity = new Vector3(0f, hinput * 2f, 0f);
}
}
// detect raycat hit
void DetectHit(ref RaycastHit detectedHit, Transform transform)
{
RaycastHit[] hits = Physics.RaycastAll(transform.position, transform.forward, this.handDistance);
foreach (RaycastHit hit in hits)
{
if (hit.collider == this.collider)
continue;
if (hit.collider.isTrigger)
continue;
if (detectedHit.collider == null || hit.distance < detectedHit.distance)
detectedHit = hit;
}
}
// usage
void OnGUI()
{
GUI.TextField(new Rect(0f, 0f, 200f, 100f), "up, down, left, right: move, rotation\nleft shift: climbing\n");
}
// draw hand on unity3d scene
void OnDrawGizmos()
{
Gizmos.DrawLine(this.hand.position, this.hand.position + this.hand.forward * this.handDistance);
}
}
|
/*
* Unity3d Wall Climbing Demo
*
* Author: Booil Ted Joung
* Email : tedfromskyy@gmail.com
*
* */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*
* Wall Climbing Player Behaviour
*
* */
public class PlayerBehaviour
: MonoBehaviour
{
// Sense wall
public Transform hand;
public float handDistance = 0.2f;
// true if the character is on wall
private bool climbing = false;
void Start()
{
}
void Update()
{
float vinput = Input.GetAxis("Vertical");
float hinput = Input.GetAxis("Horizontal");
// detect wall with hand
RaycastHit handHit = new RaycastHit();
this.DetectHit(ref handHit, this.hand);
// detect new wall for climbling
if (!this.climbing && handHit.collider != null && Input.GetButton("Climb"))
{
this.climbing = true;
this.rigidbody.useGravity = false;
}
// no wall or stop climbing
else if (this.climbing && handHit.collider == null || !Input.GetButton("Climb"))
{
this.climbing = false;
this.rigidbody.useGravity = true;
}
// Jump
if (Input.GetButtonDown("Jump"))
{
this.climbing = false;
this.rigidbody.useGravity = true;
this.rigidbody.AddForce(0f, 300f, 0f);
}
// climbling action.
if (this.climbing)
{
this.rigidbody.velocity = this.transform.up * vinput * 5f + this.transform.right * hinput * 5f;
this.rigidbody.angularVelocity = Vector3.zero;
this.transform.rotation = Quaternion.LookRotation(handHit.normal*-1f);
}
// walking or jump action
else
{
this.rigidbody.velocity = this.rigidbody.velocity.y * this.transform.up + this.transform.forward * vinput * 5f;
this.rigidbody.angularVelocity = new Vector3(0f, hinput * 2f, 0f);
}
}
// detect raycat hit
void DetectHit(ref RaycastHit detectedHit, Transform transform)
{
RaycastHit[] hits = Physics.RaycastAll(transform.position, transform.forward, this.handDistance);
foreach (RaycastHit hit in hits)
{
if (hit.collider == this.collider)
continue;
if (hit.collider.isTrigger)
continue;
if (detectedHit.collider == null || hit.distance < detectedHit.distance)
detectedHit = hit;
}
}
// usage
void OnGUI()
{
GUI.TextField(new Rect(0f, 0f, 200f, 100f), "up, down, left, right: move, rotation\nleft shift: climbing\n");
}
// draw hand on unity3d scene
void OnDrawGizmos()
{
foreach (Transform hand in this.hand)
Gizmos.DrawLine(hand.position, hand.position + hand.forward * this.handDistance);
}
}
|
mit
|
C#
|
1be3d8e36edbe0aca0cade8615f3ac50d9ee49d5
|
Move to the new StripeBasicService instead of StripeService
|
richardlawley/stripe.net,stripe/stripe-dotnet
|
src/Stripe.net/Services/EphemeralKeys/StripeEphemeralKeyService.cs
|
src/Stripe.net/Services/EphemeralKeys/StripeEphemeralKeyService.cs
|
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeEphemeralKeyService : StripeBasicService<StripeEphemeralKey>
{
public StripeEphemeralKeyService(string apiKey = null) : base(apiKey) { }
// Sync
public virtual StripeEphemeralKey Create(StripeEphemeralKeyCreateOptions createOptions, StripeRequestOptions requestOptions = null)
{
return Post(Urls.EphemeralKeys, requestOptions, createOptions);
}
public virtual StripeDeleted Delete(string keyId, StripeRequestOptions requestOptions = null)
{
return DeleteEntity($"{Urls.EphemeralKeys}/{keyId}", requestOptions);
}
// Async
public virtual Task<StripeEphemeralKey> CreateAsync(StripeEphemeralKeyCreateOptions createOptions, StripeRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
return PostAsync(Urls.EphemeralKeys, requestOptions, cancellationToken, createOptions);
}
public virtual Task<StripeDeleted> DeleteAsync(string keyId, StripeRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteEntityAsync($"{Urls.EphemeralKeys}/{keyId}", requestOptions, cancellationToken);
}
}
}
|
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Stripe.Infrastructure;
namespace Stripe
{
public class StripeEphemeralKeyService : StripeService
{
public StripeEphemeralKeyService(string apiKey = null) : base(apiKey) { }
//Sync
public virtual StripeEphemeralKey Create(StripeEphemeralKeyCreateOptions createOptions, StripeRequestOptions requestOptions = null)
{
return Mapper<StripeEphemeralKey>.MapFromJson(
Requestor.PostString(this.ApplyAllParameters(createOptions, Urls.EphemeralKeys, false),
SetupRequestOptions(requestOptions))
);
}
public virtual StripeDeleted Delete(string EphemeralKeyId, StripeRequestOptions requestOptions = null)
{
return Mapper<StripeDeleted>.MapFromJson(
Requestor.Delete(this.ApplyAllParameters(null, $"{Urls.EphemeralKeys}/{EphemeralKeyId}", false),
SetupRequestOptions(requestOptions))
);
}
//Async
public virtual async Task<StripeEphemeralKey> CreateAsync(StripeEphemeralKeyCreateOptions createOptions, StripeRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Mapper<StripeEphemeralKey>.MapFromJson(
await Requestor.PostStringAsync(this.ApplyAllParameters(createOptions, Urls.EphemeralKeys, false),
SetupRequestOptions(requestOptions),
cancellationToken)
);
}
public virtual async Task<StripeDeleted> DeleteAsync(string EphemeralKeyId, StripeRequestOptions requestOptions = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Mapper<StripeDeleted>.MapFromJson(
await Requestor.DeleteAsync(this.ApplyAllParameters(null, $"{Urls.EphemeralKeys}/{EphemeralKeyId}", false),
SetupRequestOptions(requestOptions),
cancellationToken)
);
}
}
}
|
apache-2.0
|
C#
|
74ac6eaa4e38d10e24a7cb493309093e0f9e5b63
|
Fix typo
|
GuardTime/ksi-net-sdk,GuardTime/ksi-net-sdk
|
ksi-net-api/Service/ServiceCredentials.cs
|
ksi-net-api/Service/ServiceCredentials.cs
|
/*
* Copyright 2013-2018 Guardtime, Inc.
*
* This file is part of the Guardtime client SDK.
*
* 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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
* "Guardtime" and "KSI" are trademarks or registered trademarks of
* Guardtime, Inc., and no license to trademarks is granted; Guardtime
* reserves and retains all trademark rights.
*/
using Guardtime.KSI.Hashing;
using Guardtime.KSI.Utils;
namespace Guardtime.KSI.Service
{
/// <summary>
/// Service credentials.
/// </summary>
public class ServiceCredentials : IServiceCredentials
{
/// <summary>
/// Create service credentials object from login ID and login key as bytes.
/// </summary>
/// <param name="loginId">login ID</param>
/// <param name="loginKey">login key</param>
/// <param name="macAlgorithm">MAC calculation algorithm of outgoing and incoming messages</param>
public ServiceCredentials(string loginId, byte[] loginKey, HashAlgorithm macAlgorithm = null)
{
LoginId = loginId;
LoginKey = loginKey;
MacAlgorithm = macAlgorithm;
}
/// <summary>
/// Create service credentials object from login ID and login key as string.
/// </summary>
/// <param name="loginId">login ID</param>
/// <param name="loginKey">login key</param>
/// <param name="macAlgorithm">MAC calculation algorithm of outgoing and incoming messages</param>
public ServiceCredentials(string loginId, string loginKey, HashAlgorithm macAlgorithm = null) : this(loginId, Util.EncodeNullTerminatedUtf8String(loginKey), macAlgorithm)
{
}
/// <summary>
/// Get login ID.
/// </summary>
public string LoginId { get; }
/// <summary>
/// Get login key.
/// </summary>
public byte[] LoginKey { get; }
/// <summary>
/// MAC calculation algorithm of outgoing and incoming messages
/// </summary>
public HashAlgorithm MacAlgorithm { get; }
}
}
|
/*
* Copyright 2013-2018 Guardtime, Inc.
*
* This file is part of the Guardtime client SDK.
*
* 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, CONDITIONS, OR OTHER LICENSES OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
* "Guardtime" and "KSI" are trademarks or registered trademarks of
* Guardtime, Inc., and no license to trademarks is granted; Guardtime
* reserves and retains all trademark rights.
*/
using Guardtime.KSI.Hashing;
using Guardtime.KSI.Utils;
namespace Guardtime.KSI.Service
{
/// <summary>
/// Service credentials.
/// </summary>
public class ServiceCredentials : IServiceCredentials
{
/// <summary>
/// Create service credentials object from login ID and login key as bytes.
/// </summary>
/// <param name="loginId">login ID</param>
/// <param name="loginKey">login key</param>
/// <param name="macAlgorithm">MAC calculation algorithm of outgoing and incoming messages</param>
public ServiceCredentials(string loginId, byte[] loginKey, HashAlgorithm macAlgorithm = null)
{
LoginId = loginId;
LoginKey = loginKey;
MacAlgorithm = macAlgorithm;
}
/// <summary>
/// Create servoce credentials object from login ID and login key as string.
/// </summary>
/// <param name="loginId">login ID</param>
/// <param name="loginKey">login key</param>
/// <param name="macAlgorithm">MAC calculation algorithm of outgoing and incoming messages</param>
public ServiceCredentials(string loginId, string loginKey, HashAlgorithm macAlgorithm = null) : this(loginId, Util.EncodeNullTerminatedUtf8String(loginKey), macAlgorithm)
{
}
/// <summary>
/// Get login ID.
/// </summary>
public string LoginId { get; }
/// <summary>
/// Get login key.
/// </summary>
public byte[] LoginKey { get; }
/// <summary>
/// MAC calculation algorithm of outgoing and incoming messages
/// </summary>
public HashAlgorithm MacAlgorithm { get; }
}
}
|
apache-2.0
|
C#
|
87a154f6ff34b98853ce10b5072257cee3a3f08d
|
scale tree.
|
bitzhuwei/CSharpGL,bitzhuwei/CSharpGL,bitzhuwei/CSharpGL
|
Demos/GridViewer/Scripts/ModelScaleScript.cs
|
Demos/GridViewer/Scripts/ModelScaleScript.cs
|
using CSharpGL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GridViewer
{
/// <summary>
/// scale model and its children models recursively.
/// </summary>
public class ModelScaleScript : ScriptComponent
{
private vec3 scale;
[Browsable(true)]
[Description("Invoke SetScale(vec3 factor) by modifing this property.")]
public vec3 Scale
{
get { return scale; }
set
{
scale = value;
this.SetScale(value);
}
}
public bool SetScale(vec3 factor)
{
bool updated = false;
var stack = new Stack<SceneObject>();
vec3 rootPosition;
{
SceneObject obj = this.BindingObject;
if (obj == null) { throw new Exception(); }
var transform = obj.Renderer as IModelTransform;
if (transform == null) { throw new Exception(); }
rootPosition = transform.ModelMatrix.GetTranslate();
stack.Push(obj);
}
while (stack.Count > 0)
{
SceneObject obj = stack.Pop();
var transform = obj.Renderer as IModelTransform;
if (transform != null)
{
vec3 position = transform.ModelMatrix.GetTranslate();
vec3 distance = position - rootPosition;
//mat4 model = glm.translate(mat4.identity(), distance);
mat4 model = glm.translate(mat4.identity(), rootPosition);
model = glm.scale(model, factor);
model = glm.translate(model, distance);
transform.ModelMatrix = model;
updated = true;
}
foreach (var item in obj.Children) { stack.Push(item); }
}
return updated;
}
}
}
|
using CSharpGL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GridViewer
{
/// <summary>
/// scale model and its children models recursively.
/// </summary>
public class ModelScaleScript : ScriptComponent
{
public bool Scale(vec3 factor)
{
bool updated = false;
var stack = new Stack<SceneObject>();
vec3 rootPosition;
{
SceneObject obj = this.BindingObject;
if (obj == null) { throw new Exception(); }
var transform = obj.Renderer as IModelTransform;
if (transform == null) { throw new Exception(); }
rootPosition = transform.ModelMatrix.GetTranslate();
foreach (var item in obj.Children) { stack.Push(item); }
}
while (stack.Count > 0)
{
SceneObject obj = stack.Pop();
var transform = obj.Renderer as IModelTransform;
if (transform != null)
{
vec3 position = transform.ModelMatrix.GetTranslate();
vec3 distance = position - rootPosition;
mat4 model = glm.translate(mat4.identity(), distance);
model = glm.scale(model, factor);
transform.ModelMatrix = model;
updated = true;
}
foreach (var item in obj.Children) { stack.Push(item); }
}
return updated;
}
}
}
|
mit
|
C#
|
b3e99bce79cadb59f3e53729c377362da6a29545
|
remove unused using directives
|
dnauck/License.Manager,dnauck/License.Manager
|
src/License.Manager.Core/ServiceModel/GetLicenseTypes.cs
|
src/License.Manager.Core/ServiceModel/GetLicenseTypes.cs
|
using System.Collections.Generic;
using ServiceStack.ServiceHost;
namespace License.Manager.Core.ServiceModel
{
[Route("/licenses/types", "GET, OPTIONS")]
public class GetLicenseTypes : IReturn<List<Portable.Licensing.LicenseType>>
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.ServiceHost;
namespace License.Manager.Core.ServiceModel
{
[Route("/licenses/types", "GET, OPTIONS")]
public class GetLicenseTypes : IReturn<List<Portable.Licensing.LicenseType>>
{
}
}
|
mit
|
C#
|
d98cbef285ac9bf76f092c605a5945bcba964205
|
Update HttpRequestHandlerDefinition
|
glenndierckx/RequestHandlers,Smartasses/RequestHandlers
|
src/RequestHandlers/Http/HttpRequestHandlerDefinition.cs
|
src/RequestHandlers/Http/HttpRequestHandlerDefinition.cs
|
using System.Linq;
using System.Reflection;
namespace RequestHandlers.Http
{
public class HttpRequestHandlerDefinition
{
public HttpRequestHandlerDefinition(HttpRequestAttribute attribute, IRequestDefinition definition)
{
var parsedRoute = attribute.Parse();
var isFormRequest = definition.RequestType.GetTypeInfo().GetCustomAttribute<Http.FromFormAttribute>() != null;
var canHaveBody = attribute.HttpMethod == HttpMethod.Patch
|| attribute.HttpMethod == HttpMethod.Post
|| attribute.HttpMethod == HttpMethod.Delete
|| attribute.HttpMethod == HttpMethod.Put;
var bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.GetProperty;
var defaultBinder = // when unable to detect binding, this will be the default
canHaveBody
? isFormRequest
? BindingType.FromForm
: BindingType.FromBody
: BindingType.FromQuery;
var binderHelper = new HttpRequestPropertyBinderHelper(defaultBinder, parsedRoute);
var allProperties = definition.RequestType.GetProperties(bindingFlags);
foreach (var propertyInfo in allProperties)
{
binderHelper.AddBinder(propertyInfo);
}
Parameters = binderHelper.GetPropertiesAndBinding().ToArray();
HttpMethod = attribute.HttpMethod;
Route = parsedRoute.Route;
Definition = definition;
ServiceName = attribute.ServiceName ?? definition.RequestType.Name + "Handler";
ActionName = definition.RequestType.Name.EndsWith("Request")
? definition.RequestType.Name.Substring(0, definition.RequestType.Name.Length - "Request".Length)
: definition.RequestType.Name;
}
public string ActionName { get; set; }
public string ServiceName { get; set; }
public IRequestDefinition Definition { get; set; }
public string Route { get; set; }
public HttpMethod HttpMethod { get; set; }
public HttpPropertyBinding[] Parameters { get; }
}
}
|
using System.Linq;
using System.Reflection;
namespace RequestHandlers.Http
{
public class HttpRequestHandlerDefinition
{
public HttpRequestHandlerDefinition(HttpRequestAttribute attribute, IRequestDefinition definition)
{
var parsedRoute = attribute.Parse();
var isFormRequest = definition.RequestType.GetTypeInfo().GetCustomAttribute<Http.FromFormAttribute>() != null;
var canHaveBody = attribute.HttpMethod == HttpMethod.Patch
|| attribute.HttpMethod == HttpMethod.Post
|| attribute.HttpMethod == HttpMethod.Put;
var bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.GetProperty;
var defaultBinder = // when unable to detect binding, this will be the default
canHaveBody
? isFormRequest
? BindingType.FromForm
: BindingType.FromBody
: BindingType.FromQuery;
var binderHelper = new HttpRequestPropertyBinderHelper(defaultBinder, parsedRoute);
var allProperties = definition.RequestType.GetProperties(bindingFlags);
foreach (var propertyInfo in allProperties)
{
binderHelper.AddBinder(propertyInfo);
}
Parameters = binderHelper.GetPropertiesAndBinding().ToArray();
HttpMethod = attribute.HttpMethod;
Route = parsedRoute.Route;
Definition = definition;
ServiceName = attribute.ServiceName ?? definition.RequestType.Name + "Handler";
ActionName = definition.RequestType.Name.EndsWith("Request")
? definition.RequestType.Name.Substring(0, definition.RequestType.Name.Length - "Request".Length)
: definition.RequestType.Name;
}
public string ActionName { get; set; }
public string ServiceName { get; set; }
public IRequestDefinition Definition { get; set; }
public string Route { get; set; }
public HttpMethod HttpMethod { get; set; }
public HttpPropertyBinding[] Parameters { get; }
}
}
|
mit
|
C#
|
2d054768d2771c7b3cc00352e02bc23b71165fd3
|
add Guard overload and set default messages
|
acple/ParsecSharp
|
ParsecSharp/Parser/Parser.Monad.Extensions.cs
|
ParsecSharp/Parser/Parser.Monad.Extensions.cs
|
using System;
using System.Runtime.CompilerServices;
using ParsecSharp.Internal;
namespace ParsecSharp
{
public static partial class Parser
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, TResult> Bind<TToken, T, TResult>(this Parser<TToken, T> parser, Func<T, Parser<TToken, TResult>> next)
=> new Bind<TToken, T, TResult>(parser, next);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, TResult> Bind<TToken, T, TResult>(this Parser<TToken, T> parser, Func<T, Parser<TToken, TResult>> next, Func<Fail<TToken, T>, Parser<TToken, TResult>> resume)
=> new Next<TToken, T, TResult>(parser, next, resume);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Alternative<TToken, T>(this Parser<TToken, T> first, Parser<TToken, T> second)
=> new Alternative<TToken, T>(first, second);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Alternative<TToken, T>(this Parser<TToken, T> parser, Func<Fail<TToken, T>, Parser<TToken, T>> resume)
=> new Resume<TToken, T>(parser, resume);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, TResult> Map<TToken, T, TResult>(this Parser<TToken, T> parser, Func<T, TResult> function)
=> parser.Bind(x => Pure<TToken, TResult>(function(x)));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Guard<TToken, T>(this Parser<TToken, T> parser, Func<T, bool> predicate)
=> parser.Guard(predicate, x => $"A value '{x?.ToString() ?? "<null>"}' doesn't satisfy condition");
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Guard<TToken, T>(this Parser<TToken, T> parser, Func<T, bool> predicate, Func<T, string> message)
=> parser.Bind(x => (predicate(x)) ? Pure<TToken, T>(x) : Fail<TToken, T>($"At {nameof(Guard)}, {message(x)}"));
}
}
|
using System;
using System.Runtime.CompilerServices;
using ParsecSharp.Internal;
namespace ParsecSharp
{
public static partial class Parser
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, TResult> Bind<TToken, T, TResult>(this Parser<TToken, T> parser, Func<T, Parser<TToken, TResult>> next)
=> new Bind<TToken, T, TResult>(parser, next);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, TResult> Bind<TToken, T, TResult>(this Parser<TToken, T> parser, Func<T, Parser<TToken, TResult>> next, Func<Fail<TToken, T>, Parser<TToken, TResult>> resume)
=> new Next<TToken, T, TResult>(parser, next, resume);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Alternative<TToken, T>(this Parser<TToken, T> first, Parser<TToken, T> second)
=> new Alternative<TToken, T>(first, second);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Alternative<TToken, T>(this Parser<TToken, T> parser, Func<Fail<TToken, T>, Parser<TToken, T>> resume)
=> new Resume<TToken, T>(parser, resume);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, TResult> Map<TToken, T, TResult>(this Parser<TToken, T> parser, Func<T, TResult> function)
=> parser.Bind(x => Pure<TToken, TResult>(function(x)));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Guard<TToken, T>(this Parser<TToken, T> parser, Func<T, bool> predicate)
=> parser.Bind(x => (predicate(x)) ? Pure<TToken, T>(x) : Fail<TToken, T>());
}
}
|
mit
|
C#
|
c1f02db655f91656347d21944a3d19dc44df7966
|
add example to update a row (PetaPoco)
|
jgraber/MicroORM_examples,jgraber/MicroORM_examples,jgraber/MicroORM_examples
|
MicroORM_Dapper/MicroORM_PetaPoco/Program.cs
|
MicroORM_Dapper/MicroORM_PetaPoco/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MicroORM_Dapper;
using PetaPoco;
namespace MicroORM_PetaPoco
{
class Program
{
static void Main(string[] args)
{
ReadData();
WriteData();
UpdateData();
}
private static void ReadData()
{
Console.WriteLine("Get all books");
var database = new Database("OrmConnection");
var books = database.Query<Book>("SELECT * FROM BOOK;");
foreach (var book in books)
{
Console.WriteLine(book);
}
}
private static void WriteData()
{
Book book = new Book() { Title = "PetaPoco - The Book", Summary = "Another Micro ORM", Pages = 200, Rating = 5 };
var database = new Database("OrmConnection");
database.Insert("Book", "Id", book);
Console.WriteLine("Inserted book with PetaPoco:");
Console.WriteLine(book);
}
private static void UpdateData()
{
var database = new Database("OrmConnection");
var book = database.Query<Book>("SELECT TOP 1 * FROM Book ORDER BY Id desc").Single();
book.Title = "An Updated Title for PetaPoco";
database.Update("Book", "Id", book);
var updatedBook = database.Query<Book>("SELECT * FROM Book WHERE Id = @0", book.Id).Single();
Console.WriteLine("The updated book with PetaPoco:");
Console.WriteLine(updatedBook);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MicroORM_Dapper;
using PetaPoco;
namespace MicroORM_PetaPoco
{
class Program
{
static void Main(string[] args)
{
ReadData();
WriteData();
}
private static void ReadData()
{
Console.WriteLine("Get all books");
var database = new Database("OrmConnection");
var books = database.Query<Book>("SELECT * FROM BOOK;");
foreach (var book in books)
{
Console.WriteLine(book);
}
}
private static void WriteData()
{
Book book = new Book() { Title = "PetaPoco - The Book", Summary = "Another Micro ORM", Pages = 200, Rating = 5 };
var database = new Database("OrmConnection");
database.Insert("Book", "Id", book);
Console.WriteLine("Inserted book with PetaPoco:");
Console.WriteLine(book);
}
}
}
|
apache-2.0
|
C#
|
328943cb36e99468664c43c253f4d8d6dc78fbe5
|
remove unnecessary using directive.
|
jwChung/Experimentalism,jwChung/Experimentalism
|
test/Experiment.AutoFixtureUnitTest/AssemblyLevelTest.cs
|
test/Experiment.AutoFixtureUnitTest/AssemblyLevelTest.cs
|
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
using Xunit.Extensions;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutReferencesOnlySpecifiedAssemblies()
{
var sut = typeof(TheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"Jwc.Experiment",
"Ploeh.AutoFixture"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
[Theory]
[InlineData("TheoremAttribute")]
[InlineData("TestFixtureAdapter")]
public void SutGeneratesNugetTransformFiles(string originName)
{
string directory = @"..\..\..\..\src\Experiment.AutoFixture\";
var origin = directory + originName + ".cs";
var destination = directory + originName + ".cs.pp";
Assert.True(File.Exists(origin), "exists.");
VerifyGenerateFile(origin, destination);
}
[Conditional("CI")]
private static void VerifyGenerateFile(string origin, string destination)
{
var content = File.ReadAllText(origin, Encoding.UTF8)
.Replace("namespace Jwc.Experiment", "namespace $rootnamespace$");
File.WriteAllText(destination, content, Encoding.UTF8);
Assert.True(File.Exists(destination), "exists.");
}
}
}
|
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Jwc.Experiment;
using Xunit;
using Xunit.Extensions;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutReferencesOnlySpecifiedAssemblies()
{
var sut = typeof(TheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"Jwc.Experiment",
"Ploeh.AutoFixture"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
[Theory]
[InlineData("TheoremAttribute")]
[InlineData("TestFixtureAdapter")]
public void SutGeneratesNugetTransformFiles(string originName)
{
string directory = @"..\..\..\..\src\Experiment.AutoFixture\";
var origin = directory + originName + ".cs";
var destination = directory + originName + ".cs.pp";
Assert.True(File.Exists(origin), "exists.");
VerifyGenerateFile(origin, destination);
}
[Conditional("CI")]
private static void VerifyGenerateFile(string origin, string destination)
{
var content = File.ReadAllText(origin, Encoding.UTF8)
.Replace("namespace Jwc.Experiment", "namespace $rootnamespace$");
File.WriteAllText(destination, content, Encoding.UTF8);
Assert.True(File.Exists(destination), "exists.");
}
}
}
|
mit
|
C#
|
adcc176f3419d5249b10d055ffd249e1c997c55b
|
Add PlayerSpaceship to a level
|
andrewjleavitt/SpaceThing
|
Assets/Scripts/LevelManager.cs
|
Assets/Scripts/LevelManager.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelManager : MonoBehaviour {
public EnemySpaceShip enemy;
public PlayerSpaceShip player;
public void SetupLevel() {
LayoutObject();
}
private void LayoutObject() {
Instantiate(enemy, new Vector3(9f, 0f, 0f), Quaternion.identity);
Instantiate(player, new Vector3(-9f, 0f, 0f), Quaternion.identity);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelManager : MonoBehaviour {
public EnemySpaceShip enemy;
public void SetupLevel() {
LayoutObject();
}
private void LayoutObject() {
Instantiate(enemy, new Vector3(9f, 0f, 0f), Quaternion.identity);
}
}
|
unlicense
|
C#
|
9ffdd59aed896df85dc8a024632084b1e8fc16a6
|
fix local conflicts
|
NataliaDSmirnova/CGAdvanced2017
|
Assets/Scripts/RenderObject.cs
|
Assets/Scripts/RenderObject.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RenderObject : MonoBehaviour {
public GameObject renderObject;
private RenderTexture renderTexture;
private SpriteRenderer spriteRenderer;
private RawImage image;
private RenderTexture rt;
void Start () {
image = GetComponent<RawImage>();
rt = RenderTexture.GetTemporary(Screen.width, Screen.height);
}
void Update () {
Graphics.SetRenderTarget(rt);
Mesh objectMesh = renderObject.GetComponent<MeshFilter>().sharedMesh;
var renderer = renderObject.GetComponent<MeshRenderer>();
renderer.material.SetPass(0);
Graphics.DrawMeshNow(objectMesh, objectMesh.vertices[0], Quaternion.identity);
image.texture = rt;
Graphics.SetRenderTarget(null);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RenderObject : MonoBehaviour {
public GameObject renderObject;
<<<<<<< HEAD
private RenderTexture renderTexture;
private SpriteRenderer spriteRenderer;
private int xSizeOfSprite;
private int ySizeOfSprite;
void Start () {
spriteRenderer = GetComponent<Renderer>() as SpriteRenderer;
xSizeOfSprite = (int) spriteRenderer.sprite.border.x;
ySizeOfSprite = (int) spriteRenderer.sprite.border.y;
=======
private RawImage image;
private RenderTexture rt;
void Start () {
image = GetComponent<RawImage>();
rt = RenderTexture.GetTemporary(Screen.width, Screen.height);
>>>>>>> origin/master
}
void Update () {
Graphics.SetRenderTarget(rt);
Mesh objectMesh = renderObject.GetComponent<MeshFilter>().sharedMesh;
<<<<<<< HEAD
Graphics.DrawMeshNow(objectMesh, renderObject.transform.position, Quaternion.identity);
=======
var renderer = renderObject.GetComponent<MeshRenderer>();
renderer.material.SetPass(0);
Graphics.DrawMeshNow(objectMesh, objectMesh.vertices[0], Quaternion.identity);
>>>>>>> origin/master
image.texture = rt;
Graphics.SetRenderTarget(null);
}
}
|
mit
|
C#
|
4d92b40f29c12e1fb6b2f96d69fd73ae6ced99a7
|
Use UIImage.FromFile instead of reading from the file store into memory because it's faster.
|
Didux/MvvmCross-Plugins,martijn00/MvvmCross-Plugins,MatthewSannes/MvvmCross-Plugins,lothrop/MvvmCross-Plugins
|
Cirrious/DownloadCache/Cirrious.MvvmCross.Plugins.DownloadCache.Touch/MvxTouchLocalFileImageLoader.cs
|
Cirrious/DownloadCache/Cirrious.MvvmCross.Plugins.DownloadCache.Touch/MvxTouchLocalFileImageLoader.cs
|
// MvxTouchLocalFileImageLoader.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Plugins.File;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Cirrious.MvvmCross.Plugins.DownloadCache.Touch
{
public class MvxTouchLocalFileImageLoader
: IMvxLocalFileImageLoader<UIImage>
{
private const string ResourcePrefix = "res:";
public MvxImage<UIImage> Load(string localPath, bool shouldCache)
{
UIImage uiImage;
if (localPath.StartsWith(ResourcePrefix))
{
var resourcePath = localPath.Substring(ResourcePrefix.Length);
uiImage = LoadResourceImage(resourcePath, shouldCache);
}
else
{
uiImage = LoadUIImage(localPath);
}
return new MvxTouchImage(uiImage);
}
private UIImage LoadUIImage(string localPath)
{
var file = Mvx.Resolve<IMvxFileStore>();
var nativePath = file.NativePath(localPath);
return UIImage.FromFile(nativePath);
}
private UIImage LoadResourceImage(string resourcePath, bool shouldCache)
{
if (shouldCache)
return UIImage.FromFile(resourcePath);
else
return UIImage.FromFileUncached(resourcePath);
}
}
}
|
// MvxTouchLocalFileImageLoader.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Plugins.File;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace Cirrious.MvvmCross.Plugins.DownloadCache.Touch
{
public class MvxTouchLocalFileImageLoader
: IMvxLocalFileImageLoader<UIImage>
{
private const string ResourcePrefix = "res:";
public MvxImage<UIImage> Load(string localPath, bool shouldCache)
{
UIImage uiImage;
if (localPath.StartsWith(ResourcePrefix))
{
var resourcePath = localPath.Substring(ResourcePrefix.Length);
uiImage = LoadResourceImage(resourcePath, shouldCache);
}
else
{
uiImage = LoadUIImage(localPath);
}
return new MvxTouchImage(uiImage);
}
private UIImage LoadUIImage(string localPath)
{
var file = Mvx.Resolve<IMvxFileStore>();
byte[] data = null;
if (!file.TryReadBinaryFile(localPath, stream =>
{
var memoryStream = new System.IO.MemoryStream();
stream.CopyTo(memoryStream);
data = memoryStream.GetBuffer();
return true;
}))
return null;
var imageData = NSData.FromArray(data);
return UIImage.LoadFromData(imageData);
}
private UIImage LoadResourceImage(string resourcePath, bool shouldCache)
{
if (shouldCache)
return UIImage.FromFile(resourcePath);
else
return UIImage.FromFileUncached(resourcePath);
}
}
}
|
mit
|
C#
|
c34ab15bc4f45188c56c60c9d0b64cc3029bab8a
|
Remove unused binding
|
dirkrombauts/production-helper-for-ti3
|
ProductionHelperForTI3.Specification.AutomationLayer/Bindings.cs
|
ProductionHelperForTI3.Specification.AutomationLayer/Bindings.cs
|
using TechTalk.SpecFlow;
using ProductionHelperForTI3.Domain;
namespace ProductionHelperForTI3.Specification.AutomationLayer
{
using NFluent;
[Binding]
public class Bindings
{
private Planet planet;
private SpaceDock spaceDock;
private Technology technology;
private ProductionRun productionRun;
private Race race;
[When(@"I produce '(.*)' '(.*)'")]
public void WhenIProduce(int numberOfUnits, string nameOfUnits)
{
var unit = new Unit(nameOfUnits);
if (this.productionRun == null)
{
this.productionRun = new ProductionRun(this.technology, this.race);
}
this.productionRun.Produce(numberOfUnits, unit);
}
[Given(@"I have the '(.*)' Technology")]
public void GivenIHaveTheTechnology(string technology)
{
this.technology = new Technology(technology);
}
[Then(@"I have to pay '(.*)' resource")]
[Then(@"I have to pay '(.*)' resources")]
[Then(@"I have to pay '(.*)' resource\(s\)")]
public void ThenIHaveToPayResources(int numberOfResources)
{
Check.That(this.productionRun.Cost).IsEqualTo(numberOfResources);
}
[Given(@"my Race is the '(.*)'")]
public void GivenMyRaceIsThe(string nameOfRace)
{
this.race = new Race(nameOfRace);
}
[Given(@"I have a planet with Resource Value '(.*)'")]
public void GivenIHaveAPlanetWithResourceValue(int resourceValue)
{
this.planet = new Planet { ResourceValue = resourceValue };
}
[When(@"I produce units at the space dock of that planet")]
public void WhenIProduceUnitsAtTheSpaceDockOfThatPlanet()
{
this.spaceDock = new SpaceDock(this.planet, this.technology);
}
[Then(@"the build limit is '(.*)'")]
public void ThenTheBuildLimitIs(int expectedBuildLimit)
{
Check.That(this.spaceDock.BuildLimit).IsEqualTo(expectedBuildLimit);
}
}
}
|
using TechTalk.SpecFlow;
using ProductionHelperForTI3.Domain;
namespace ProductionHelperForTI3.Specification.AutomationLayer
{
using NFluent;
using TechTalk.SpecFlow.Configuration;
[Binding]
public class Bindings
{
private Planet planet;
private SpaceDock spaceDock;
private Technology technology;
private ProductionRun productionRun;
private Race race;
[When(@"I produce '(.*)' '(.*)'")]
public void WhenIProduce(int numberOfUnits, string nameOfUnits)
{
var unit = new Unit(nameOfUnits);
if (this.productionRun == null)
{
this.productionRun = new ProductionRun(this.technology, this.race);
}
this.productionRun.Produce(numberOfUnits, unit);
}
[Given(@"I have the '(.*)' Technology")]
public void GivenIHaveTheTechnology(string technology)
{
this.technology = new Technology(technology);
}
[Then(@"I have to pay '(.*)' resource")]
[Then(@"I have to pay '(.*)' resources")]
[Then(@"I have to pay '(.*)' resource\(s\)")]
public void ThenIHaveToPayResources(int numberOfResources)
{
Check.That(this.productionRun.Cost).IsEqualTo(numberOfResources);
}
[Given(@"my Race is the '(.*)'")]
public void GivenMyRaceIsThe(string nameOfRace)
{
this.race = new Race(nameOfRace);
}
[Given(@"I have a planet with Resource Value '(.*)'")]
public void GivenIHaveAPlanetWithResourceValue(int resourceValue)
{
this.planet = new Planet { ResourceValue = resourceValue };
}
[When(@"I produce units at the space dock of that planet")]
public void WhenIProduceUnitsAtTheSpaceDockOfThatPlanet()
{
this.spaceDock = new SpaceDock(this.planet, this.technology);
}
[Then(@"the build limit is '(.*)'")]
public void ThenTheBuildLimitIs(int expectedBuildLimit)
{
Check.That(this.spaceDock.BuildLimit).IsEqualTo(expectedBuildLimit);
}
}
}
|
mit
|
C#
|
b73e137ff4ed19f85f376ab0f8a062c9617d689d
|
Simplify content set
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/ViewModels/AddWallet/LegalDocumentsViewModel.cs
|
WalletWasabi.Fluent/ViewModels/AddWallet/LegalDocumentsViewModel.cs
|
using ReactiveUI;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Legal;
using WalletWasabi.Services;
using System;
using System.Reactive.Linq;
using System.Reactive.Disposables;
namespace WalletWasabi.Fluent.ViewModels.AddWallet
{
[NavigationMetaData(
Title = "Legal Docs",
Caption = "Displays terms and conditions",
Order = 3,
Category = "General",
Keywords = new[] { "View", "Legal", "Docs", "Documentation", "Terms", "Conditions", "Help" },
IconName = "info_regular",
NavigationTarget = NavigationTarget.DialogScreen)]
public partial class LegalDocumentsViewModel : RoutableViewModel
{
[AutoNotify] private string? _content;
public LegalDocumentsViewModel(LegalChecker legalChecker)
{
Title = "Terms and Conditions";
NextCommand = BackCommand;
LegalChecker = legalChecker;
this.WhenAnyValue(x => x.Content)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(content => IsBusy = content is null);
}
private LegalChecker LegalChecker { get; }
protected override void OnNavigatedTo(bool inStack, CompositeDisposable disposable)
{
base.OnNavigatedTo(inStack, disposable);
Observable.Merge(
Observable.FromEventPattern<LegalDocuments>(LegalChecker, nameof(LegalChecker.AgreedChanged)),
Observable.FromEventPattern<LegalDocuments>(LegalChecker, nameof(LegalChecker.ProvisionalChanged)))
.Select(x => x.EventArgs)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(legalDocuments => Content = legalDocuments.Content)
.DisposeWith(disposable);
Content = LegalChecker.TryGetNewLegalDocs(out LegalDocuments? provisional)
? provisional.Content
: LegalChecker.CurrentLegalDocument is { } current
? current.Content
: null;
}
}
}
|
using ReactiveUI;
using WalletWasabi.Fluent.ViewModels.Navigation;
using WalletWasabi.Legal;
using WalletWasabi.Services;
using System;
using System.Reactive.Linq;
using System.Reactive.Disposables;
namespace WalletWasabi.Fluent.ViewModels.AddWallet
{
[NavigationMetaData(
Title = "Legal Docs",
Caption = "Displays terms and conditions",
Order = 3,
Category = "General",
Keywords = new[] { "View", "Legal", "Docs", "Documentation", "Terms", "Conditions", "Help" },
IconName = "info_regular",
NavigationTarget = NavigationTarget.DialogScreen)]
public partial class LegalDocumentsViewModel : RoutableViewModel
{
[AutoNotify] private string? _content;
public LegalDocumentsViewModel(LegalChecker legalChecker)
{
Title = "Terms and Conditions";
NextCommand = BackCommand;
LegalChecker = legalChecker;
this.WhenAnyValue(x => x.Content)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(content => IsBusy = content is null);
}
private LegalChecker LegalChecker { get; }
protected override void OnNavigatedTo(bool inStack, CompositeDisposable disposable)
{
base.OnNavigatedTo(inStack, disposable);
Observable.Merge(
Observable.FromEventPattern<LegalDocuments>(LegalChecker, nameof(LegalChecker.AgreedChanged)),
Observable.FromEventPattern<LegalDocuments>(LegalChecker, nameof(LegalChecker.ProvisionalChanged)))
.Select(x => x.EventArgs)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(legalDocuments => UpdateContent(legalDocuments))
.DisposeWith(disposable);
if (LegalChecker.TryGetNewLegalDocs(out LegalDocuments? provisional))
{
UpdateContent(provisional);
}
else if (LegalChecker.CurrentLegalDocument is { } current)
{
UpdateContent(current);
}
}
private void UpdateContent(LegalDocuments legalDocuments)
{
Content = legalDocuments.Content;
}
}
}
|
mit
|
C#
|
96fe070d39b29b08bfbc601c4c93176cfddb11c3
|
Add OMCode property
|
ADAPT/ADAPT
|
source/ADAPT/Documents/Obs.cs
|
source/ADAPT/Documents/Obs.cs
|
/*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190710 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class Obs // Corresponds to the original PAIL OM; renamed for clarity.
{
public Obs()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>(); // List of code components to allow parameters, semantic refinement
TimeScopes = new List<TimeScope>(); // PhenomenonTime / ResultTime / ValidityRange as per ISO 19156
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public int? OMSourceId { get; set; } // OMSource reduces Obs to (mostly) key,value pair even with sensors, installation
public int? OMCodeId { get; set; } // OMCode reduces Obs to (mostly) key,value pair when installation data is not needed
public string OMCode { get; set; } // The string value provides the simplest form of meaning, by referring a pre-existing semantic resource by name (code).
public List<int> CodeComponentIds { get; set; } // List of code components refs to allow parameters, semantic refinement
public List<TimeScope> TimeScopes { get; set; }
public int? GrowerId { get; set; } // Optional, provides ability to put an Obs in the context of a grower
public int? PlaceId { get; set; } // Optional, provides ability to put an Obs in the context of a Place
public Shape SpatialExtent { get; set; } // Optional, includes Point, Polyline, and Polygon features of interest
// Note: PlaceId provides a feature of interest by reference; SpatialExtent does so by value. They are not necessarily
// mutually exclusive.
public string Value { get; set; } // The actual value of the observation. Its meaning is described by the OMCodeDefinition
public string UoMCode { get; set; } // ADAPT codes for units of measure (e.g., "m1s-1" for meter/second) are required here.
// PAIL allows different UoMAuthorities; but translation must happen in the PAIL plug-in level.
public List<ContextItem> ContextItems { get; set; }
}
}
|
/*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190710 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class Obs // Corresponds to the original PAIL OM; renamed for clarity.
{
public Obs()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>(); // List of code components to allow parameters, semantic refinement
TimeScopes = new List<TimeScope>(); // PhenomenonTime / ResultTime / ValidityRange as per ISO 19156
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public int? OMSourceId { get; set; } // OMSource reduces Obs to (mostly) key,value pair even with sensors, installation
public int? OMCodeId { get; set; } // OMCode reduces Obs to (mostly) key,value pair when installation data is not needed
public List<int> CodeComponentIds { get; set; } // List of code components refs to allow parameters, semantic refinement
public List<TimeScope> TimeScopes { get; set; }
public int? GrowerId { get; set; } // Optional, provides ability to put an Obs in the context of a grower
public int? PlaceId { get; set; } // Optional, provides ability to put an Obs in the context of a Place
public Shape SpatialExtent { get; set; } // Optional, includes Point, Polyline, and Polygon features of interest
// Note: PlaceId provides a feature of interest by reference; SpatialExtent does so by value. They are not necessarily
// mutually exclusive.
public string Value { get; set; } // The actual value of the observation. Its meaning is described by the OMCodeDefinition
public string UoMCode { get; set; } // ADAPT codes are required here.
// PAIL allows different UoMAuthorities; but translation must happen in the PAIL plug-in level.
public List<ContextItem> ContextItems { get; set; }
}
}
|
epl-1.0
|
C#
|
f6c75f4d0290c2535d72985c5c7da6d775ca7c2b
|
Add OMCode property
|
ADAPT/ADAPT
|
source/ADAPT/Documents/ObsCollection.cs
|
source/ADAPT/Documents/ObsCollection.cs
|
/*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190430 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class ObsCollection
{
public ObsCollection()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>(); // List of code components that apply to all child Obs in the collection
TimeScopes = new List<TimeScope>(); // List of TimeScopes that apply to all child Obs in the collection
ContextItems = new List<ContextItem>();
ObsCollectionIds = new List<int>(); // Note: these are references to ObsCollections in Documents
ObsIds = new List<int>(); // Note: these are references to Obs in Documents
}
public CompoundIdentifier Id { get; private set; }
public int? OMSourceId { get; set; } // OMSource reduces child Obs to (mostly) key,value pair even with sensors, installation
public int? OMCodeId { get; set; } // OMCode reduces child Obs to (mostly) key,value pair when installation data is not needed
public string OMCode { get; set; } // The string value provides the simplest form of meaning, by referring a pre-existing semantic resource by name (code).
public List<int> CodeComponentIds { get; set; } // List of code components refs to allow parameters, semantic refinement
public List<TimeScope> TimeScopes { get; set; }
public int? GrowerId { get; set; } // Optional, provides ability to put an ObsCollection in the context of a grower
public int? PlaceId { get; set; } // Optional, provides ability to put an ObsCollection in the context of a Place
public Shape SpatialExtent { get; set; } // Optional, includes Point, Polyline, and Polygon features of interest
// Note: PlaceId provides a feature of interest by reference; SpatialExtent does so by value. They are not necessarily
// mutually exclusive.
public List<int> ObsCollectionIds { get; set; } // Recursive!
public List<int> ObsIds { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
|
/*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190430 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class ObsCollection
{
public ObsCollection()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>(); // List of code components that apply to all child Obs in the collection
TimeScopes = new List<TimeScope>(); // List of TimeScopes that apply to all child Obs in the collection
ContextItems = new List<ContextItem>();
ObsCollectionIds = new List<int>(); // Note: these are references to ObsCollections in Documents
ObsIds = new List<int>(); // Note: these are references to Obs in Documents
}
public CompoundIdentifier Id { get; private set; }
public int? OMSourceId { get; set; } // OMSource reduces child Obs to (mostly) key,value pair even with sensors, installation
public int? OMCodeId { get; set; } // OMCode reduces child Obs to (mostly) key,value pair when installation data is not needed
public List<int> CodeComponentIds { get; set; } // List of code components refs to allow parameters, semantic refinement
public List<TimeScope> TimeScopes { get; set; }
public int? GrowerId { get; set; } // Optional, provides ability to put an ObsCollection in the context of a grower
public int? PlaceId { get; set; } // Optional, provides ability to put an ObsCollection in the context of a Place
public Shape SpatialExtent { get; set; } // Optional, includes Point, Polyline, and Polygon features of interest
// Note: PlaceId provides a feature of interest by reference; SpatialExtent does so by value. They are not necessarily
// mutually exclusive.
public List<int> ObsCollectionIds { get; set; } // Recursive!
public List<int> ObsIds { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
|
epl-1.0
|
C#
|
3641856595498f22f4d4dfb00097c0c5e3d2101d
|
scale theme now relative to gameobject initial scale, like in other themes
|
killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
|
Assets/MixedRealityToolkit.SDK/Features/UX/Scripts/VisualThemes/ThemeEngines/InteractableScaleTheme.cs
|
Assets/MixedRealityToolkit.SDK/Features/UX/Scripts/VisualThemes/ThemeEngines/InteractableScaleTheme.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.UI
{
/// <summary>
/// Theme Engine to control initialized GameObject's scale based on state changes
/// </summary>
public class InteractableScaleTheme : InteractableThemeBase
{
protected Vector3 startScale;
private Transform hostTransform;
public InteractableScaleTheme()
{
Types = new Type[] { typeof(Transform) };
Name = "Scale Theme";
}
/// <inheritdoc />
public override ThemeDefinition GetDefaultThemeDefinition()
{
return new ThemeDefinition()
{
ThemeType = GetType(),
StateProperties = new List<ThemeStateProperty>()
{
new ThemeStateProperty()
{
Name = "Scale",
Type = ThemePropertyTypes.Vector3,
Values = new List<ThemePropertyValue>(),
Default = new ThemePropertyValue() { Vector3 = Vector3.one}
},
},
CustomProperties = new List<ThemeProperty>(),
};
}
/// <inheritdoc />
public override void Init(GameObject host, ThemeDefinition settings)
{
base.Init(host, settings);
hostTransform = Host.transform;
startScale = hostTransform.localScale;
}
/// <inheritdoc />
public override ThemePropertyValue GetProperty(ThemeStateProperty property)
{
ThemePropertyValue start = new ThemePropertyValue();
start.Vector3 = hostTransform.localScale;
return start;
}
/// <inheritdoc />
public override void SetValue(ThemeStateProperty property, int index, float percentage)
{
hostTransform.localScale = Vector3.Lerp(property.StartValue.Vector3, Vector3.Scale(startScale, property.Values[index].Vector3), percentage);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.UI
{
/// <summary>
/// Theme Engine to control initialized GameObject's scale based on state changes
/// </summary>
public class InteractableScaleTheme : InteractableThemeBase
{
private Transform hostTransform;
public InteractableScaleTheme()
{
Types = new Type[] { typeof(Transform) };
Name = "Scale Theme";
}
/// <inheritdoc />
public override ThemeDefinition GetDefaultThemeDefinition()
{
return new ThemeDefinition()
{
ThemeType = GetType(),
StateProperties = new List<ThemeStateProperty>()
{
new ThemeStateProperty()
{
Name = "Scale",
Type = ThemePropertyTypes.Vector3,
Values = new List<ThemePropertyValue>(),
Default = new ThemePropertyValue() { Vector3 = Vector3.one}
},
},
CustomProperties = new List<ThemeProperty>(),
};
}
/// <inheritdoc />
public override void Init(GameObject host, ThemeDefinition settings)
{
base.Init(host, settings);
hostTransform = Host.transform;
}
/// <inheritdoc />
public override ThemePropertyValue GetProperty(ThemeStateProperty property)
{
ThemePropertyValue start = new ThemePropertyValue();
start.Vector3 = hostTransform.localScale;
return start;
}
/// <inheritdoc />
public override void SetValue(ThemeStateProperty property, int index, float percentage)
{
hostTransform.localScale = Vector3.Lerp(property.StartValue.Vector3, property.Values[index].Vector3, percentage);
}
}
}
|
mit
|
C#
|
bc380e14f322678cf4deb6168eea23d8f3bc61d1
|
FIx typo
|
autofac/Autofac
|
src/Autofac/Builder/DeferredCallback.cs
|
src/Autofac/Builder/DeferredCallback.cs
|
using System;
using Autofac.Core.Registration;
namespace Autofac.Builder
{
/// <summary>
/// Reference object allowing location and update of a registration callback.
/// </summary>
public class DeferredCallback
{
// _callback set to default! to get around initialization detection problem in roslyn.
private Action<IComponentRegistryBuilder> _callback = default!;
/// <summary>
/// Initializes a new instance of the <see cref="DeferredCallback"/> class.
/// </summary>
/// <param name="callback">
/// An <see cref="Action{T}"/> that executes a registration action
/// against an <see cref="IComponentRegistryBuilder"/>.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown if <paramref name="callback" /> is <see langword="null" />.
/// </exception>
public DeferredCallback(Action<IComponentRegistryBuilder> callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
this.Id = Guid.NewGuid();
this.Callback = callback;
}
/// <summary>
/// Gets or sets the callback to execute during registration.
/// </summary>
/// <value>
/// An <see cref="Action{T}"/> that executes a registration action
/// against an <see cref="IComponentRegistryBuilder"/>.
/// </value>
/// <exception cref="System.ArgumentNullException">
/// Thrown if <paramref name="value" /> is <see langword="null" />.
/// </exception>
public Action<IComponentRegistryBuilder> Callback
{
get
{
return this._callback;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
this._callback = value;
}
}
/// <summary>
/// Gets the callback identifier.
/// </summary>
/// <value>
/// A <see cref="Guid"/> that uniquely identifies the callback action
/// in a set of callbacks.
/// </value>
public Guid Id { get; }
}
}
|
using System;
using Autofac.Core.Registration;
namespace Autofac.Builder
{
/// <summary>
/// Reference object allowing location and update of a registration callback.
/// </summary>
public class DeferredCallback
{
// _callback set to default! to get around initialisation detection problem in rosyln.
private Action<IComponentRegistryBuilder> _callback = default!;
/// <summary>
/// Initializes a new instance of the <see cref="DeferredCallback"/> class.
/// </summary>
/// <param name="callback">
/// An <see cref="Action{T}"/> that executes a registration action
/// against an <see cref="IComponentRegistryBuilder"/>.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown if <paramref name="callback" /> is <see langword="null" />.
/// </exception>
public DeferredCallback(Action<IComponentRegistryBuilder> callback)
{
if (callback == null)
{
throw new ArgumentNullException(nameof(callback));
}
this.Id = Guid.NewGuid();
this.Callback = callback;
}
/// <summary>
/// Gets or sets the callback to execute during registration.
/// </summary>
/// <value>
/// An <see cref="Action{T}"/> that executes a registration action
/// against an <see cref="IComponentRegistryBuilder"/>.
/// </value>
/// <exception cref="System.ArgumentNullException">
/// Thrown if <paramref name="value" /> is <see langword="null" />.
/// </exception>
public Action<IComponentRegistryBuilder> Callback
{
get
{
return this._callback;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
this._callback = value;
}
}
/// <summary>
/// Gets the callback identifier.
/// </summary>
/// <value>
/// A <see cref="Guid"/> that uniquely identifies the callback action
/// in a set of callbacks.
/// </value>
public Guid Id { get; }
}
}
|
mit
|
C#
|
b0bd80210dc67b067f41815ade33b01e7a020563
|
Build script now creates individual zip file packages to align with the NuGet packages and semantic versioning.
|
autofac/Autofac.Wcf,caioproiete/Autofac.Wcf
|
Properties/VersionAssemblyInfo.cs
|
Properties/VersionAssemblyInfo.cs
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-28 02:03")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-02-22 14:39")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
|
mit
|
C#
|
6792709db32313b71a1c849019db6201b720d06b
|
Fix test
|
mj1856/TimeZoneNames
|
TimeZoneNames.Tests/TimeZoneCountriesTests.cs
|
TimeZoneNames.Tests/TimeZoneCountriesTests.cs
|
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace TimeZoneNames.Tests
{
public class TimeZoneCountriesTests
{
[Fact]
public void Can_Get_Zones_For_US()
{
var zones = TimeZoneNames.GetTimeZoneIdsForCountry("US");
foreach (var zone in zones)
Debug.WriteLine(zone);
Assert.Equal(29, zones.Length);
Assert.True(zones.Contains("America/New_York"));
Assert.True(zones.Contains("America/Chicago"));
Assert.True(zones.Contains("America/Denver"));
Assert.True(zones.Contains("America/Los_Angeles"));
Assert.True(zones.Contains("America/Phoenix"));
Assert.True(zones.Contains("Pacific/Honolulu"));
Assert.True(!zones.Contains("Europe/London"));
}
[Fact]
public void Can_Get_Zones_For_GB()
{
var zones = TimeZoneNames.GetTimeZoneIdsForCountry("GB");
foreach (var zone in zones)
Debug.WriteLine(zone);
Assert.Equal(1, zones.Length);
Assert.Equal("Europe/London", zones[0]);
}
[Fact]
public void Can_Get_Zones_For_RU()
{
var zones = TimeZoneNames.GetTimeZoneIdsForCountry("RU");
foreach (var zone in zones)
Debug.WriteLine(zone);
Assert.Equal(21, zones.Length);
Assert.True(zones.Contains("Europe/Moscow"));
Assert.True(zones.Contains("Europe/Kaliningrad"));
Assert.True(zones.Contains("Asia/Vladivostok"));
Assert.True(zones.Contains("Asia/Kamchatka"));
Assert.True(!zones.Contains("Europe/London"));
}
}
}
|
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace TimeZoneNames.Tests
{
public class TimeZoneCountriesTests
{
[Fact]
public void Can_Get_Zones_For_US()
{
var zones = TimeZoneNames.GetTimeZoneIdsForCountry("US");
foreach (var zone in zones)
Debug.WriteLine(zone);
Assert.Equal(29, zones.Length);
Assert.True(zones.Contains("America/New_York"));
Assert.True(zones.Contains("America/Chicago"));
Assert.True(zones.Contains("America/Denver"));
Assert.True(zones.Contains("America/Los_Angeles"));
Assert.True(zones.Contains("America/Phoenix"));
Assert.True(zones.Contains("Pacific/Honolulu"));
Assert.True(!zones.Contains("Europe/London"));
}
[Fact]
public void Can_Get_Zones_For_GB()
{
var zones = TimeZoneNames.GetTimeZoneIdsForCountry("GB");
foreach (var zone in zones)
Debug.WriteLine(zone);
Assert.Equal(1, zones.Length);
Assert.Equal("Europe/London", zones[0]);
}
[Fact]
public void Can_Get_Zones_For_RU()
{
var zones = TimeZoneNames.GetTimeZoneIdsForCountry("RU");
foreach (var zone in zones)
Debug.WriteLine(zone);
Assert.Equal(19, zones.Length);
Assert.True(zones.Contains("Europe/Moscow"));
Assert.True(zones.Contains("Europe/Kaliningrad"));
Assert.True(zones.Contains("Asia/Vladivostok"));
Assert.True(zones.Contains("Asia/Kamchatka"));
Assert.True(!zones.Contains("Europe/London"));
}
}
}
|
mit
|
C#
|
8251b1b565f1e57ffc572040e953717ed7e66c63
|
change namespace of PropertyChangedCounter class.
|
cube-soft/Cube.Core,cube-soft/Cube.Core
|
Libraries/Tests/Sources/Helpers/PropertyChangedCounter.cs
|
Libraries/Tests/Sources/Helpers/PropertyChangedCounter.cs
|
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
namespace Cube.Tests;
using System.ComponentModel;
using System.Threading;
using Cube.Observable.Extensions;
/* ------------------------------------------------------------------------- */
///
/// PropertyChangedCounter
///
/// <summary>
/// Provides functionality to count the number of times PropertyChanged
/// events occur.
/// </summary>
///
/* ------------------------------------------------------------------------- */
public class PropertyChangedCounter : DisposableBase
{
#region Constructors
/* --------------------------------------------------------------------- */
///
/// PropertyChangedCounter
///
/// <summary>
/// Initializes a new instance of the PropertyChangedCounter class with
/// the specified arguments.
/// </summary>
///
/// <param name="src">Target objects.</param>
///
/* --------------------------------------------------------------------- */
public PropertyChangedCounter(params INotifyPropertyChanged[] src)
{
foreach (var e in src)
{
_disposable.Add(e.Subscribe(_ => Interlocked.Increment(ref _value)));
}
}
#endregion
#region Properties
/* --------------------------------------------------------------------- */
///
/// Value
///
/// <summary>
/// Gets the current number of times PropertyChanged events occur.
/// </summary>
///
/* --------------------------------------------------------------------- */
public int Value => _value;
#endregion
#region Methods
/* --------------------------------------------------------------------- */
///
/// Dispose
///
/// <summary>
/// Releases the unmanaged resources used by the object and
/// optionally releases the managed resources.
/// </summary>
///
/// <param name="disposing">
/// true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.
/// </param>
///
/* --------------------------------------------------------------------- */
protected override void Dispose(bool disposing)
{
Logger.Debug(Value.ToString());
_disposable.Dispose();
}
#endregion
#region Fields
private readonly DisposableContainer _disposable = new();
private int _value = 0;
#endregion
}
|
/* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
namespace Cube.Tests.Forms;
using System.ComponentModel;
using System.Threading;
using Cube.Observable.Extensions;
/* ------------------------------------------------------------------------- */
///
/// PropertyChangedCounter
///
/// <summary>
/// Provides functionality to count the number of times PropertyChanged
/// events occur.
/// </summary>
///
/* ------------------------------------------------------------------------- */
public class PropertyChangedCounter : DisposableBase
{
#region Constructors
/* --------------------------------------------------------------------- */
///
/// PropertyChangedCounter
///
/// <summary>
/// Initializes a new instance of the PropertyChangedCounter class with
/// the specified arguments.
/// </summary>
///
/// <param name="src">Target objects.</param>
///
/* --------------------------------------------------------------------- */
public PropertyChangedCounter(params INotifyPropertyChanged[] src)
{
foreach (var e in src)
{
_disposable.Add(e.Subscribe(_ => Interlocked.Increment(ref _value)));
}
}
#endregion
#region Properties
/* --------------------------------------------------------------------- */
///
/// Value
///
/// <summary>
/// Gets the current number of times PropertyChanged events occur.
/// </summary>
///
/* --------------------------------------------------------------------- */
public int Value => _value;
#endregion
#region Methods
/* --------------------------------------------------------------------- */
///
/// Dispose
///
/// <summary>
/// Releases the unmanaged resources used by the object and
/// optionally releases the managed resources.
/// </summary>
///
/// <param name="disposing">
/// true to release both managed and unmanaged resources;
/// false to release only unmanaged resources.
/// </param>
///
/* --------------------------------------------------------------------- */
protected override void Dispose(bool disposing)
{
Logger.Debug(Value.ToString());
_disposable.Dispose();
}
#endregion
#region Fields
private readonly DisposableContainer _disposable = new();
private int _value = 0;
#endregion
}
|
apache-2.0
|
C#
|
ef64dc27a1016c47d3d36809a266fe155d3cd528
|
Update ShaneONeill.cs
|
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
|
src/Firehose.Web/Authors/ShaneONeill.cs
|
src/Firehose.Web/Authors/ShaneONeill.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class ShaneONeill : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Shane";
public string LastName => "O'Neill";
public string ShortBioOrTagLine => "DBA. Food, Coffee, Whiskey (not necessarily in that order)... ";
public string StateOrRegion => "Ireland";
public string EmailAddress => string.Empty;
public string TwitterHandle => "SOZDBA";
public string GravatarHash => "0440d5d8f1b51b4765e3d48aec441510";
public string GitHubHandle => "shaneis";
public GeoPosition Position => new GeoPosition(53.2707, -9.0568);
public Uri WebSite => new Uri("https://nocolumnname.blog/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://nocolumnname.blog/feed/"); } }
public bool Filter(SyndicationItem item)
{
// This filters out only the posts that have the "PowerShell" category
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class ShaneONeill : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Shane";
public string LastName => "O'Neill";
public string ShortBioOrTagLine => "DBA. Food, Coffee, Whiskey (not necessarily in that order)... ";
public string StateOrRegion => "Ireland";
public string EmailAddress => string.Empty;
public string TwitterHandle => "SOZDBA";
public string GravatarHash => "0440d5d8f1b51b4765e3d48aec441510";
public string GitHubHandle => "shaneis";
public GeoPosition Position => new GeoPosition(53.2707, 9.0568);
public Uri WebSite => new Uri("https://nocolumnname.blog/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://nocolumnname.blog/feed/"); } }
public bool Filter(SyndicationItem item)
{
// This filters out only the posts that have the "PowerShell" category
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
}
}
|
mit
|
C#
|
eefd3a565fd5447c47fe147be4bebacca25db4f3
|
Add simple unit test.
|
tiesmaster/DCC,tiesmaster/DCC
|
Dcc.Test/DccMiddlewareTests.cs
|
Dcc.Test/DccMiddlewareTests.cs
|
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Tiesmaster.Dcc;
using Xunit;
namespace Dcc.Test
{
public class DccMiddlewareTests
{
[Fact]
public void CanCreate()
{
// arrange
var options = CreateOptions();
// act
var sut = new DccMiddleware(NoOpNext, options);
// assert
sut.Should().NotBeNull();
}
private static IOptions<DccOptions> CreateOptions() => Options.Create(new DccOptions {Host = "test"});
private Task NoOpNext(HttpContext context) => Task.CompletedTask;
}
}
|
using FluentAssertions;
using Tiesmaster.Dcc;
using Xunit;
namespace Dcc.Test
{
public class DccMiddlewareTests
{
[Fact]
public void SanityTest()
{
true.Should().BeTrue();
}
[Fact]
public void TEST_NAME()
{
// arrange
var sut = new DccMiddleware(null, null);
// act
// assert
}
}
}
|
mit
|
C#
|
216f0b971e47964bba9b8a99f5ab98c7901d96b1
|
increment patch version,
|
jwChung/Experimentalism,jwChung/Experimentalism
|
build/CommonAssemblyInfo.cs
|
build/CommonAssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.8.12")]
[assembly: AssemblyInformationalVersion("0.8.12")]
/*
* Version 0.8.12
*
* Rename some properties of FirstClassCommand to clarify
*
* BREAKING CHANGE
* FirstClassCommand class
* before:
* Method
* after:
* DeclaredMethod
*
* before:
* TestCase
* after:
* TestMethod
*/
|
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.8.11")]
[assembly: AssemblyInformationalVersion("0.8.11")]
/*
* Version 0.8.11
*
* Fix creating test commands of abstract base test class
* using the First-Class-Test manner.
*/
|
mit
|
C#
|
dd06a637a81a0d9889d7837d20becf66a8acdc5a
|
Fix HandleInput caching logic
|
Tom94/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,default0/osu-framework,Tom94/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,default0/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework
|
osu.Framework/Caching/HandleInputCache.cs
|
osu.Framework/Caching/HandleInputCache.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Concurrent;
using System.Reflection;
using osu.Framework.Graphics;
namespace osu.Framework.Caching
{
public class HandleInputCache
{
private readonly ConcurrentDictionary<Type, bool> cachedValues = new ConcurrentDictionary<Type, bool>();
private readonly string[] inputMethods = {
"OnHover",
"OnHoverLost",
"OnMouseDown",
"OnMouseUp",
"OnClick",
"OnDoubleClick",
"OnDragStart",
"OnDrag",
"OnDragEnd",
"OnWheel",
"OnFocus",
"OnFocusLost",
"OnKeyDown",
"OnKeyUp",
"OnMouseMove"
};
public bool Get(Type type)
{
if (!type.IsSubclassOf(typeof(Drawable)))
throw new ArgumentException();
var cached = cachedValues.TryGetValue(type, out var value);
if (!cached)
{
foreach (var inputMethod in inputMethods)
{
var isOverridden = type.GetMethod(inputMethod, BindingFlags.Instance | BindingFlags.NonPublic).DeclaringType != typeof(Drawable);
if (isOverridden)
{
cachedValues.TryAdd(type, true);
return true;
}
}
cachedValues.TryAdd(type, value = false);
}
return value;
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Concurrent;
using System.Reflection;
using osu.Framework.Graphics;
namespace osu.Framework.Caching
{
public class HandleInputCache
{
private readonly ConcurrentDictionary<Type, bool> cachedValues = new ConcurrentDictionary<Type, bool>();
private readonly string[] inputMethods = {
"OnHover",
"OnHoverLost",
"OnMouseDown",
"OnMouseUp",
"OnClick",
"OnDoubleClick",
"OnDragStart",
"OnDrag",
"OnDragEnd",
"OnWheel",
"OnFocus",
"OnFocusLost",
"OnKeyDown",
"OnKeyUp",
"OnMouseMove"
};
public bool Get(Type type)
{
if (!type.IsSubclassOf(typeof(Drawable)))
throw new ArgumentException();
var cached = cachedValues.TryGetValue(type, out var value);
if (!cached)
{
foreach (var inputMethod in inputMethods)
{
var isOverridden = type.GetMethod(inputMethod, BindingFlags.Instance | BindingFlags.NonPublic).DeclaringType != typeof(Drawable);
if (isOverridden)
{
cachedValues.TryAdd(type, value = true);
break;
}
}
}
return value;
}
}
}
|
mit
|
C#
|
f530574b89bd30e0f897de4a73c49bff5a314be2
|
Fix typo
|
paiden/Nett
|
Test/Nett.UnitTests/Functional/ParserErrorMessageTests.cs
|
Test/Nett.UnitTests/Functional/ParserErrorMessageTests.cs
|
using System;
using FluentAssertions;
using Xunit;
namespace Nett.UnitTests.Functional
{
public sealed class ParserErrorMessageTests
{
private const string KeyMissingError = "*Key is missing.";
private const string ValueMissingError = "*Value is missing.";
private const string StringNotClosedError = "*String not closed.";
public static TheoryData<string, string, int, int> InputData =
new TheoryData<string, string, int, int>
{
{ "1.0", "*Failed to parse key because unexpected token '1.0' was found.", 1, 1 },
{ "X = ", ValueMissingError, 1, 5 },
{ "X = \r\n", ValueMissingError, 1, 5 },
{ "X = \r", ValueMissingError, 1, 6 }, // \r is a omitted char, and after that EOF will cause error => 5 + 1
{ "X = \n", ValueMissingError, 1, 5 },
{ "X = \r\n 2.0", ValueMissingError, 1, 5 },
{ "=1", KeyMissingError, 1, 1 },
{ "=", KeyMissingError, 1, 1 },
{ "X = \"Hello", StringNotClosedError, 1, 5 }, // string errors use string start pos as error indicator position
{ "X = 'Hello", StringNotClosedError, 1, 5 },
{ "X = '''Hello \r\n\r\n", StringNotClosedError, 1, 5 },
{ "X = \"\"\"Hello \r\n\r\n", StringNotClosedError, 1, 5 },
};
[Theory(DisplayName = "ErrMsg has correct pos")]
[MemberData(nameof(InputData))]
public static void Parser_WhenInputIsInvalid_GeneratesErrorMessageWithLineAndColumn(string toml, string _, int line, int column)
{
// Act
Action a = () => Toml.ReadString(toml);
// Assert
a.ShouldThrow<Exception>().WithMessage($"Line {line}, Column {column}:*");
}
[Theory(DisplayName = "Useful ErrMsg")]
[MemberData(nameof(InputData))]
public static void Parser_WhenInputIsInvalid_GeneratesSomewhatUsefulErrorMessage(string toml, string error, int _, int __)
{
// Act
Action a = () => Toml.ReadString(toml);
// Assert
a.ShouldThrow<Exception>().WithMessage($"*{error}*");
}
}
}
|
using System;
using FluentAssertions;
using Xunit;
namespace Nett.UnitTests.Functional
{
public sealed class ParserErrorMessageTests
{
private const string KeyMissingError = "*Key is missing.";
private const string ValueMissingError = "*Value is missing.";
private const string StringNotClosedError = "*String not closed.";
public static TheoryData<string, string, int, int> InputData =
new TheoryData<string, string, int, int>
{
{ "1.0", "*Failed to parse key because unexpected token '1.0' was found.", 1, 1 },
{ "X = ", ValueMissingError, 1, 5 },
{ "X = \r\n", ValueMissingError, 1, 5 },
{ "X = \r", ValueMissingError, 1, 6 }, // \r is a ommited char, and after that EOF will cause error => 5 + 1
{ "X = \n", ValueMissingError, 1, 5 },
{ "X = \r\n 2.0", ValueMissingError, 1, 5 },
{ "=1", KeyMissingError, 1, 1 },
{ "=", KeyMissingError, 1, 1 },
{ "X = \"Hello", StringNotClosedError, 1, 5 }, // string errors use string start pos as error indicator position
{ "X = 'Hello", StringNotClosedError, 1, 5 },
{ "X = '''Hello \r\n\r\n", StringNotClosedError, 1, 5 },
{ "X = \"\"\"Hello \r\n\r\n", StringNotClosedError, 1, 5 },
};
[Theory(DisplayName = "ErrMsg has correct pos")]
[MemberData(nameof(InputData))]
public static void Parser_WhenInputIsInvalid_GeneratesErrorMessageWithLineAndColumn(string toml, string _, int line, int column)
{
// Act
Action a = () => Toml.ReadString(toml);
// Assert
a.ShouldThrow<Exception>().WithMessage($"Line {line}, Column {column}:*");
}
[Theory(DisplayName = "Useful ErrMsg")]
[MemberData(nameof(InputData))]
public static void Parser_WhenInputIsInvalid_GeneratesSomewhatUsefulErrorMessage(string toml, string error, int _, int __)
{
// Act
Action a = () => Toml.ReadString(toml);
// Assert
a.ShouldThrow<Exception>().WithMessage($"*{error}*");
}
}
}
|
mit
|
C#
|
899ceef6fb59ca31830aa256381412ca751d3cf6
|
update password reset css
|
agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov
|
WebAPI.Dashboard/Views/AccountAccess/PasswordReset.cshtml
|
WebAPI.Dashboard/Views/AccountAccess/PasswordReset.cshtml
|
@model WebAPI.Dashboard.Models.ViewModels.MainViewModel
@{
ViewBag.Title = "Password Reset";
}
<div id="home">
<div class="pull-right">
@Html.ActionLink("Log Out", "Logout")
</div>
</div>
<div class="col-sm-offset-3 col-sm-6">
@Html.ErrorBox()
@Html.MessageBox()
</div>
@using (Html.BeginForm("Reset", "AccountAccess", FormMethod.Post, new
{
@class = "form-horizontal", style = "padding-top:50px;"
}))
{
<div class="col-sm-offset-3 well col-sm-6">
<h2>
Reset your password
</h2>
<div class="form-group">
<label class="col-sm-3 control-label" for="email">
Email Address:
</label>
<div class="col-sm-6">
<div class="input-group">
@Html.TextBox("Email", Model.User.Email,
new
{
required = "true",
type = "email",
@class = "form-control"
})
<div class="input-group-btn">
@Html.Button("Reset", new
{
@class = "btn btn-primary"
})
</div>
</div>
</div>
</div>
</div>
}
|
@model WebAPI.Dashboard.Models.ViewModels.MainViewModel
@{
ViewBag.Title = "Password Reset";
}
<div id="home">
<div class="pull-right">
@Html.ActionLink("Log Out", "Logout")
</div>
</div>
<div class="col-sm-offset-3 col-sm-6">
@Html.ErrorBox()
@Html.MessageBox()
</div>
@using (Html.BeginForm("Reset", "AccountAccess", FormMethod.Post, new
{
@class = "form-horizontal", style = "padding-top:50px;"
}))
{
<div class="offset3 well span6">
<h2>
Reset your password
</h2>
<div class="form-group">
<label class="control-label" for="urlpattern">
Email Address:
</label>
<div class="col-sm-9">
<div class="input-group">
@Html.TextBox("Email", Model.User.Email,
new
{
required = "true",
@class = "input-large"
})@Html.Button("Reset", new
{
@class = "btn btn-danger"
})
</div>
</div>
</div>
</div>
}
|
mit
|
C#
|
548ba43acf5f934a5fe95d227d11a0fc392ed338
|
Change the claim so that the id of the user is stored
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EmployerApprenticeshipsService.Web/Authentication/OwinWrapper.cs
|
src/SFA.DAS.EmployerApprenticeshipsService.Web/Authentication/OwinWrapper.cs
|
using System.Collections.Generic;
using System.Security.Claims;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core.Models;
using Microsoft.Owin;
namespace SFA.DAS.EmployerApprenticeshipsService.Web.Authentication
{
public class OwinWrapper : IOwinWrapper
{
private readonly IOwinContext _owinContext;
public OwinWrapper(IOwinContext owinContext)
{
_owinContext = owinContext;
}
public void SignInUser(string id, string displayName, string email)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, displayName),
new Claim(ClaimTypes.Email, email),
new Claim("sub", id)
};
var claimsIdentity = new ClaimsIdentity(claims,"Cookies");
var authenticationManager = _owinContext.Authentication;
authenticationManager.SignIn(claimsIdentity);
_owinContext.Authentication.User = new ClaimsPrincipal(claimsIdentity);
}
public void SignOutUser()
{
var authenticationManager = _owinContext.Authentication;
authenticationManager.SignOut("Cookies");
}
public SignInMessage GetSignInMessage(string id)
{
return _owinContext.Environment.GetSignInMessage(id);
}
public void IssueLoginCookie(string id, string displayName)
{
//var env = _owinContext.Environment;
//env.IssueLoginCookie(new AuthenticatedLogin
//{
// Subject = id,
// Name = displayName
//});
}
public void RemovePartialLoginCookie()
{
//_owinContext.Environment.RemovePartialLoginCookie();
}
}
}
|
using System.Collections.Generic;
using System.Security.Claims;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core.Models;
using Microsoft.Owin;
namespace SFA.DAS.EmployerApprenticeshipsService.Web.Authentication
{
public class OwinWrapper : IOwinWrapper
{
private readonly IOwinContext _owinContext;
public OwinWrapper(IOwinContext owinContext)
{
_owinContext = owinContext;
}
public void SignInUser(string id, string displayName, string email)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, displayName),
new Claim(ClaimTypes.Email, email),
new Claim("sub", email)
};
var claimsIdentity = new ClaimsIdentity(claims,"Cookies");
var authenticationManager = _owinContext.Authentication;
authenticationManager.SignIn(claimsIdentity);
_owinContext.Authentication.User = new ClaimsPrincipal(claimsIdentity);
}
public void SignOutUser()
{
var authenticationManager = _owinContext.Authentication;
authenticationManager.SignOut("Cookies");
}
public SignInMessage GetSignInMessage(string id)
{
return _owinContext.Environment.GetSignInMessage(id);
}
public void IssueLoginCookie(string id, string displayName)
{
//var env = _owinContext.Environment;
//env.IssueLoginCookie(new AuthenticatedLogin
//{
// Subject = id,
// Name = displayName
//});
}
public void RemovePartialLoginCookie()
{
//_owinContext.Environment.RemovePartialLoginCookie();
}
}
}
|
mit
|
C#
|
3daace53738dfb290eb31ce68b7e05428bab31ce
|
test parser
|
wowhy/wowhy,wowhy/wowhy,wowhy/wowhy
|
All/SampleParser/Program.cs
|
All/SampleParser/Program.cs
|
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using HyLibrary.Parser.Expr;
using HyLibrary.ExtensionMethod;
namespace SampleParser
{
public class Test
{
public int Id { get; set; }
public Test() { }
public Test(int id) { this.Id = id; }
public override string ToString()
{
return string.Format("{{ Id:{0} }}", this.Id);
}
}
public class Program
{
static void Main(string[] argv)
{
ExprParser.Using.Add("SampleParser");
var parser = new ExprParser();
var exp = parser.Parse<Func<Test, bool>>(
@"(Test k) =>
{
return k.Id > 1;
}");
Console.WriteLine(exp.ToString());
var list = new List<Test>()
{
new Test { Id = 1 },
new Test { Id = 2 },
new Test { Id = 3 },
new Test { Id = 4 },
};
var result = list.Where(exp.Compile()).Select(k => k.Id.ToString()).Join(',');
Console.WriteLine(result);
var exp2 = parser.Parse<Func<int, Test>>(@"(int id)=> new Test(id)");
Console.WriteLine(exp2.ToString());
Console.WriteLine(exp2.Compile()(10));
}
}
}
|
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using HyLibrary.Parser.Expr;
using HyLibrary.ExtensionMethod;
namespace SampleParser
{
public class Test
{
public int Id { get; set; }
}
public class Program
{
static void Main(string[] argv)
{
ExprParser.Using.Add("SampleParser");
var parser = new ExprParser();
var exp = parser.Parse<Func<Test, bool>>(
@"(Test k) =>
{
return k.Id > 1;
}");
Console.WriteLine(exp.ToString());
var list = new List<Test>()
{
new Test { Id = 1 },
new Test { Id = 2 },
new Test { Id = 3 },
new Test { Id = 4 },
};
var result = list.Where(exp.Compile()).Select(k => k.Id.ToString()).Join(',');
Console.WriteLine(result);
}
}
}
|
apache-2.0
|
C#
|
d7e35063a3ce1699b8126834fc3978be123b0687
|
Add option to change protocol version
|
dialogflow/dialogflow-dotnet-client,dialogflow/dialogflow-dotnet-client,api-ai/api-ai-net,api-ai/api-ai-net,IntranetFactory/api-ai-net
|
ApiAiSDK/AIConfiguration.cs
|
ApiAiSDK/AIConfiguration.cs
|
//
// API.AI .NET SDK - client-side libraries for API.AI
// =================================================
//
// Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
// https://www.api.ai
//
// ***********************************************************************************************************************
//
// 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.Collections;
using ApiAiSDK.Model;
using System;
namespace ApiAiSDK
{
public class AIConfiguration
{
private const string SERVICE_PROD_URL = "https://api.api.ai/v1/";
private const string SERVICE_DEV_URL = "https://dev.api.ai/api/";
private const string CURRENT_PROTOCOL_VERSION = "20150204";
public string SubscriptionKey { get; private set; }
public string ClientAccessToken { get; private set; }
public SupportedLanguage Language { get; set; }
public bool VoiceActivityDetectionEnabled { get; set; }
/// <summary>
/// If true, will be used Testing API.AI server instead of Production server. This option for TESTING PURPOSES ONLY.
/// </summary>
public bool DevMode { get; set; }
/// <summary>
/// If true, all request and response content will be printed to the console. Use this option only FOR DEVELOPMENT.
/// </summary>
public bool DebugLog { get; set; }
string protocolVersion;
public string ProtocolVersion
{
get
{
return protocolVersion;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
protocolVersion = value;
}
}
public AIConfiguration(string subscriptionKey, string clientAccessToken, SupportedLanguage language)
{
this.SubscriptionKey = subscriptionKey;
this.ClientAccessToken = clientAccessToken;
this.Language = language;
DevMode = false;
DebugLog = false;
VoiceActivityDetectionEnabled = true;
ProtocolVersion = CURRENT_PROTOCOL_VERSION;
}
public string RequestUrl {
get {
var baseUrl = DevMode ? SERVICE_DEV_URL : SERVICE_PROD_URL;
return string.Format("{0}{1}?v={2}", baseUrl, "query", ProtocolVersion);
}
}
}
}
|
//
// API.AI .NET SDK - client-side libraries for API.AI
// =================================================
//
// Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
// https://www.api.ai
//
// ***********************************************************************************************************************
//
// 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.Collections;
using ApiAiSDK.Model;
namespace ApiAiSDK
{
public class AIConfiguration
{
private const string SERVICE_PROD_URL = "https://api.api.ai/v1/";
private const string SERVICE_DEV_URL = "https://dev.api.ai/api/";
private const string CURRENT_PROTOCOL_VERSION = "20150204";
public string SubscriptionKey { get; private set; }
public string ClientAccessToken { get; private set; }
public SupportedLanguage Language { get; set; }
public bool VoiceActivityDetectionEnabled { get; set; }
/// <summary>
/// If true, will be used Testing API.AI server instead of Production server. This option for TESTING PURPOSES ONLY.
/// </summary>
public bool DevMode { get; set; }
/// <summary>
/// If true, all request and response content will be printed to the console. Use this option only FOR DEVELOPMENT.
/// </summary>
public bool DebugLog { get; set; }
/// <summary>
/// If true ILGenerator will not be used while json serialization and deserialization. Use this on platforms with denied code generation, like iOS.
/// Generally you should not change this option.
/// </summary>
public bool JsonProcessingWithoutDynamicCode { get; set; }
public AIConfiguration(string subscriptionKey, string clientAccessToken, SupportedLanguage language)
{
this.SubscriptionKey = subscriptionKey;
this.ClientAccessToken = clientAccessToken;
this.Language = language;
DevMode = false;
DebugLog = false;
VoiceActivityDetectionEnabled = true;
}
public string RequestUrl {
get {
var baseUrl = DevMode ? SERVICE_DEV_URL : SERVICE_PROD_URL;
return string.Format("{0}{1}?v={2}", baseUrl, "query", CURRENT_PROTOCOL_VERSION);
}
}
}
}
|
apache-2.0
|
C#
|
d90aa41b22d73a1b84491b82185033405e2cb71b
|
Update Singleton.cs
|
Glauz/Unity3D-CharacterCustomizationTutorial
|
Assets/Scripts/Singleton.cs
|
Assets/Scripts/Singleton.cs
|
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public void Awake()
{
if (instance == null)
{
instance = GetComponent<T>();
}
else
Destroy(this.gameObject);
}
public static T Instance
{
get
{
if (instance == null)
print("Instance of GameObject does not exist!");
return instance;
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
namespace Glauz
{
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
instance = new GameObject().AddComponent<T>();
return instance;
}
}
public void Awake()
{
if (instance != null)
{
Debug.Log("Other Instance of " + this.GetType().Name + " has been destroyed on GameObject " + name + "!");
}
instance = this as T;
}
}
}
|
mit
|
C#
|
44cb41891cbbaf3184d8546af3731e03883eae30
|
Update Developer-Banner.cs
|
DeanCabral/Code-Snippets
|
Console/Developer-Banner.cs
|
Console/Developer-Banner.cs
|
class DeveloperBanner
{
static string assignmentTitle, developerName, dateSubmitted, generalPurpose;
static int bannerLength = 50;
static void Main(string[] args)
{
GetUserInput();
}
static void GetUserInput()
{
Console.Write("Input Assignment Title: ");
assignmentTitle = Console.ReadLine();
Console.Write("Input Developer Name: ");
developerName = Console.ReadLine();
Console.Write("Input Submission Date: ");
dateSubmitted = Console.ReadLine();
Console.Write("Input General Purpose: ");
generalPurpose = Console.ReadLine();
Console.WriteLine();
GenerateOutputBanner();
}
static void GenerateOutputBanner()
{
Console.WriteLine(DrawLine());
Console.WriteLine(BannerBody(assignmentTitle));
Console.WriteLine(BannerBody(developerName));
Console.WriteLine(BannerBody(dateSubmitted));
Console.WriteLine(BannerBody(generalPurpose));
Console.WriteLine(DrawLine());
Console.ReadLine();
}
static string BannerBody(string information)
{
string output = "";
int count = (bannerLength - 10) - information.Length;
output = "** " + information + DrawWhiteSpace(count) + "**";
return output;
}
static string DrawLine()
{
string output = "";
for (int i = 0; i < bannerLength; i++)
{
output += "*";
}
return output;
}
static string DrawWhiteSpace(int count)
{
string output = "";
for (int i = 0; i < count; i++)
{
output += " ";
}
return output;
}
}
|
class DeveloperBanner
{
static string assignmentTitle, developerName, dateSubmitted, generalPurpose;
static int bannerLength = 50;
static void Main(string[] args)
{
GetUserInput();
}
static void GetUserInput()
{
Console.Write("Input Assignment Title: ");
assignmentTitle = Console.ReadLine();
Console.Write("Input Developer Name: ");
developerName = Console.ReadLine();
Console.Write("Input Submission Date: ");
dateSubmitted = Console.ReadLine();
Console.Write("Input General Purpose: ");
generalPurpose = Console.ReadLine();
Console.WriteLine();
GenerateOutputBanner();
}
static void GenerateOutputBanner()
{
Console.WriteLine(DrawLine());
Console.WriteLine(BannerBody(assignmentTitle));
Console.WriteLine(BannerBody(developerName));
Console.WriteLine(BannerBody(dateSubmitted));
Console.WriteLine(BannerBody(detailPurpose));
Console.WriteLine(DrawLine());
Console.ReadLine();
}
static string BannerBody(string information)
{
string output = "";
int count = (bannerLength - 10) - information.Length;
output = "** " + information + DrawWhiteSpace(count) + "**";
return output;
}
static string DrawLine()
{
string output = "";
for (int i = 0; i < bannerLength; i++)
{
output += "*";
}
return output;
}
static string DrawWhiteSpace(int count)
{
string output = "";
for (int i = 0; i < count; i++)
{
output += " ";
}
return output;
}
}
|
mit
|
C#
|
a893be597f320608c253569d2c3bf572b5bc5944
|
Remove not needed tower transform
|
emazzotta/unity-tower-defense
|
Assets/Scripts/Tower.cs
|
Assets/Scripts/Tower.cs
|
using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour {
public float range = 10f;
public GameObject bulletPrefab;
public int cost = 5;
public int damage = 10;
public float radius = 0;
private MetallKefer nearestMetallKefer;
void Start () {
InvokeRepeating("AimAtTarget", 0, 0.5f);
this.nearestMetallKefer = null;
}
void AimAtTarget() {
MetallKefer[] enemies = GameObject.FindObjectsOfType<MetallKefer>();
this.nearestMetallKefer = GetClosestEnemy(enemies);
if(nearestMetallKefer != null) {
if (nearestMetallKefer != null && nearestMetallKefer.GetHealth () > 0) {
ShootAt (nearestMetallKefer);
}
Vector3 lookRotation = nearestMetallKefer.transform.position - this.transform.position;
if (lookRotation != Vector3.zero) {
var targetRotation = Quaternion.LookRotation(lookRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime);
}
}
}
void ShootAt(MetallKefer metallKefer) {
GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, this.transform.position, this.transform.rotation);
bulletGO.transform.SetParent (this.transform);
Bullet b = bulletGO.GetComponent<Bullet>();
b.target = metallKefer;
b.damage = damage;
}
MetallKefer GetClosestEnemy(MetallKefer[] enemies) {
MetallKefer tMin = null;
float minDist = Mathf.Infinity;
Vector3 currentPos = transform.position;
foreach (MetallKefer enemy in enemies) {
float dist = Vector3.Distance(enemy.transform.position, currentPos);
if (dist < minDist) {
tMin = enemy;
minDist = dist;
}
}
return tMin;
}
}
|
using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour {
public float range = 10f;
public GameObject bulletPrefab;
public int cost = 5;
public int damage = 10;
public float radius = 0;
private MetallKefer nearestMetallKefer;
void Start () {
InvokeRepeating("AimAtTarget", 0, 0.5f);
this.nearestMetallKefer = null;
towerTransform = transform.Find("Tower");
}
void AimAtTarget() {
MetallKefer[] enemies = GameObject.FindObjectsOfType<MetallKefer>();
this.nearestMetallKefer = GetClosestEnemy(enemies);
if(nearestMetallKefer != null) {
if (nearestMetallKefer != null && nearestMetallKefer.GetHealth () > 0) {
ShootAt (nearestMetallKefer);
}
Vector3 lookRotation = nearestMetallKefer.transform.position - this.transform.position;
if (lookRotation != Vector3.zero) {
var targetRotation = Quaternion.LookRotation(lookRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime);
}
}
}
void ShootAt(MetallKefer metallKefer) {
GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, this.transform.position, this.transform.rotation);
bulletGO.transform.SetParent (this.transform);
Bullet b = bulletGO.GetComponent<Bullet>();
b.target = metallKefer;
b.damage = damage;
}
MetallKefer GetClosestEnemy(MetallKefer[] enemies) {
MetallKefer tMin = null;
float minDist = Mathf.Infinity;
Vector3 currentPos = transform.position;
foreach (MetallKefer enemy in enemies) {
float dist = Vector3.Distance(enemy.transform.position, currentPos);
if (dist < minDist) {
tMin = enemy;
minDist = dist;
}
}
return tMin;
}
}
|
mit
|
C#
|
a00c763ce424308133a61843b5be5e7b05964a8d
|
Set JSON as the default (and only) formatter
|
cloudfoundry-incubator/wats,cloudfoundry/wats,cloudfoundry-incubator/wats,cloudfoundry/wats,cloudfoundry-incubator/wats,cloudfoundry/wats,cloudfoundry/wats,cloudfoundry-incubator/wats,cloudfoundry/wats,cloudfoundry-incubator/wats
|
Nora/App_Start/WebApiConfig.cs
|
Nora/App_Start/WebApiConfig.cs
|
using System.Web.Http;
namespace Nora
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});
// Remove XML formatter
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
}
|
using System.Web.Http;
namespace Nora
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional});
}
}
}
|
apache-2.0
|
C#
|
88cd1594d2dbeeeaf7a2dadb1bccc52a9f02357a
|
Mark redundant methods in IDiffer as obsolete
|
mmanela/diffplex,mmanela/diffplex,mmanela/diffplex,mmanela/diffplex
|
DiffPlex/IDiffer.cs
|
DiffPlex/IDiffer.cs
|
using System;
using DiffPlex.Model;
namespace DiffPlex
{
/// <summary>
/// Responsible for generating differences between texts
/// </summary>
public interface IDiffer
{
[Obsolete("Use CreateDiffs method instead", false)]
DiffResult CreateLineDiffs(string oldText, string newText, bool ignoreWhitespace);
[Obsolete("Use CreateDiffs method instead", false)]
DiffResult CreateLineDiffs(string oldText, string newText, bool ignoreWhitespace, bool ignoreCase);
[Obsolete("Use CreateDiffs method instead", false)]
DiffResult CreateCharacterDiffs(string oldText, string newText, bool ignoreWhitespace);
[Obsolete("Use CreateDiffs method instead", false)]
DiffResult CreateCharacterDiffs(string oldText, string newText, bool ignoreWhitespace, bool ignoreCase);
[Obsolete("Use CreateDiffs method instead", false)]
DiffResult CreateWordDiffs(string oldText, string newText, bool ignoreWhitespace, char[] separators);
[Obsolete("Use CreateDiffs method instead", false)]
DiffResult CreateWordDiffs(string oldText, string newText, bool ignoreWhitespace, bool ignoreCase, char[] separators);
[Obsolete("Use CreateDiffs method instead", false)]
DiffResult CreateCustomDiffs(string oldText, string newText, bool ignoreWhiteSpace, Func<string, string[]> chunker);
[Obsolete("Use CreateDiffs method instead", false)]
DiffResult CreateCustomDiffs(string oldText, string newText, bool ignoreWhiteSpace, bool ignoreCase, Func<string, string[]> chunker);
/// <summary>
/// Create a diff by comparing text line by line
/// </summary>
/// <param name="oldText">The old text.</param>
/// <param name="newText">The new text.</param>
/// <param name="ignoreWhiteSpace">if set to <c>true</c> will ignore white space when determining if lines are the same.</param>
/// <param name="ignoreCase">Determine if the text comparision is case sensitive or not</param>
/// <param name="chunker">Component responsible for tokenizing the compared texts</param>
/// <returns>A DiffResult object which details the differences</returns>
DiffResult CreateDiffs(string oldText, string newText, bool ignoreWhiteSpace, bool ignoreCase, IChunker chunker);
}
}
|
using System;
using DiffPlex.Model;
namespace DiffPlex
{
/// <summary>
/// Responsible for generating differences between texts
/// </summary>
public interface IDiffer
{
DiffResult CreateLineDiffs(string oldText, string newText, bool ignoreWhitespace);
DiffResult CreateLineDiffs(string oldText, string newText, bool ignoreWhitespace, bool ignoreCase);
DiffResult CreateCharacterDiffs(string oldText, string newText, bool ignoreWhitespace);
DiffResult CreateCharacterDiffs(string oldText, string newText, bool ignoreWhitespace, bool ignoreCase);
DiffResult CreateWordDiffs(string oldText, string newText, bool ignoreWhitespace, char[] separators);
DiffResult CreateWordDiffs(string oldText, string newText, bool ignoreWhitespace, bool ignoreCase, char[] separators);
DiffResult CreateCustomDiffs(string oldText, string newText, bool ignoreWhiteSpace, Func<string, string[]> chunker);
DiffResult CreateCustomDiffs(string oldText, string newText, bool ignoreWhiteSpace, bool ignoreCase, Func<string, string[]> chunker);
/// <summary>
/// Create a diff by comparing text line by line
/// </summary>
/// <param name="oldText">The old text.</param>
/// <param name="newText">The new text.</param>
/// <param name="ignoreWhiteSpace">if set to <c>true</c> will ignore white space when determining if lines are the same.</param>
/// <param name="ignoreCase">Determine if the text comparision is case sensitive or not</param>
/// <param name="chunker">Component responsible for tokenizing the compared texts</param>
/// <returns>A DiffResult object which details the differences</returns>
DiffResult CreateDiffs(string oldText, string newText, bool ignoreWhiteSpace, bool ignoreCase, IChunker chunker);
}
}
|
apache-2.0
|
C#
|
af8c9d0b359d89c57d71a22409e4121b1154eb36
|
Improve base test
|
sickboy/JConverter
|
src/JConverter.Tests/BaseTest.cs
|
src/JConverter.Tests/BaseTest.cs
|
using NUnit.Framework;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoFakeItEasy;
namespace JConverter.Tests
{
[TestFixture]
public abstract class BaseTest
{
protected Fixture Fixture { get; } = new Fixture();
protected BaseTest()
{
Fixture.Customize(new AutoFakeItEasyCustomization());
}
}
public abstract class BaseTest<T> : BaseTest
{
// ReSharper disable once InconsistentNaming
public T SUT { get; set; }
protected virtual void BuildFixture() => SUT = Fixture.Create<T>();
}
}
|
using NUnit.Framework;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoFakeItEasy;
namespace JConverter.Tests
{
[TestFixture]
public abstract class BaseTest
{
protected Fixture Fixturer { get; } = new Fixture();
protected BaseTest()
{
Fixturer.Customize(new AutoFakeItEasyCustomization());
}
}
}
|
mit
|
C#
|
71f5386875aa82b82faa1b780b9a465f3e3bf743
|
Fix Selenium4 support
|
ObjectivityLtd/Test.Automation
|
Ocaramba.Tests.Xunit/Tests/ExampleTest2.cs
|
Ocaramba.Tests.Xunit/Tests/ExampleTest2.cs
|
// <copyright file="ExampleTest2.cs" company="Objectivity Bespoke Software Specialists">
// Copyright (c) Objectivity Bespoke Software Specialists. All rights reserved.
// </copyright>
// <license>
// The MIT License (MIT)
// 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.
// </license>
namespace Ocaramba.Tests.Xunit.Tests
{
using global::Xunit;
using Ocaramba.Tests.PageObjects.PageObjects.TheInternet;
public class ExampleTest2 : ProjectTestBase
{
[Fact]
public void NestedFramesTest()
{
var nestedFramesPage = new InternetPage(this.DriverContext)
.OpenHomePage()
.GoToNestedFramesPage()
.SwitchToFrame("frame-top");
nestedFramesPage.SwitchToFrame("frame-left");
Assert.Equal("LEFT", nestedFramesPage.LeftBody);
nestedFramesPage.SwitchToParentFrame().SwitchToFrame("frame-middle");
Assert.Equal("MIDDLE", nestedFramesPage.MiddleBody);
nestedFramesPage.SwitchToParentFrame().SwitchToFrame("frame-right");
Assert.Equal("RIGHT", nestedFramesPage.RightBody);
nestedFramesPage.ReturnToDefaultContent().SwitchToFrame("frame-bottom");
Assert.Equal("BOTTOM", nestedFramesPage.BottomBody);
}
}
}
|
// <copyright file="ExampleTest2.cs" company="Objectivity Bespoke Software Specialists">
// Copyright (c) Objectivity Bespoke Software Specialists. All rights reserved.
// </copyright>
// <license>
// The MIT License (MIT)
// 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.
// </license>
namespace Ocaramba.Tests.Xunit.Tests
{
using global::Xunit;
using Ocaramba.Tests.PageObjects.PageObjects.Kendo;
using Ocaramba.Tests.PageObjects.PageObjects.TheInternet;
public class ExampleTest2 : ProjectTestBase
{
[Fact]
public void NestedFramesTest()
{
var nestedFramesPage = new InternetPage(this.DriverContext)
.OpenHomePage()
.GoToNestedFramesPage()
.SwitchToFrame("frame-top");
nestedFramesPage.SwitchToFrame("frame-left");
Assert.Equal("LEFT", nestedFramesPage.LeftBody);
nestedFramesPage.SwitchToParentFrame().SwitchToFrame("frame-middle");
Assert.Equal("MIDDLE", nestedFramesPage.MiddleBody);
nestedFramesPage.SwitchToParentFrame().SwitchToFrame("frame-right");
Assert.Equal("RIGHT", nestedFramesPage.RightBody);
nestedFramesPage.ReturnToDefaultContent().SwitchToFrame("frame-bottom");
Assert.Equal("BOTTOM", nestedFramesPage.BottomBody);
}
[Fact]
public void KendoOpenCloseComboboxTest()
{
var homePage = new KendoComboBoxPage(this.DriverContext);
homePage.Open();
homePage.OpenFabricComboBox();
Assert.True(homePage.IsFabricComboBoxExpanded());
homePage.CloseFabricComboBox();
Assert.False(homePage.IsFabricComboBoxExpanded());
}
}
}
|
mit
|
C#
|
a4d25b138641fef9c85bc38924c8dd81a00d01e4
|
Change name
|
Verrickt/BsodSimulator
|
BsodSimulator/ViewModel/ViewModelBase.cs
|
BsodSimulator/ViewModel/ViewModelBase.cs
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace BsodSimulator.ViewModel
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName]string propertyName=null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected void SetProperty<T>(ref T property,T value, [CallerMemberName]string propertyName = null,Action callback=null)
{
if (!EqualityComparer<T>.Default.Equals(property,value))
{
property = value;
OnPropertyChanged(propertyName);
callback?.Invoke();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
namespace BsodSimulator.ViewModel
{
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName]string propertyName=null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected void SetPropertyValue<T>(ref T property,T value, [CallerMemberName]string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(property,value))
{
property = value;
OnPropertyChanged(propertyName);
}
}
}
}
|
mit
|
C#
|
1fc14eaffc255d3b4b4c12dac08a48c354860fe0
|
Add implementation of enumerable interface for list responses.
|
henrikfroehling/TraktApiSharp
|
Source/Lib/TraktApiSharp/Experimental/Responses/TraktListResponse.cs
|
Source/Lib/TraktApiSharp/Experimental/Responses/TraktListResponse.cs
|
namespace TraktApiSharp.Experimental.Responses
{
using Exceptions;
using System.Collections;
using System.Collections.Generic;
public class TraktListResponse<TContentType> : ATraktResponse<List<TContentType>>, ITraktResponseHeaders, IEnumerable<TContentType>
{
public string SortBy { get; set; }
public string SortHow { get; set; }
public int? UserCount { get; set; }
internal TraktListResponse() : base() { }
internal TraktListResponse(List<TContentType> value) : base(value) { }
internal TraktListResponse(TraktException exception) : base(exception) { }
public static explicit operator List<TContentType>(TraktListResponse<TContentType> response) => response.Value;
public static implicit operator TraktListResponse<TContentType>(List<TContentType> value) => new TraktListResponse<TContentType>(value);
public IEnumerator<TContentType> GetEnumerator() => Value.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
|
namespace TraktApiSharp.Experimental.Responses
{
using Exceptions;
using System.Collections.Generic;
public class TraktListResponse<TContentType> : ATraktResponse<List<TContentType>>, ITraktResponseHeaders
{
public string SortBy { get; set; }
public string SortHow { get; set; }
public int? UserCount { get; set; }
internal TraktListResponse() : base() { }
internal TraktListResponse(List<TContentType> value) : base(value) { }
internal TraktListResponse(TraktException exception) : base(exception) { }
public static explicit operator List<TContentType>(TraktListResponse<TContentType> response) => response.Value;
public static implicit operator TraktListResponse<TContentType>(List<TContentType> value) => new TraktListResponse<TContentType>(value);
}
}
|
mit
|
C#
|
3797b21b2e21cfa46070791268055c054df11953
|
Break test for testing
|
fullstack101/SuggestionSystem,fullstack101/SuggestionSystem,fullstack101/SuggestionSystem,fullstack101/SuggestionSystem
|
Source/SuggestionSystem/Tests/SuggestionSystem.Web.Api.Tests/ControllerTests/SuggestionsControllerTests.cs
|
Source/SuggestionSystem/Tests/SuggestionSystem.Web.Api.Tests/ControllerTests/SuggestionsControllerTests.cs
|
namespace SuggestionSystem.Web.Api.Tests.ControllerTests
{
using Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyTested.WebApi;
using Setups;
[TestClass]
public class SuggestionsControllerTests
{
private IControllerBuilder<SuggestionsController> controller;
[TestInitialize]
public void Init()
{
this.controller = MyWebApi
.Controller<SuggestionsController>()
.WithResolvedDependencies(Services.GetSuggestionsService(), Services.GetCommentsService(), Services.GetVotesService());
}
[TestMethod]
public void UserGetSuggestionsShouldNotReturnWaitingForApproveAndNotApprovedSuggestions()
{
controller
.Calling(c => c.Get(1, 20, "DateCreated", null, null, false, false))
.ShouldReturn()
.Null();
}
}
}
|
namespace SuggestionSystem.Web.Api.Tests.ControllerTests
{
using Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyTested.WebApi;
using Setups;
[TestClass]
public class SuggestionsControllerTests
{
private IControllerBuilder<SuggestionsController> controller;
[TestInitialize]
public void Init()
{
this.controller = MyWebApi
.Controller<SuggestionsController>()
.WithResolvedDependencies(Services.GetSuggestionsService(), Services.GetCommentsService(), Services.GetVotesService());
}
[TestMethod]
public void UserGetSuggestionsShouldNotReturnWaitingForApproveAndNotApprovedSuggestions()
{
controller
.Calling(c => c.Get(1, 20, "DateCreated", null, null, false, false))
.ShouldReturn()
.Ok();
}
}
}
|
mit
|
C#
|
12058c446f84ea0c0d70f230c9b5e031015eb320
|
Remove request HTTP method from logging
|
alexanderkozlenko/oads,alexanderkozlenko/oads
|
src/Anemonis.MicrosoftOffice.AddinHost/Middleware/RequestTracingMiddleware.cs
|
src/Anemonis.MicrosoftOffice.AddinHost/Middleware/RequestTracingMiddleware.cs
|
// © Alexander Kozlenko. Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Serilog;
using Serilog.Events;
namespace Anemonis.MicrosoftOffice.AddinHost.Middleware
{
/// <summary>Represents request tracking middleware.</summary>
public sealed class RequestTracingMiddleware : IMiddleware
{
private readonly ILogger _logger;
/// <summary>Initializes a new instance of the <see cref="RequestTracingMiddleware" /> class.</summary>
/// <param name="logger">The logger instance.</param>
/// <exception cref="ArgumentNullException"><paramref name="logger" /> is <see langword="null" />.</exception>
public RequestTracingMiddleware(ILogger logger)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_logger = logger;
}
async Task IMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next.Invoke(context);
}
finally
{
var level = context.Response.StatusCode < StatusCodes.Status400BadRequest ? LogEventLevel.Information : LogEventLevel.Error;
_logger.Write(level, "{0} {1}", context.Response.StatusCode, context.Request.GetEncodedPathAndQuery());
}
}
}
}
|
// © Alexander Kozlenko. Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Serilog;
using Serilog.Events;
namespace Anemonis.MicrosoftOffice.AddinHost.Middleware
{
/// <summary>Represents request tracking middleware.</summary>
public sealed class RequestTracingMiddleware : IMiddleware
{
private readonly ILogger _logger;
/// <summary>Initializes a new instance of the <see cref="RequestTracingMiddleware" /> class.</summary>
/// <param name="logger">The logger instance.</param>
/// <exception cref="ArgumentNullException"><paramref name="logger" /> is <see langword="null" />.</exception>
public RequestTracingMiddleware(ILogger logger)
{
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_logger = logger;
}
async Task IMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
await next.Invoke(context);
}
finally
{
var level = context.Response.StatusCode < StatusCodes.Status400BadRequest ? LogEventLevel.Information : LogEventLevel.Error;
_logger.Write(level, "{0} {1} {2}", context.Response.StatusCode, context.Request.Method, context.Request.GetEncodedPathAndQuery());
}
}
}
}
|
mit
|
C#
|
78561fa944b0c8a7df0cb49b63482eeb0da6dbc1
|
Update version to 1.1.0
|
TheOtherTimDuncan/TOTD-Mailer
|
SharedAssemblyInfo.cs
|
SharedAssemblyInfo.cs
|
using System.Reflection;
// 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyProduct("TOTD Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
using System.Reflection;
// 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyProduct("TOTD Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
e46ff2094938ab07c696176d5f42e99f6beaa4ac
|
Fix unit test
|
GNOME/hyena,dufoli/hyena,arfbtwn/hyena,GNOME/hyena,dufoli/hyena,petejohanson/hyena,petejohanson/hyena,arfbtwn/hyena
|
src/Hyena/Hyena.Metrics/Tests/MetricsTests.cs
|
src/Hyena/Hyena.Metrics/Tests/MetricsTests.cs
|
//
// MetricsTests.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if ENABLE_TESTS
using System;
using System.IO;
using NUnit.Framework;
using Hyena;
using Hyena.Metrics;
namespace Hyena.Tests
{
[TestFixture]
public class MetricsTests
{
[Test]
public void MetricsCollection ()
{
var metrics = new MetricsCollection ("myuniqueid", new MemorySampleStore ());
Assert.AreEqual ("myuniqueid", metrics.AnonymousUserId);
metrics.AddDefaults ();
Assert.IsTrue (metrics.Count > 0);
string metrics_str = metrics.ToString ();
Assert.IsTrue (metrics_str.Contains ("ID: myuniqueid"));
// tests/Makefile.am runs the tests with Locale=it_IT
Assert.IsTrue (metrics_str.Contains ("it-IT"));
}
}
}
#endif
|
//
// MetricsTests.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if ENABLE_TESTS
using System;
using System.IO;
using NUnit.Framework;
using Hyena;
using Hyena.Metrics;
namespace Hyena.Tests
{
[TestFixture]
public class MetricsTests
{
[Test]
public void MetricsCollection ()
{
var metrics = new MetricsCollection ("myuniqueid", new MemorySampleStore ());
Assert.AreEqual ("myuniqueid", metrics.AnonymousUserId);
metrics.AddDefaults ();
Assert.IsTrue (metrics.Count > 0);
foreach (var metric in metrics) {
metric.TakeSample ();
}
string metrics_str = metrics.ToString ();
Assert.IsTrue (metrics_str.Contains ("ID: myuniqueid"));
// tests/Makefile.am runs the tests with Locale=it_IT
Assert.IsTrue (metrics_str.Contains ("it-IT"));
}
}
}
#endif
|
mit
|
C#
|
38f48181f6be152107ac0f7e8c6d7aefc8fa0db1
|
use TypeHelper.ConvertType
|
Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore
|
src/JsonApiDotNetCore/Models/AttrAttribute.cs
|
src/JsonApiDotNetCore/Models/AttrAttribute.cs
|
using System;
using System.Reflection;
using JsonApiDotNetCore.Internal;
namespace JsonApiDotNetCore.Models
{
public class AttrAttribute : Attribute
{
public AttrAttribute(string publicName)
{
PublicAttributeName = publicName;
}
public string PublicAttributeName { get; set; }
public string InternalAttributeName { get; set; }
public object GetValue(object entity)
{
return entity
.GetType()
.GetProperty(InternalAttributeName)
.GetValue(entity);
}
public void SetValue(object entity, object newValue)
{
var propertyInfo = entity
.GetType()
.GetProperty(InternalAttributeName);
if (propertyInfo != null)
{
var convertedValue = TypeHelper.ConvertType(newValue, propertyInfo.PropertyType);
propertyInfo.SetValue(entity, convertedValue);
}
}
}
}
|
using System;
using System.Reflection;
namespace JsonApiDotNetCore.Models
{
public class AttrAttribute : Attribute
{
public AttrAttribute(string publicName)
{
PublicAttributeName = publicName;
}
public string PublicAttributeName { get; set; }
public string InternalAttributeName { get; set; }
public object GetValue(object entity)
{
return entity
.GetType()
.GetProperty(InternalAttributeName)
.GetValue(entity);
}
public void SetValue(object entity, object newValue)
{
var propertyInfo = entity
.GetType()
.GetProperty(InternalAttributeName);
if (propertyInfo != null)
{
Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
var convertedValue = (newValue == null) ? null : Convert.ChangeType(newValue, t);
propertyInfo.SetValue(entity, convertedValue, null);
}
}
}
}
|
mit
|
C#
|
ad554784521b258c193b3e7541b7ffe6cbae5ace
|
Fix comment/doc for TracerProvider.Default (#3584)
|
open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet
|
src/OpenTelemetry.Api/Trace/TracerProvider.cs
|
src/OpenTelemetry.Api/Trace/TracerProvider.cs
|
// <copyright file="TracerProvider.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Diagnostics;
namespace OpenTelemetry.Trace
{
/// <summary>
/// TracerProvider is the entry point of the OpenTelemetry API. It provides access to <see cref="Tracer"/>.
/// </summary>
public class TracerProvider : BaseProvider
{
/// <summary>
/// Initializes a new instance of the <see cref="TracerProvider"/> class.
/// </summary>
protected TracerProvider()
{
}
/// <summary>
/// Gets the default <see cref="TracerProvider"/>.
/// </summary>
public static TracerProvider Default { get; } = new TracerProvider();
/// <summary>
/// Gets a tracer with given name and version.
/// </summary>
/// <param name="name">Name identifying the instrumentation library.</param>
/// <param name="version">Version of the instrumentation library.</param>
/// <returns>Tracer instance.</returns>
public Tracer GetTracer(string name, string version = null)
{
if (name == null)
{
name = string.Empty;
}
return new Tracer(new ActivitySource(name, version));
}
}
}
|
// <copyright file="TracerProvider.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Diagnostics;
namespace OpenTelemetry.Trace
{
/// <summary>
/// TracerProvider is the entry point of the OpenTelemetry API. It provides access to <see cref="Tracer"/>.
/// </summary>
public class TracerProvider : BaseProvider
{
/// <summary>
/// Initializes a new instance of the <see cref="TracerProvider"/> class.
/// </summary>
protected TracerProvider()
{
}
/// <summary>
/// Gets the default Tracer.
/// </summary>
public static TracerProvider Default { get; } = new TracerProvider();
/// <summary>
/// Gets a tracer with given name and version.
/// </summary>
/// <param name="name">Name identifying the instrumentation library.</param>
/// <param name="version">Version of the instrumentation library.</param>
/// <returns>Tracer instance.</returns>
public Tracer GetTracer(string name, string version = null)
{
if (name == null)
{
name = string.Empty;
}
return new Tracer(new ActivitySource(name, version));
}
}
}
|
apache-2.0
|
C#
|
5407e088930379dace739afedc25f93fd2cb7561
|
Implement BMP's GetData()
|
Davipb/BluwolfIcons
|
BluwolfIcons/BmpIconImage.cs
|
BluwolfIcons/BmpIconImage.cs
|
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
namespace BluwolfIcons
{
/// <summary>
/// A BMP (Bitmap) image inside an icon.
/// </summary>
public class BmpIconImage
{
/// <summary>
/// The original image.
/// </summary>
public Bitmap Image { get; set; }
/// <summary>
/// Whether a transparency map should be generated automatically for this image.
/// Set to <c>false</c> if the image already contains a transparency map. See remarks for more info.
/// </summary>
/// <remarks>
/// BMP images inside icons are stored with an extra transparency map above the actual image data.
/// That transparency map is a 1-bit per pixel AND mask that defines if a pixel is visible or not,
/// allowing for 1-bit transparency.
/// </remarks>
public bool GenerateTransparencyMap { get; set; } = true;
/// <summary>
/// Creates a new BMP icon image, with <paramref name="image"/> as its original image.
/// </summary>
/// <param name="image">The original image to use in this icon image.</param>
public BmpIconImage(Bitmap image)
{
Image = image;
}
/// <summary>
/// Generates the BMP icon image data for this image.
/// </summary>
/// <returns>The BMP icon image data for this image.</returns>
public byte[] GetData()
{
Bitmap result = null;
if (GenerateTransparencyMap)
{
// To avoid dealing with all possible formats, we'll standardize to 32-bit per pixel ARGB.
var normalized = Image.Clone(new Rectangle(Point.Empty, Image.Size), PixelFormat.Format32bppArgb);
result = new Bitmap(normalized.Width, normalized.Height * 2, normalized.PixelFormat);
var normalizedData = normalized.LockBits(new Rectangle(Point.Empty, normalized.Size), ImageLockMode.ReadOnly, normalized.PixelFormat);
var resultData = result.LockBits(new Rectangle(Point.Empty, result.Size), ImageLockMode.WriteOnly, result.PixelFormat);
byte[] buffer = new byte[normalizedData.Stride * normalizedData.Height];
// The transparency map must appear before the actual image, so we copy it now.
// Buffer will be set to all 0s, so the whole image will be visible.
// TODO: Implement support for already-transparent images
Marshal.Copy(buffer, 0, resultData.Scan0, buffer.Length);
// Now we copy the actual image.
Marshal.Copy(normalizedData.Scan0, buffer, 0, buffer.Length);
Marshal.Copy(buffer, 0, resultData.Scan0 + buffer.Length, buffer.Length);
normalized.UnlockBits(normalizedData);
normalized.Dispose();
result.UnlockBits(resultData);
}
else
{
// We copy the actual image because it'll be disposed later
result = Image.Clone(new Rectangle(Point.Empty, Image.Size), Image.PixelFormat);
}
using (var stream = new MemoryStream())
{
result.Save(stream, ImageFormat.MemoryBmp);
result.Dispose();
return stream.GetBuffer();
}
}
}
}
|
using System;
using System.Drawing;
namespace BluwolfIcons
{
/// <summary>
/// A BMP (Bitmap) image inside an icon.
/// </summary>
public class BmpIconImage
{
/// <summary>
/// The original image.
/// </summary>
public Bitmap Image { get; set; }
/// <summary>
/// Whether a transparency map should be generated automatically for this image.
/// Set to <c>false</c> if the image already contains a transparency map. See remarks for more info.
/// </summary>
/// <remarks>
/// <para>BMP images inside icons are stored with an extra transparency map above the actual image data.
/// That transparency map is a 1-bit per pixel AND mask that defines if a pixel is visible or not,
/// allowing for 1-bit transparency.</para>
/// <para>When generating the transparency map, <see cref="TransparencyTolerance"/> will be used for natively
/// transparent image formats.</para>
/// </remarks>
public bool GenerateTransparencyMap { get; set; } = true;
/// <summary>
/// When <see cref="GenerateTransparencyMap"/> is set to <c>true</c>, this defines the cutoff point
/// when generating the 1-bit transparency map. Alphas below this value will be considered transparent,
/// and those above or equal to it, visible.
/// </summary>
public byte TransparencyTolerance { get; set; } = 128;
/// <summary>
/// Creates a new BMP icon image, with <paramref name="image"/> as its original image.
/// </summary>
/// <param name="image">The original image to use in this icon image.</param>
public BmpIconImage(Bitmap image)
{
Image = image;
}
/// <summary>
/// Generates the BMP icon image data for this image.
/// </summary>
/// <returns>The BMP icon image data for this image.</returns>
public byte[] GetData()
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
c31f6f8d0ccdf2ae2f4374656df1075a8fa151d4
|
Add utility method ToSnakeCase to convert keys such as 'AppDataSubFolderName' to 'app_data_sub_folder_name' which seems more appropriate for settings files.
|
PenguinF/sandra-three
|
Sandra.UI.WF.Chess/Settings.cs
|
Sandra.UI.WF.Chess/Settings.cs
|
/*********************************************************************************
* Settings.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
using SysExtensions;
using System.Text;
namespace Sandra.UI.WF
{
internal static class SettingKeys
{
/// <summary>
/// Converts a Pascal case identifier to snake case for use as a key in a settings file.
/// </summary>
private static string ToSnakeCase(this string pascalCaseIdentifier)
{
// Start with converting to lower case.
StringBuilder snakeCase = new StringBuilder(pascalCaseIdentifier.ToLowerInvariant());
// Start at the end so the loop index doesn't need an update after insertion of an underscore.
// Stop at index 1, to prevent underscore before the first letter.
for (int i = pascalCaseIdentifier.Length - 1; i > 0; --i)
{
// Insert underscores before letters that have changed case.
if (pascalCaseIdentifier[i] != snakeCase[i])
{
snakeCase.Insert(i, '_');
}
}
return snakeCase.ToString();
}
internal static readonly SettingProperty<string> AppDataSubFolderName = new SettingProperty<string>(
new SettingKey(nameof(AppDataSubFolderName).ToSnakeCase()),
PType.String.Instance);
internal static readonly SettingProperty<PersistableFormState> Window = new SettingProperty<PersistableFormState>(
new SettingKey(nameof(Window).ToSnakeCase()),
PersistableFormState.Type);
internal static readonly SettingProperty<MovesTextBox.MFOSettingValue> Notation = new SettingProperty<MovesTextBox.MFOSettingValue>(
new SettingKey(nameof(Notation).ToSnakeCase()),
new PType.Enumeration<MovesTextBox.MFOSettingValue>(EnumHelper<MovesTextBox.MFOSettingValue>.AllValues));
internal static readonly SettingProperty<int> Zoom = new SettingProperty<int>(
new SettingKey(nameof(Zoom).ToSnakeCase()),
PType.RichTextZoomFactor.Instance);
}
internal static class Settings
{
public static SettingObject CreateDefault()
{
SettingCopy defaultSettings = new SettingCopy();
defaultSettings.AddOrReplace(SettingKeys.AppDataSubFolderName, "SandraChess");
return defaultSettings.Commit();
}
}
}
|
/*********************************************************************************
* Settings.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
using SysExtensions;
namespace Sandra.UI.WF
{
internal static class SettingKeys
{
internal static readonly SettingProperty<string> AppDataSubFolderName = new SettingProperty<string>(
new SettingKey(nameof(AppDataSubFolderName).ToLowerInvariant()),
PType.String.Instance);
internal static readonly SettingProperty<PersistableFormState> Window = new SettingProperty<PersistableFormState>(
new SettingKey(nameof(Window).ToLowerInvariant()),
PersistableFormState.Type);
internal static readonly SettingProperty<MovesTextBox.MFOSettingValue> Notation = new SettingProperty<MovesTextBox.MFOSettingValue>(
new SettingKey(nameof(Notation).ToLowerInvariant()),
new PType.Enumeration<MovesTextBox.MFOSettingValue>(EnumHelper<MovesTextBox.MFOSettingValue>.AllValues));
internal static readonly SettingProperty<int> Zoom = new SettingProperty<int>(
new SettingKey(nameof(Zoom).ToLowerInvariant()),
PType.RichTextZoomFactor.Instance);
}
internal static class Settings
{
public static SettingObject CreateDefault()
{
SettingCopy defaultSettings = new SettingCopy();
defaultSettings.AddOrReplace(SettingKeys.AppDataSubFolderName, "SandraChess");
return defaultSettings.Commit();
}
}
}
|
apache-2.0
|
C#
|
5f38c2e37084271a07abb8f8a8e7ba0c08f257ee
|
Fix test assembly load path
|
nbarbettini/polyglot-dotnet,nbarbettini/libpolyglot
|
libpolyglot.Tests/Assembly_tests.cs
|
libpolyglot.Tests/Assembly_tests.cs
|
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Shouldly;
using Xunit;
namespace libpolyglot.Tests
{
public class Assembly_tests
{
public static IEnumerable<object[]> TestAssemblies()
{
yield return new object[] { "EmptyVB.dll", Language.Vb };
yield return new object[] { "EmptyCS.dll", Language.CSharp };
yield return new object[] { "AnonymousAsyncVB.dll", Language.Vb };
yield return new object[] { "AnonymousAsyncCS.dll", Language.CSharp };
yield return new object[] { "DynamicCS.dll", Language.CSharp };
yield return new object[] { "EmptyFSharp.dll", Language.FSharp };
}
[Theory]
[MemberData(nameof(TestAssemblies))]
public void When_analyzing(string file, Language expected)
{
var assembly = Assembly.LoadFrom($"TestAssemblies{Path.DirectorySeparatorChar}{file}");
var analyzer = new AssemblyAnalyzer(assembly);
analyzer.DetectedLanguage.ShouldBe(expected);
}
}
}
|
using System.Collections.Generic;
using System.Reflection;
using Shouldly;
using Xunit;
namespace libpolyglot.Tests
{
public class Assembly_tests
{
public static IEnumerable<object[]> TestAssemblies()
{
yield return new object[] { "EmptyVB.dll", Language.Vb };
yield return new object[] { "EmptyCS.dll", Language.CSharp };
yield return new object[] { "AnonymousAsyncVB.dll", Language.Vb };
yield return new object[] { "AnonymousAsyncCS.dll", Language.CSharp };
yield return new object[] { "DynamicCS.dll", Language.CSharp };
yield return new object[] { "EmptyFSharp.dll", Language.FSharp };
}
[Theory]
[MemberData(nameof(TestAssemblies))]
public void When_analyzing(string file, Language expected)
{
var assembly = Assembly.LoadFrom($"TestAssemblies\\{file}");
var analyzer = new AssemblyAnalyzer(assembly);
analyzer.DetectedLanguage.ShouldBe(expected);
}
}
}
|
mit
|
C#
|
60699782ffee66364fe172ed41ce8973abe949e4
|
Use IDbConnection instead of SqlConnection (fixes #1)
|
half-ogre/dapper-wrapper
|
DapperWrapper/SqlExecutor.cs
|
DapperWrapper/SqlExecutor.cs
|
using System.Collections.Generic;
using System.Data;
using Dapper;
namespace DapperWrapper
{
public class SqlExecutor : IDbExecutor
{
readonly IDbConnection _dbConnection;
public SqlExecutor(IDbConnection dbConnection)
{
_dbConnection = dbConnection;
}
public int Execute(
string sql,
object param = null,
IDbTransaction transaction = null,
int? commandTimeout = default(int?),
CommandType? commandType = default(CommandType?))
{
return _dbConnection.Execute(
sql,
param,
transaction,
commandTimeout,
commandType);
}
public IEnumerable<dynamic> Query(
string sql,
object param = null,
IDbTransaction transaction = null,
bool buffered = true,
int? commandTimeout = default(int?),
CommandType? commandType = default(CommandType?))
{
return _dbConnection.Query(
sql,
param,
transaction,
buffered,
commandTimeout,
commandType);
}
public IEnumerable<T> Query<T>(
string sql,
object param = null,
IDbTransaction transaction = null,
bool buffered = true,
int? commandTimeout = default(int?),
CommandType? commandType = default(CommandType?))
{
return _dbConnection.Query<T>(
sql,
param,
transaction,
buffered,
commandTimeout,
commandType);
}
public void Dispose()
{
_dbConnection.Dispose();
}
}
}
|
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Dapper;
namespace DapperWrapper
{
public class SqlExecutor : IDbExecutor
{
readonly SqlConnection _sqlConnection;
public SqlExecutor(SqlConnection sqlConnection)
{
_sqlConnection = sqlConnection;
}
public int Execute(
string sql,
object param = null,
IDbTransaction transaction = null,
int? commandTimeout = default(int?),
CommandType? commandType = default(CommandType?))
{
return _sqlConnection.Execute(
sql,
param,
transaction,
commandTimeout,
commandType);
}
public IEnumerable<dynamic> Query(
string sql,
object param = null,
IDbTransaction transaction = null,
bool buffered = true,
int? commandTimeout = default(int?),
CommandType? commandType = default(CommandType?))
{
return _sqlConnection.Query(
sql,
param,
transaction,
buffered,
commandTimeout,
commandType);
}
public IEnumerable<T> Query<T>(
string sql,
object param = null,
IDbTransaction transaction = null,
bool buffered = true,
int? commandTimeout = default(int?),
CommandType? commandType = default(CommandType?))
{
return _sqlConnection.Query<T>(
sql,
param,
transaction,
buffered,
commandTimeout,
commandType);
}
public void Dispose()
{
_sqlConnection.Dispose();
}
}
}
|
mit
|
C#
|
ad9171d3ca7c61923da022597e14dad5fcc15b57
|
Change http request total name to match Prometheus guidelines
|
andrasm/prometheus-net
|
Prometheus.HttpExporter.AspNetCore/HttpRequestCount/HttpRequestCountOptions.cs
|
Prometheus.HttpExporter.AspNetCore/HttpRequestCount/HttpRequestCountOptions.cs
|
namespace Prometheus.HttpExporter.AspNetCore.HttpRequestCount
{
public class HttpRequestCountOptions : HttpExporterOptionsBase
{
public Counter Counter { get; set; } =
Metrics.CreateCounter(DefaultName, DefaultHelp, HttpRequestLabelNames.All);
private const string DefaultName = "http_requests_total";
private const string DefaultHelp = "Provides the count of HTTP requests from an ASP.NET application.";
}
}
|
namespace Prometheus.HttpExporter.AspNetCore.HttpRequestCount
{
public class HttpRequestCountOptions : HttpExporterOptionsBase
{
public Counter Counter { get; set; } =
Metrics.CreateCounter(DefaultName, DefaultHelp, HttpRequestLabelNames.All);
private const string DefaultName = "aspnet_http_requests_total";
private const string DefaultHelp = "Provides the count of HTTP requests from an ASP.NET application.";
}
}
|
mit
|
C#
|
ab07d5132cc04a619a89eb7c5b211bde7371a3b8
|
Order elements in some classes
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Gma/QrCodeNet/Encoding/Positioning/Stencils/PatternStencilBase.cs
|
WalletWasabi/Gma/QrCodeNet/Encoding/Positioning/Stencils/PatternStencilBase.cs
|
using System;
namespace Gma.QrCodeNet.Encoding.Positioning.Stencils
{
internal abstract class PatternStencilBase : BitMatrix
{
protected const bool O = false;
protected const bool X = true;
internal PatternStencilBase(int version)
{
Version = version;
}
public int Version { get; private set; }
public abstract bool[,] Stencil { get; }
public override int Width => Stencil.GetLength(0);
public override int Height => Stencil.GetLength(1);
public override bool[,] InternalArray => throw new NotImplementedException();
public override bool this[int i, int j]
{
get => Stencil[i, j];
set => throw new NotSupportedException();
}
public abstract void ApplyTo(TriStateMatrix matrix);
}
}
|
using System;
namespace Gma.QrCodeNet.Encoding.Positioning.Stencils
{
internal abstract class PatternStencilBase : BitMatrix
{
protected const bool O = false;
protected const bool X = true;
internal PatternStencilBase(int version)
{
Version = version;
}
public int Version { get; private set; }
public abstract bool[,] Stencil { get; }
public override bool this[int i, int j]
{
get => Stencil[i, j];
set => throw new NotSupportedException();
}
public override int Width => Stencil.GetLength(0);
public override int Height => Stencil.GetLength(1);
public override bool[,] InternalArray => throw new NotImplementedException();
public abstract void ApplyTo(TriStateMatrix matrix);
}
}
|
mit
|
C#
|
43b2d539864ef9c5960ba44921238ed6d17d6319
|
Increment Version Number.
|
krs43/ib-csharp,sebfia/ib-csharp,qusma/ib-csharp
|
Krs.Ats.IBNet/Properties/AssemblyInfo.cs
|
Krs.Ats.IBNet/Properties/AssemblyInfo.cs
|
using System;
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("Krs.Ats.IBNet")]
[assembly : AssemblyDescription("Interactive Brokers C# Client")]
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("Dinosaurtech")]
[assembly : AssemblyProduct("Krs.Ats.IBNet")]
[assembly : AssemblyCopyright("Copyright © 2009")]
[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("099cdbe6-c63a-4c1d-9d1e-de9942e56388")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly : AssemblyVersion("9.6.3.14")]
[assembly : AssemblyFileVersion("9.6.3.14")]
//CLS Compliant
[assembly : CLSCompliant(true)]
|
using System;
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("Krs.Ats.IBNet")]
[assembly : AssemblyDescription("Interactive Brokers C# Client")]
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("Dinosaurtech")]
[assembly : AssemblyProduct("Krs.Ats.IBNet")]
[assembly : AssemblyCopyright("Copyright © 2008")]
[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("099cdbe6-c63a-4c1d-9d1e-de9942e56388")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly : AssemblyVersion("9.6.3.13")]
[assembly : AssemblyFileVersion("9.6.3.13")]
//CLS Compliant
[assembly : CLSCompliant(true)]
|
mit
|
C#
|
6da3410c53ea86bd90dd6fe5795f68820d44d2dc
|
update package info
|
jgh004/CsvHelperAsync,jgh004/CsvHelperAsync,jgh004/CsvHelperAsync
|
CsvHelperAsync/Properties/AssemblyInfo.cs
|
CsvHelperAsync/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("CsvHelperAsync")]
[assembly: AssemblyDescription( "A library of asynchronous read and write large csv file. 简单高效的 csv 异步读写类, 可读写大型 csv 文件. See https://github.com/jgh004/CsvHelperAsync" )]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany( "ITnmg.net" )]
[assembly: AssemblyProduct("CsvHelperAsync")]
[assembly: AssemblyCopyright( "Copyright © 2016 ITnmg.net" )]
[assembly: AssemblyTrademark( "CsvHelperAsync" )]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("c425d531-7ec7-49f0-be1c-86089d9a7df3")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "1.0.1.0" )]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("CsvHelperAsync")]
[assembly: AssemblyDescription( "A library of asynchronous read and write large csv file. 简单高效的 csv 异步读写类, 可读写大型 csv 文件. See https://github.com/jgh004/CsvHelperAsync" )]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany( "ITnmg.net" )]
[assembly: AssemblyProduct("CsvHelperAsync")]
[assembly: AssemblyCopyright( "Copyright © 2016 ITnmg.net" )]
[assembly: AssemblyTrademark( "CsvHelperAsync" )]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("c425d531-7ec7-49f0-be1c-86089d9a7df3")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
2d733388f5a55abd330e5ce2d5e87a9c2a8af4fc
|
Change the personalization example comparison to be case insensitive
|
Kentico/Deliver-Dancing-Goat-.NET-MVC,Kentico/cloud-sample-app-net,Kentico/cloud-sample-app-net,Kentico/cloud-sample-app-net,Kentico/Deliver-Dancing-Goat-.NET-MVC
|
DancingGoat/Controllers/HomeController.cs
|
DancingGoat/Controllers/HomeController.cs
|
using System;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using DancingGoat.Models;
using KenticoCloud.Personalization;
using KenticoCloud.Personalization.MVC;
using KenticoCloud.Delivery;
namespace DancingGoat.Controllers
{
public class HomeController : ControllerBase
{
private readonly PersonalizationClient personalizationClient;
public HomeController()
{
// Disable personalization when PersonalizationToken is not set
var personalizationToken = ConfigurationManager.AppSettings["PersonalizationToken"];
if (!string.IsNullOrWhiteSpace(personalizationToken))
{
personalizationClient = new PersonalizationClient(personalizationToken);
}
}
public async Task<ActionResult> Index()
{
var response = await client.GetItemAsync<Home>("home");
var viewModel = new HomeViewModel
{
ContentItem = response.Item,
};
// Show promotion banner by default
var showPromotion = true;
if (personalizationClient != null)
{
// Get User ID of the current visitor
var visitorUid = Request.GetCurrentPersonalizationUid();
if (!string.IsNullOrEmpty(visitorUid))
{
// Determine whether the visitor submitted a form
var visitorSegments = await personalizationClient.GetVisitorSegmentsAsync(visitorUid);
showPromotion = !visitorSegments.Segments.Any(
s => string.Equals(s.Codename, "Customers_Who_Requested_a_Coffee_Sample",
StringComparison.OrdinalIgnoreCase)
);
}
}
var codeName = showPromotion ? "home_page_promotion" : "home_page_hero_unit";
viewModel.Header = response.Item.HeroUnit.Cast<HeroUnit>().FirstOrDefault(x => x.System.Codename == codeName);
return View(viewModel);
}
[ChildActionOnly]
public ActionResult CompanyAddress()
{
var contact = Task.Run(() => client.GetItemAsync<Home>("home", new ElementsParameter("contact"))).Result.Item.Contact;
return PartialView("CompanyAddress", contact);
}
}
}
|
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using DancingGoat.Models;
using KenticoCloud.Personalization;
using KenticoCloud.Personalization.MVC;
using KenticoCloud.Delivery;
namespace DancingGoat.Controllers
{
public class HomeController : ControllerBase
{
private readonly PersonalizationClient personalizationClient;
public HomeController()
{
// Disable personalization when PersonalizationToken is not set
var personalizationToken = ConfigurationManager.AppSettings["PersonalizationToken"];
if (!string.IsNullOrWhiteSpace(personalizationToken))
{
personalizationClient = new PersonalizationClient(personalizationToken);
}
}
public async Task<ActionResult> Index()
{
var response = await client.GetItemAsync<Home>("home");
var viewModel = new HomeViewModel
{
ContentItem = response.Item,
};
// Show promotion banner by default
var showPromotion = true;
if (personalizationClient != null)
{
// Get User ID of the current visitor
var visitorUid = Request.GetCurrentPersonalizationUid();
if (!string.IsNullOrEmpty(visitorUid))
{
// Determine whether the visitor submitted a form
var visitorSegments = await personalizationClient.GetVisitorSegmentsAsync(visitorUid);
showPromotion = !visitorSegments.Segments.Any(s => s.Codename == "Customers_Who_Requested_a_Coffee_Sample");
}
}
var codeName = showPromotion ? "home_page_promotion" : "home_page_hero_unit";
viewModel.Header = response.Item.HeroUnit.Cast<HeroUnit>().FirstOrDefault(x => x.System.Codename == codeName);
return View(viewModel);
}
[ChildActionOnly]
public ActionResult CompanyAddress()
{
var contact = Task.Run(() => client.GetItemAsync<Home>("home", new ElementsParameter("contact"))).Result.Item.Contact;
return PartialView("CompanyAddress", contact);
}
}
}
|
mit
|
C#
|
bcd8c7b22f0fc7c38678e2c3e947ba59048116e2
|
Fix cheering occuring incorrectly
|
NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare
|
Assets/Microgames/BeachBall/Scripts/BeachBallCollisionObserver.cs
|
Assets/Microgames/BeachBall/Scripts/BeachBallCollisionObserver.cs
|
using UnityEngine;
/// <summary>
/// Observes ball params. Switches z index and triggers win if requirements are met
/// </summary>
public class BeachBallCollisionObserver : MonoBehaviour
{
[SerializeField]
private AudioClip victoryClip;
protected Collider2D innerArea;
protected Collider2D ballCollider;
protected Rigidbody2D ballPhysics;
protected bool fired = false;
public bool Fired
{
get
{
return fired;
}
set
{}
}
protected virtual void Start()
{
innerArea = GetComponent<Collider2D>();
var ballGo = GameObject.Find("Ball");
ballCollider = ballGo.GetComponent<CircleCollider2D>();
ballPhysics = ballGo.GetComponent<Rigidbody2D>();
}
void Update()
{
}
public virtual void OnTriggerStay2D(Collider2D other)
{
if (!fired && ballPhysics.velocity.y < 0 && other == ballCollider
&& !MicrogameController.instance.getVictoryDetermined())
{
fired = true;
other.gameObject.GetComponent<BeachBallZSwitcher>().Switch();
MicrogameController.instance.setVictory(victory: true, final: true);
MicrogameController.instance.playSFX(victoryClip);
}
}
}
|
using UnityEngine;
/// <summary>
/// Observes ball params. Switches z index and triggers win if requirements are met
/// </summary>
public class BeachBallCollisionObserver : MonoBehaviour
{
[SerializeField]
private AudioClip victoryClip;
protected Collider2D innerArea;
protected Collider2D ballCollider;
protected Rigidbody2D ballPhysics;
protected bool fired = false;
public bool Fired
{
get
{
return fired;
}
set
{}
}
protected virtual void Start()
{
innerArea = GetComponent<Collider2D>();
var ballGo = GameObject.Find("Ball");
ballCollider = ballGo.GetComponent<CircleCollider2D>();
ballPhysics = ballGo.GetComponent<Rigidbody2D>();
}
void Update()
{
}
public virtual void OnTriggerStay2D(Collider2D other)
{
if (!fired && ballPhysics.velocity.y < 0 && other == ballCollider)
{
fired = true;
other.gameObject.GetComponent<BeachBallZSwitcher>().Switch();
MicrogameController.instance.setVictory(victory: true, final: true);
MicrogameController.instance.playSFX(victoryClip);
}
}
}
|
mit
|
C#
|
101860bd4f07cf8ac194adb526ec10881d807a4c
|
Update Startup.cs
|
alsafonov/gitresources,alsafonov/gitresources
|
GitResources/Startup.cs
|
GitResources/Startup.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace GitResources
{
public partial class Startup
{
//11111111111111111111111111111
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace GitResources
{
public partial class Startup
{
}
}
|
mit
|
C#
|
930499532171a06e686d9a3e99b071f48faa37d0
|
reduce max default frame data length
|
lopper/WebSocket.Portable,esskar/WebSocket.Portable,kabsila/WebSocket.Portable
|
WebSocket.Portable.Core/Internal/Consts.cs
|
WebSocket.Portable.Core/Internal/Consts.cs
|
namespace WebSocket.Portable.Internal
{
internal static class Consts
{
public static readonly char[] ExtensionParmeterValueNeedQuotesChars = { ' ', '\t', ',', ';', '=' };
public const string HeaderOrigin = "Origin";
public const string HeaderSecWebSocketAccept = "Sec-WebSocket-Accept";
public const string HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions";
public const string HeaderSecWebSocketKey = "Sec-WebSocket-Key";
public const string HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol";
public const string HeaderSecWebSocketVersion = "Sec-WebSocket-Version";
public const string SchemeHttp = "http";
public const string SchemeHttps = "https";
public const string SchemeWs = "ws";
public const string SchemeWss = "wss";
public const string ServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
public static readonly string[] SupportedClientVersions = { "13" };
public const int MaxDefaultFrameDataLength = 1016;
public const int MaxAllowedFrameDataLength = 1024 * 256;
}
}
|
namespace WebSocket.Portable.Internal
{
internal static class Consts
{
public static readonly char[] ExtensionParmeterValueNeedQuotesChars = { ' ', '\t', ',', ';', '=' };
public const string HeaderOrigin = "Origin";
public const string HeaderSecWebSocketAccept = "Sec-WebSocket-Accept";
public const string HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions";
public const string HeaderSecWebSocketKey = "Sec-WebSocket-Key";
public const string HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol";
public const string HeaderSecWebSocketVersion = "Sec-WebSocket-Version";
public const string SchemeHttp = "http";
public const string SchemeHttps = "https";
public const string SchemeWs = "ws";
public const string SchemeWss = "wss";
public const string ServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
public static readonly string[] SupportedClientVersions = { "13" };
public const int MaxDefaultFrameDataLength = 1024;
public const int MaxAllowedFrameDataLength = 1024 * 256;
}
}
|
apache-2.0
|
C#
|
9d30402bd593f196b8778b488eb5d8d00e0ffb47
|
remove a Enrol method overloading
|
Mooophy/158212
|
as5/Lib/University.cs
|
as5/Lib/University.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lib
{
public class University
{
public SortedSet<Student> Students { get; private set; }
public SortedSet<Paper> Papers { get; private set; }
public Dictionary<Paper, SortedSet<Student>> Enrollment { get; private set; }
public University()
{
Students = new SortedSet<Student>();
Papers = new SortedSet<Paper>();
Enrollment = new Dictionary<Paper, SortedSet<Student>>();
}
public void Add(Student student)
{
Students.Add(student);
}
public void Add(Paper paper)
{
Papers.Add(paper);
}
public void AddRange(IEnumerable<Student> collection)
{
foreach(var elem in collection) Students.Add(elem);
}
public void AddRange(IEnumerable<Paper> collection)
{
foreach (var elem in collection) Papers.Add(elem);
}
public IEnumerable<Student> Find(Paper paper)
{
return Enrollment.ContainsKey(paper) ? Enrollment[paper].AsEnumerable() : (new Student[0]).AsEnumerable();
}
public IEnumerable<Paper> Find(Student student)
{
return from entry in Enrollment where entry.Value.Contains(student) select entry.Key;
}
public bool Enrol(int paperCode, int studentId)
{
var paper = FindPaper(paperCode);
var student = FindStudent(studentId);
if (!Papers.Contains(paper) || !Students.Contains(student) || paper == null || student == null)
return false;
if (Enrollment.Keys.Contains(paper))
Enrollment[paper].Add(student);
else
Enrollment[paper] = new SortedSet<Student> { student };
return true;
}
public Paper FindPaper(int paperCode)
{
return Papers.First(p => p.Number == paperCode);
}
public Student FindStudent(int studentId)
{
return Students.First(s => s.Id == studentId);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lib
{
public class University
{
public SortedSet<Student> Students { get; private set; }
public SortedSet<Paper> Papers { get; private set; }
public Dictionary<Paper, SortedSet<Student>> Enrollment { get; private set; }
public University()
{
Students = new SortedSet<Student>();
Papers = new SortedSet<Paper>();
Enrollment = new Dictionary<Paper, SortedSet<Student>>();
}
public void Add(Student student)
{
Students.Add(student);
}
public void Add(Paper paper)
{
Papers.Add(paper);
}
public void AddRange(IEnumerable<Student> collection)
{
foreach(var elem in collection) Students.Add(elem);
}
public void AddRange(IEnumerable<Paper> collection)
{
foreach (var elem in collection) Papers.Add(elem);
}
public IEnumerable<Student> Find(Paper paper)
{
return Enrollment.ContainsKey(paper) ? Enrollment[paper].AsEnumerable() : (new Student[0]).AsEnumerable();
}
public IEnumerable<Paper> Find(Student student)
{
return from entry in Enrollment where entry.Value.Contains(student) select entry.Key;
}
public bool Enrol(Paper paper, Student student)
{
if (!Papers.Contains(paper) || !Students.Contains(student) || paper == null || student == null)
return false;
if (Enrollment.Keys.Contains(paper))
Enrollment[paper].Add(student);
else
Enrollment[paper] = new SortedSet<Student> { student };
return true;
}
public bool Enrol(int paperCode, int studentId)
{
return Enrol(FindPaper(paperCode), FindStudent(studentId));
}
public Paper FindPaper(int paperCode)
{
return Papers.First(p => p.Number == paperCode);
}
public Student FindStudent(int studentId)
{
return Students.First(s => s.Id == studentId);
}
}
}
|
mit
|
C#
|
25153f1ff749a95776ffe93c9fac0bc7b2cea469
|
Clean up on logging
|
Red-Folder/WebCrawl-Functions
|
WebCrawlCleanup/run.csx
|
WebCrawlCleanup/run.csx
|
using System.Net;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Red_Folder.WebCrawl.Data;
public static async Task Run(TimerInfo timerInfo, TraceWriter log)
{
log.Info($"Web Crawl Clean up triggered");
// Convert from connection string to uri & key
// Doesn't currently appear to be a vary to create a DocumentClient from a connection string
string documentDbEndpoint = System.Environment.GetEnvironmentVariable("APPSETTING_rfcwebcrawl_DOCUMENTDB");
string endpointUri = documentDbEndpoint.Split(';')[0].Split('=')[1];
string primaryKey = documentDbEndpoint.Split(';')[1].Split('=')[1];
string databaseName = "crawlOutput";
string collectionName = "WebCrawl";
DocumentClient client;
log.Info($"Creating client for: {endpointUri}");
client = new DocumentClient(new Uri(endpointUri), primaryKey);
// Set some common query options
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
var docCount = client.CreateDocumentQuery<CrawlResults>(UriFactory
.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.ToList()
.Count();
log.Info(String.Format("Total of {0} documents found", docCount));
if (docCount > 1)
{
log.Info("Setting up the LINQ query to get all docs except latest ...");
//var sqlQuery = String.Format("select top {0} from c order by c.timestamp", docCount - 13);
//Get a reference to the collection
//DocumentCollection coll = client.CreateDocumentCollectionQuery(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), //queryOptions)
// .ToArray()
// .FirstOrDefault();
//First execution of the query
//var results = client.CreateDocumentQuery<CrawlResults>(coll.DocumentsLink, sqlQuery).AsDocumentQuery();
var results = client.CreateDocumentQuery<CrawlResults>(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.OrderBy(x => x.Timestamp)
.Take(docCount - 13)
.AsDocumentQuery();
while (results.HasMoreResults)
{
foreach (CrawlResults doc in await results.ExecuteNextAsync())
{
log.Info(String.Format("Deleting document {0}", doc.Id));
Uri docUri = UriFactory.CreateDocumentUri(databaseName, collectionName, doc.Id);
log.Info(String.Format("Uri = {0}", docUri.ToString()));
// Use this constructed Uri to delete the document
//await client.DeleteDocumentAsync(docUri);
//log.Info($"Selflink = {0}", ((Document)doc).SelfLink);
//await client.DeleteDocumentAsync(doc.SelfLink);
}
}
}
log.Info("Finished");
}
|
using System.Net;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Red_Folder.WebCrawl.Data;
public static async Task Run(TimerInfo timerInfo, TraceWriter log)
{
log.Info($"Web Crawl Clean up triggered");
// Convert from connection string to uri & key
// Doesn't currently appear to be a vary to create a DocumentClient from a connection string
string documentDbEndpoint = System.Environment.GetEnvironmentVariable("APPSETTING_rfcwebcrawl_DOCUMENTDB");
string endpointUri = documentDbEndpoint.Split(';')[0].Split('=')[1];
string primaryKey = documentDbEndpoint.Split(';')[1].Split('=')[1];
string databaseName = "crawlOutput";
string collectionName = "WebCrawl";
DocumentClient client;
log.Info($"Creating client for: {endpointUri}");
client = new DocumentClient(new Uri(endpointUri), primaryKey);
// Set some common query options
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 };
var docCount = client.CreateDocumentQuery<CrawlResults>(UriFactory
.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.ToList()
.Count();
log.Info($"Total of {0} documents found");
if (docCount > 1)
{
log.Info("Setting up the LINQ query to get all docs except latest ...");
//var sqlQuery = String.Format("select top {0} from c order by c.timestamp", docCount - 13);
//Get a reference to the collection
//DocumentCollection coll = client.CreateDocumentCollectionQuery(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), //queryOptions)
// .ToArray()
// .FirstOrDefault();
//First execution of the query
//var results = client.CreateDocumentQuery<CrawlResults>(coll.DocumentsLink, sqlQuery).AsDocumentQuery();
var results = client.CreateDocumentQuery<CrawlResults>(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), queryOptions)
.OrderBy(x => x.Timestamp)
.Take(docCount - 13)
.AsDocumentQuery();
while (results.HasMoreResults)
{
foreach (CrawlResults doc in await results.ExecuteNextAsync())
{
log.Info($"Deleting document {0}", doc.Id);
Uri docUri = UriFactory.CreateDocumentUri(databaseName, collectionName, doc.Id);
log.Info($"Uri = {0}", docUri.ToString());
// Use this constructed Uri to delete the document
//await client.DeleteDocumentAsync(docUri);
//log.Info($"Selflink = {0}", ((Document)doc).SelfLink);
//await client.DeleteDocumentAsync(doc.SelfLink);
}
}
}
log.Info("Finished");
}
|
mit
|
C#
|
c143453f5f3e960871674a219b1556a7a55b29d6
|
Fix point skipped during get points issue
|
holance/helix-toolkit,chrkon/helix-toolkit,helix-toolkit/helix-toolkit,JeremyAnsel/helix-toolkit,smischke/helix-toolkit,Iluvatar82/helix-toolkit
|
Source/HelixToolkit.Wpf.SharpDX/Model/Geometry/PointGeometry3D.cs
|
Source/HelixToolkit.Wpf.SharpDX/Model/Geometry/PointGeometry3D.cs
|
namespace HelixToolkit.Wpf.SharpDX
{
using System;
using System.Collections.Generic;
using HelixToolkit.SharpDX.Shared.Utilities;
[Serializable]
public class PointGeometry3D : Geometry3D
{
public IEnumerable<Geometry3D.Point> Points
{
get
{
for (int i = 0; i < Positions.Count; ++i)
{
yield return new Point { P0 = Positions[i] };
}
}
}
protected override IOctree CreateOctree(OctreeBuildParameter parameter)
{
return new PointGeometryOctree(Positions, parameter);
}
}
}
|
namespace HelixToolkit.Wpf.SharpDX
{
using System;
using System.Collections.Generic;
using HelixToolkit.SharpDX.Shared.Utilities;
[Serializable]
public class PointGeometry3D : Geometry3D
{
public IEnumerable<Geometry3D.Point> Points
{
get
{
for (int i = 0; i < Indices.Count; i += 2)
{
yield return new Point { P0 = Positions[Indices[i]] };
}
}
}
protected override IOctree CreateOctree(OctreeBuildParameter parameter)
{
return new PointGeometryOctree(Positions, parameter);
}
}
}
|
mit
|
C#
|
b0c678c894cfd71fa0b4aed21801a638d7ac4e09
|
Change CharParser to use a predicate
|
exodrifter/unity-rumor
|
Parser/Simple/CharParser.cs
|
Parser/Simple/CharParser.cs
|
using System;
namespace Exodrifter.Rumor.Parser
{
public class CharParser : Parser<char>
{
private readonly Func<char, bool> predicate;
private readonly string expected;
public CharParser(char ch)
: this((other) => ch == other, ch.ToString()) { }
/// <summary>
/// Creates a new CharParser which succeeds on a predicate check.
/// </summary>
/// <param name="predicate">
/// The predicate to test.
/// </param>
/// <param name="expected">
/// The expected value (used in error messages).
/// </param>
public CharParser(Func<char, bool> predicate, string expected)
{
this.predicate = predicate;
this.expected = expected;
}
public override Result<char> Parse(State state)
{
if (state.Source.Length <= state.Index)
{
return Result<char>.Error(state.Index, expected);
}
var ch = state.Source[state.Index];
if (predicate(ch))
{
var newState = state.AddIndex(1);
return Result<char>.Success(newState, ch);
}
return Result<char>.Error(state.Index, expected);
}
}
}
|
namespace Exodrifter.Rumor.Parser
{
public class CharParser : Parser<char>
{
private readonly char ch;
public CharParser(char ch)
{
this.ch = ch;
}
public override Result<char> Parse(State state)
{
if (state.Source.Length <= state.Index)
{
return Result<char>.Error(state.Index, ch.ToString());
}
if (state.Source[state.Index] == ch)
{
var newState = state.AddIndex(1);
return Result<char>.Success(newState, ch);
}
return Result<char>.Error(state.Index, ch.ToString());
}
}
}
|
mit
|
C#
|
7a03c277cf6cd60fae86fc049025b08d20e2a2a9
|
Add quote search by keyword and text
|
Midnight-Myth/Mitternacht-NEW,powered-by-moe/MikuBot,Blacnova/NadekoBot,PravEF/EFNadekoBot,gfrewqpoiu/NadekoBot,ShadowNoire/NadekoBot,halitalf/NadekoMods,Midnight-Myth/Mitternacht-NEW,WoodenGlaze/NadekoBot,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Nielk1/NadekoBot,miraai/NadekoBot,Grinjr/NadekoBot,Taknok/NadekoBot,Youngsie1997/NadekoBot,ScarletKuro/NadekoBot,shikhir-arora/NadekoBot
|
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
|
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
|
using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
return _set.Where(q => q.Text.Contains(text) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
|
using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
return _set.Where(q => q.Text.Contains(text) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
|
mit
|
C#
|
f4e2bbf69519b38b9c3748ef65461c90c7739946
|
Allow to define host address in client
|
lemked/simplesecurewcfapp
|
Client/Program.cs
|
Client/Program.cs
|
using System;
using System.ServiceModel;
using Service;
namespace Client
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter server address: ");
var hostAddress = Console.ReadLine();
var address = new EndpointAddress(new Uri(string.Format("http://{0}:9000/MyService", hostAddress)));
var binding = new BasicHttpBinding();
var factory = new ChannelFactory<IWcfService>(binding, address);
IWcfService host = factory.CreateChannel();
Console.WriteLine("Please enter some words or press [Esc] to exit the application.");
while (true)
{
var key = Console.ReadKey();
if (key.Key.Equals(ConsoleKey.Escape))
{
return;
}
string input = key.KeyChar.ToString() + Console.ReadLine(); // read input
string output = host.Echo(input); // send to host, receive output
Console.WriteLine(output); // write output
}
}
}
}
|
using System;
using System.ServiceModel;
using Service;
namespace Client
{
class Program
{
static void Main(string[] args)
{
var address = new EndpointAddress(new Uri("http://localhost:9000/MyService"));
var binding = new BasicHttpBinding();
var factory = new ChannelFactory<IWcfService>(binding, address);
IWcfService host = factory.CreateChannel();
Console.WriteLine("Please enter some words or press [Esc] to exit the application.");
while (true)
{
var key = Console.ReadKey();
if (key.Key.Equals(ConsoleKey.Escape))
{
return;
}
string input = key.KeyChar.ToString() + Console.ReadLine(); // read input
string output = host.Echo(input); // send to host, receive output
Console.WriteLine(output); // write output
}
}
}
}
|
apache-2.0
|
C#
|
1414669ebb0d8cb75cce9677d0947ed730b291b5
|
Add PrepaymentID to bank transaction
|
MatthewSteeples/XeroAPI.Net
|
source/XeroApi/Model/BankTransaction.cs
|
source/XeroApi/Model/BankTransaction.cs
|
using System;
namespace XeroApi.Model
{
public class BankTransaction : EndpointModelBase
{
[ItemId]
public Guid? BankTransactionID { get; set; }
public Account BankAccount { get; set; }
public string Type { get; set; }
public string Reference { get; set; }
public string Url { get; set; }
public string ExternalLinkProviderName { get; set; }
public bool IsReconciled { get; set; }
public decimal? CurrencyRate { get; set; }
public Contact Contact { get; set; }
public DateTime? Date { get; set; }
public DateTime? DueDate { get; set; }
public virtual Guid? BrandingThemeID { get; set; }
public virtual string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public virtual LineItems LineItems { get; set; }
public virtual decimal? SubTotal { get; set; }
public virtual decimal? TotalTax { get; set; }
public virtual decimal? Total { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public virtual string CurrencyCode { get; set; }
public DateTime? FullyPaidOnDate { get; set; }
public Guid? PrepaymentID { get; set; }
}
public class BankTransactions : ModelList<BankTransaction>
{
}
}
|
using System;
namespace XeroApi.Model
{
public class BankTransaction : EndpointModelBase
{
[ItemId]
public Guid? BankTransactionID { get; set; }
public Account BankAccount { get; set; }
public string Type { get; set; }
public string Reference { get; set; }
public string Url { get; set; }
public string ExternalLinkProviderName { get; set; }
public bool IsReconciled { get; set; }
public decimal? CurrencyRate { get; set; }
public Contact Contact { get; set; }
public DateTime? Date { get; set; }
public DateTime? DueDate { get; set; }
public virtual Guid? BrandingThemeID { get; set; }
public virtual string Status { get; set; }
public LineAmountType LineAmountTypes { get; set; }
public virtual LineItems LineItems { get; set; }
public virtual decimal? SubTotal { get; set; }
public virtual decimal? TotalTax { get; set; }
public virtual decimal? Total { get; set; }
[ItemUpdatedDate]
public DateTime? UpdatedDateUTC { get; set; }
public virtual string CurrencyCode { get; set; }
public DateTime? FullyPaidOnDate { get; set; }
}
public class BankTransactions : ModelList<BankTransaction>
{
}
}
|
mit
|
C#
|
3cfbf91fdbdf2abb43285658f39f7fbb7a551982
|
Bump version
|
khalidabuhakmeh/NElasticsearch,synhershko/NElasticsearch
|
NElasticsearch/Properties/AssemblyInfo.cs
|
NElasticsearch/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("NElasticsearch")]
[assembly: AssemblyDescription("An alternative Elasticsearch client for .NET, built on-the-go while working on real-world projects")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Itamar Syn-Hershko")]
[assembly: AssemblyProduct("NElasticsearch")]
[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("174baa7a-0959-4398-bf1e-dc110d7ce414")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
|
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("NElasticsearch")]
[assembly: AssemblyDescription("An alternative Elasticsearch client for .NET, built on-the-go while working on real-world projects")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Itamar Syn-Hershko")]
[assembly: AssemblyProduct("NElasticsearch")]
[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("174baa7a-0959-4398-bf1e-dc110d7ce414")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
|
apache-2.0
|
C#
|
98042eb7d4aaec3e53530b6ffbc2bff2b014ea71
|
add the default fadeout-while-scaling-up to clicked objects
|
ppy/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu,ZLima12/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,EVAST9919/osu,peppy/osu-new,2yangk23/osu,peppy/osu,smoogipooo/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,UselessToucan/osu
|
osu.Game.Rulesets.Osu/Mods/OsuModDeflate.cs
|
osu.Game.Rulesets.Osu/Mods/OsuModDeflate.cs
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using System.Collections.Generic;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModDeflate : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Deflate";
public override string ShortenedName => "DF";
public override FontAwesome Icon => FontAwesome.fa_compress;
public override ModType Type => ModType.Fun;
public override string Description => "Become one with the approach circle...";
public override double ScoreMultiplier => 1;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var drawable in drawables)
drawable.ApplyCustomUpdateState += drawableOnApplyCustomUpdateState;
}
protected void drawableOnApplyCustomUpdateState(DrawableHitObject drawable, ArmedState state)
{
if (!(drawable is DrawableHitCircle d))
return;
d.ApproachCircle.Hide();
var h = d.HitObject;
using (d.BeginAbsoluteSequence(h.StartTime - h.TimePreempt))
{
var origScale = d.Scale;
d.ScaleTo(1.1f, 1) // if duration = 0 then components (i.e. flash) scale with it -> we don't want that
.Then()
.ScaleTo(origScale, h.TimePreempt)
.Then()
.ScaleTo(d.Scale * 1.5f, 400, Easing.OutQuad); // reapply overwritten ScaleTo
}
}
}
}
|
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using System.Collections.Generic;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModDeflate : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Deflate";
public override string ShortenedName => "DF";
public override FontAwesome Icon => FontAwesome.fa_compress;
public override ModType Type => ModType.Fun;
public override string Description => "Become one with the approach circle...";
public override double ScoreMultiplier => 1;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var drawable in drawables)
drawable.ApplyCustomUpdateState += drawableOnApplyCustomUpdateState;
}
protected void drawableOnApplyCustomUpdateState(DrawableHitObject drawable, ArmedState state)
{
if (!(drawable is DrawableHitCircle d))
return;
d.ApproachCircle.Hide();
var h = d.HitObject;
using (d.BeginAbsoluteSequence(h.StartTime - h.TimePreempt))
{
var origScale = d.Scale;
d.ScaleTo(1.1f, 1) // if duration = 0 then components (i.e. flash) scale with it -> we don't want that
.Then()
.ScaleTo(origScale, h.TimePreempt);
}
}
}
}
|
mit
|
C#
|
1f0297a0ae0bdb086f76c0e90625f7d3fd53c1a8
|
Update version
|
CodefoundryDE/LegacyWrapper,CodefoundryDE/LegacyWrapper
|
GlobalAssemblyInfo.cs
|
GlobalAssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyDescription("LegacyWrapper uses a wrapper process to call dlls from a process of the opposing architecture (X86 or AMD64).")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("codefoundry.de")]
[assembly: AssemblyCopyright("Copyright (c) 2019, Franz Wimmer. (MIT License)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: InternalsVisibleTo("LegacyWrapperTest")]
[assembly: InternalsVisibleTo("LegacyWrapperTest.Integration")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // For moq
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyDescription("LegacyWrapper uses a wrapper process to call dlls from a process of the opposing architecture (X86 or AMD64).")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("codefoundry.de")]
[assembly: AssemblyCopyright("Copyright (c) 2017, Franz Wimmer. (MIT License)")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: InternalsVisibleTo("LegacyWrapperTest")]
[assembly: InternalsVisibleTo("LegacyWrapperTest.Integration")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // For moq
|
mit
|
C#
|
931c8c36a54148689a70bb14b59a57f8983b4ffc
|
Update assembly version.
|
MatthewKing/DeviceId
|
src/DeviceId/Properties/AssemblyInfo.cs
|
src/DeviceId/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DeviceId")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeviceId")]
[assembly: AssemblyCopyright("Copyright © Matthew King 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("13803197-daeb-4ba4-8a38-7be03930f463")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DeviceId")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeviceId")]
[assembly: AssemblyCopyright("Copyright © Matthew King 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("13803197-daeb-4ba4-8a38-7be03930f463")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
|
mit
|
C#
|
410f304e142287f50f1f9ca9d31da639e54cd747
|
Document color scheme button
|
lambdacasserole/shaver
|
Shaver/ColorSchemeButton.cs
|
Shaver/ColorSchemeButton.cs
|
using System.Drawing;
using System.Windows.Forms;
namespace Shaver
{
/// <summary>
/// A color scheme keyboard button control.
/// </summary>
class ColorSchemeButton : KeyboardButton
{
private int iconSize;
/// <summary>
/// Gets or sets the icon size on the button.
/// </summary>
public int IconSize
{
get
{
return iconSize;
}
set
{
iconSize = value;
Refresh(); // Redraw.
}
}
/// <summary>
/// Initializes a new instance of a color scheme button.
/// </summary>
public ColorSchemeButton() : base()
{
// Icon size should initially be 8.
iconSize = 8;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Draw four colored circles icon.
int x = Width / 2;
int y = Height / 2;
int s = IconSize / 4;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
e.Graphics.FillEllipse(new SolidBrush(Color.Red), x - IconSize - s, y - IconSize - s, IconSize, IconSize);
e.Graphics.FillEllipse(new SolidBrush(Color.Orange), x + s, y - IconSize - s, IconSize, IconSize);
e.Graphics.FillEllipse(new SolidBrush(Color.Blue), x - IconSize - s, y + s, IconSize, IconSize);
e.Graphics.FillEllipse(new SolidBrush(Color.Yellow), x + s, y + s, IconSize, IconSize);
}
}
}
|
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Shaver
{
/// <summary>
/// A color scheme keyboard button control.
/// </summary>
class ColorSchemeButton : KeyboardButton
{
private int iconSize;
/// <summary>
/// Gets or sets the icon size on the button.
/// </summary>
public int IconSize
{
get
{
return iconSize;
}
set
{
iconSize = value;
Refresh();
}
}
/// <summary>
/// Initializes a new instance of a color scheme button.
/// </summary>
public ColorSchemeButton() : base()
{
iconSize = 8;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Draw two pages copy symbol.
int x = Width / 2;
int y = Height / 2;
int s = IconSize / 4;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
e.Graphics.FillEllipse(new SolidBrush(Color.Red), x - IconSize - s, y - IconSize - s, IconSize, IconSize);
e.Graphics.FillEllipse(new SolidBrush(Color.Orange), x + s, y - IconSize - s, IconSize, IconSize);
e.Graphics.FillEllipse(new SolidBrush(Color.Blue), x - IconSize - s, y + s, IconSize, IconSize);
e.Graphics.FillEllipse(new SolidBrush(Color.Yellow), x + s, y + s, IconSize, IconSize);
}
}
}
|
mit
|
C#
|
5a42df47cf2154f437673faf01d7195bf3b6166f
|
Write as separate words
|
jeremycook/PickupMailViewer,jeremycook/PickupMailViewer
|
PickupMailViewer/Controllers/HomeController.cs
|
PickupMailViewer/Controllers/HomeController.cs
|
using PickupMailViewer.Helpers;
using PickupMailViewer.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace PickupMailViewer.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(GetMailListModel());
}
public ActionResult FileList()
{
return View(GetMailListModel());
}
private static IOrderedEnumerable<MailModel> GetMailListModel()
{
var mailPaths = MailHelper.ListMailFiles(Properties.Settings.Default.MailDir);
var mails = mailPaths.Select(path => new MailModel(path)).OrderByDescending(m => m.SentOn);
return mails;
}
public FileResult DownloadMail(string mailId)
{
if (mailId.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > 0)
{
throw new ArgumentException("Invalid characters in mailId", "mailId");
}
var filePath = Path.Combine(Properties.Settings.Default.MailDir, mailId);
if (!MailHelper.ListMailFiles(Properties.Settings.Default.MailDir).Contains(filePath))
{
throw new ArgumentException("mailId is not in white list", "mailId");
}
var result = new FileStreamResult(new FileStream(filePath, FileMode.Open), "message/rfc822");
result.FileDownloadName = mailId;
return result;
}
[OutputCache(Location = OutputCacheLocation.Downstream, VaryByParam = "mailId", Duration = 3600 * 24 * 7)] // No need to output cache on the server since the mail content is cached internally anyway
public ActionResult GetMailDetails(string mailId)
{
if (mailId.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > 0)
{
throw new ArgumentException("Invalid characters in mailId", "mailId");
}
var filePath = Path.Combine(Properties.Settings.Default.MailDir, mailId);
if (!MailHelper.ListMailFiles(Properties.Settings.Default.MailDir).Contains(filePath))
{
throw new ArgumentException("mailId is not in while list", "mailId");
}
return PartialView(new MailModel(filePath));
}
}
}
|
using PickupMailViewer.Helpers;
using PickupMailViewer.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace PickupMailViewer.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(GetMailListModel());
}
public ActionResult FileList()
{
return View(GetMailListModel());
}
private static IOrderedEnumerable<MailModel> GetMailListModel()
{
var mailPaths = MailHelper.ListMailFiles(Properties.Settings.Default.MailDir);
var mails = mailPaths.Select(path => new MailModel(path)).OrderByDescending(m => m.SentOn);
return mails;
}
public FileResult DownloadMail(string mailId)
{
if (mailId.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > 0)
{
throw new ArgumentException("Invalid characters in mailId", "mailId");
}
var filePath = Path.Combine(Properties.Settings.Default.MailDir, mailId);
if (!MailHelper.ListMailFiles(Properties.Settings.Default.MailDir).Contains(filePath))
{
throw new ArgumentException("mailId is not in white list", "mailId");
}
var result = new FileStreamResult(new FileStream(filePath, FileMode.Open), "message/rfc822");
result.FileDownloadName = mailId;
return result;
}
[OutputCache(Location = OutputCacheLocation.Downstream, VaryByParam = "mailId", Duration = 3600 * 24 * 7)] // No need to output cache on the server since the mailcontent is cached internally anyway
public ActionResult GetMailDetails(string mailId)
{
if (mailId.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > 0)
{
throw new ArgumentException("Invalid characters in mailId", "mailId");
}
var filePath = Path.Combine(Properties.Settings.Default.MailDir, mailId);
if (!MailHelper.ListMailFiles(Properties.Settings.Default.MailDir).Contains(filePath))
{
throw new ArgumentException("mailId is not in while list", "mailId");
}
return PartialView(new MailModel(filePath));
}
}
}
|
mit
|
C#
|
14666322e1f82c74ea0b4bec69b07092a014b600
|
Check for null values.
|
bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes
|
Orchard.Source.1.8.1/src/Orchard.Web/Themes/LccNetwork.Bootstrap/Views/ProjectionWidgetWorkItemCarousel.cshtml
|
Orchard.Source.1.8.1/src/Orchard.Web/Themes/LccNetwork.Bootstrap/Views/ProjectionWidgetWorkItemCarousel.cshtml
|
@using Orchard.ContentManagement;
@using LccNetwork.Bootstrap.Extensions;
@{
var contentItems = Model.ContentItems;
var carouselUniqueId = Guid.NewGuid().ToString();
var items = new List<dynamic>();
var processedWorkAreas = new List<string>();
foreach (var contentItem in contentItems)
{
// work area
dynamic workItemPart = contentItem.WorkItem;
var workArea = workItemPart != null && workItemPart.Area != null && workItemPart.Area.Terms != null && workItemPart.Area.Terms.Count > 0 ?
workItemPart.Area.Terms[0] : null;
// media part
var mediaPart = MyFunctions.GetMediaPartFromMediaLibraryPickerField(workItemPart.Image);
// create a bag of properties
// consider refactoring this into a ViewModel
var item = new
{
WorkArea = new
{
Term = workArea != null ? workArea.Name : string.Empty,
Slug = workArea != null ? workArea.Slug : string.Empty
},
WorkItem = new
{
Summary = workItemPart != null && workItemPart.Summary != null ? workItemPart.Summary.Value : string.Empty,
Slug = Url.ItemDisplayUrl((IContent)contentItem)
},
Img = new
{
Alt = mediaPart != null ? mediaPart.AlternateText : null,
Src = mediaPart != null ? mediaPart.MediaUrl : null
}
};
// ensure no properties are null
if (item.WorkArea.Term == null || item.WorkArea.Slug == null || item.WorkItem.Summary == null ||
item.WorkArea.Slug == null || item.Img.Alt == null || item.Img.Src == null)
{
continue;
}
// ensure that we only display one item per work area
if (processedWorkAreas.Any(s => s.Equals(item.WorkArea.Term)))
{
continue;
}
processedWorkAreas.Add(item.WorkArea.Term);
items.Add(item);
}
}
<div id="@carouselUniqueId" class="carousel slide" data-ride="carousel">
@* Note: We may tweak the indicator width and item width in CSS. *@
@Display.CarouselIndicators(CarouselItems: items, CarouselId: carouselUniqueId, IndicatorWidth: 200)
@Display.CarouselInner(CarouselItems: items, CarouselId: carouselUniqueId, ItemWidth: 735)
</div>
|
@using Orchard.ContentManagement;
@using LccNetwork.Bootstrap.Extensions;
@{
var contentItems = Model.ContentItems;
var carouselUniqueId = Guid.NewGuid().ToString();
var items = new List<dynamic>();
var processedWorkAreas = new List<string>();
foreach (var contentItem in contentItems)
{
// work area
dynamic workItemPart = contentItem.WorkItem;
var workArea = workItemPart != null && workItemPart.Area != null && workItemPart.Area.Terms != null && workItemPart.Area.Terms.Length > 0 ?
workItemPart.Area.Terms[0] : string.Empty;
// media part
var mediaPart = MyFunctions.GetMediaPartFromMediaLibraryPickerField(workItemPart.Image);
// create a bag of properties
// consider refactoring this into a ViewModel
var item = new
{
WorkArea = new
{
Term = workArea.Name,
Slug = workArea.Slug
},
WorkItem = new
{
Summary = workItemPart.Summary.Value,
Slug = Url.ItemDisplayUrl((IContent)contentItem)
},
Img = new
{
Alt = mediaPart != null ? mediaPart.AlternateText : null,
Src = mediaPart != null ? mediaPart.MediaUrl : null
}
};
// ensure no properties are null
if (item.WorkArea.Term == null || item.WorkArea.Slug == null || item.WorkItem.Summary == null ||
item.WorkArea.Slug == null || item.Img.Alt == null || item.Img.Src == null)
{
continue;
}
// ensure that we only display one item per work area
if (processedWorkAreas.Any(s => s.Equals(item.WorkArea.Term)))
{
continue;
}
processedWorkAreas.Add(item.WorkArea.Term);
items.Add(item);
}
}
<div id="@carouselUniqueId" class="carousel slide" data-ride="carousel">
@* Note: We may tweak the indicator width and item width in CSS. *@
@Display.CarouselIndicators(CarouselItems: items, CarouselId: carouselUniqueId, IndicatorWidth: 200)
@Display.CarouselInner(CarouselItems: items, CarouselId: carouselUniqueId, ItemWidth: 735)
</div>
|
bsd-3-clause
|
C#
|
21d99d8d53213b2f068dbbf038b45ff6da22fa52
|
correct regex to remove spaces
|
OlegKleyman/AlphaDev,OlegKleyman/AlphaDev,OlegKleyman/AlphaDev
|
tests/integration/AlphaDev.Web.Tests.Integration/SeleniumNotifier.cs
|
tests/integration/AlphaDev.Web.Tests.Integration/SeleniumNotifier.cs
|
using System.IO;
using System.Text.RegularExpressions;
using LightBDD.Core.Metadata;
using LightBDD.Core.Notification;
using LightBDD.Core.Results;
using OpenQA.Selenium;
namespace AlphaDev.Web.Tests.Integration
{
public class SeleniumNotifier : IScenarioProgressNotifier
{
private readonly ITakesScreenshot _screenshotTaker;
private IScenarioInfo _scenario;
public SeleniumNotifier(ITakesScreenshot screenshotTaker)
{
_screenshotTaker = screenshotTaker;
}
public void NotifyScenarioStart(IScenarioInfo scenario)
{
_scenario = scenario;
}
public void NotifyScenarioFinished(IScenarioResult scenario)
{
}
public void NotifyStepStart(IStepInfo step)
{
TakeScreenshot(step, "1");
}
public void NotifyStepFinished(IStepResult step)
{
TakeScreenshot(step.Info, "2");
}
public void NotifyStepComment(IStepInfo step, string comment)
{
}
private void TakeScreenshot(IStepInfo step, string suffix)
{
if (_screenshotTaker != null)
{
const string screenshotsDirectoryName = "sout";
if (!Directory.Exists(screenshotsDirectoryName))
{
Directory.CreateDirectory(screenshotsDirectoryName);
}
var escapedStepFileName = Regex.Replace(step.Name.ToString(),
$@"[{string.Join(string.Empty, Path.GetInvalidFileNameChars())}|\s]", string.Empty,
RegexOptions.Compiled);
_screenshotTaker.GetScreenshot()
?.SaveAsFile(
$@"{screenshotsDirectoryName}/{_scenario.Name}{step.Number}{escapedStepFileName}{suffix}.png",
ScreenshotImageFormat.Png);
}
}
}
}
|
using System.IO;
using System.Text.RegularExpressions;
using LightBDD.Core.Metadata;
using LightBDD.Core.Notification;
using LightBDD.Core.Results;
using OpenQA.Selenium;
namespace AlphaDev.Web.Tests.Integration
{
public class SeleniumNotifier : IScenarioProgressNotifier
{
private readonly ITakesScreenshot _screenshotTaker;
private IScenarioInfo _scenario;
public SeleniumNotifier(ITakesScreenshot screenshotTaker)
{
_screenshotTaker = screenshotTaker;
}
public void NotifyScenarioStart(IScenarioInfo scenario)
{
_scenario = scenario;
}
public void NotifyScenarioFinished(IScenarioResult scenario)
{
}
public void NotifyStepStart(IStepInfo step)
{
TakeScreenshot(step, "1");
}
public void NotifyStepFinished(IStepResult step)
{
TakeScreenshot(step.Info, "2");
}
public void NotifyStepComment(IStepInfo step, string comment)
{
}
private void TakeScreenshot(IStepInfo step, string suffix)
{
if (_screenshotTaker != null)
{
const string screenshotsDirectoryName = "sout";
if (!Directory.Exists(screenshotsDirectoryName))
{
Directory.CreateDirectory(screenshotsDirectoryName);
}
var escapedStepFileName = Regex.Replace(step.Name.ToString(),
$@"[{string.Join(string.Empty, Path.GetInvalidFileNameChars())}\s]", string.Empty,
RegexOptions.Compiled);
_screenshotTaker.GetScreenshot()
?.SaveAsFile(
$@"{screenshotsDirectoryName}/{_scenario.Name}{step.Number}{escapedStepFileName}{suffix}.png",
ScreenshotImageFormat.Png);
}
}
}
}
|
unlicense
|
C#
|
31503861ac2ba7102bafdbb29c0bf656ff647918
|
Remove hardcoded `/umbraco/` reference
|
imulus/census,imulus/census
|
Src/Census/Configuration.cs
|
Src/Census/Configuration.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Census.Core.Interfaces;
using Census.UmbracoObjectRelations;
using umbraco;
namespace Census.Core
{
public static class Configuration
{
public static List<IRelation> RelationDefinitions
{
get
{
// TODO: Configurable via TypeFinder or otherwise
return new List<IRelation>() { new DataTypeToProperty(), new TemplateToContent(), new TemplateToDocumentType(), new PropertyEditorToDataType(), new MacroToTemplate(), new MacroToContent() };
}
}
public static List<IRelation> GetRelationsByPagePath(string pagePath)
{
return
Configuration.RelationDefinitions.Where(
x => x.PagePath.Any(pp => pp.ToLower() == pagePath.ToLower().Replace(UmbracoDirectory.ToLower(), string.Empty))).ToList();
}
public static string UmbracoDirectory
{
get
{
return GlobalSettings.Path;
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Census.Core.Interfaces;
using Census.UmbracoObjectRelations;
namespace Census.Core
{
public static class Configuration
{
public static List<IRelation> RelationDefinitions
{
get
{
// TODO: Configurable via TypeFinder or otherwise
return new List<IRelation>() { new DataTypeToProperty(), new TemplateToContent(), new TemplateToDocumentType(), new PropertyEditorToDataType(), new MacroToTemplate(), new MacroToContent() };
}
}
public static List<IRelation> GetRelationsByPagePath(string pagePath)
{
return
Configuration.RelationDefinitions.Where(
x => x.PagePath.Any(pp => pp.ToLower() == pagePath.ToLower().Replace("/umbraco/", "/"))).ToList();
}
}
}
|
mit
|
C#
|
d9a7ba71ef03e7f6c93ae9351b3ba608aebf1b54
|
Update Vector2.cs
|
elacy/PopulationSimulator
|
PopSim.Logic/Vector2.cs
|
PopSim.Logic/Vector2.cs
|
using System;
namespace PopSim.Logic
{
public class Vector2
{
public Vector2(double x, double y)
{
X = x;
Y = y;
IsZero = Math.Abs(x) < double.Epsilon && Math.Abs(y) < double.Epsilon;
}
public bool IsZero { get; private set; }
public double X { get; private set; }
public double Y { get; private set; }
public Vector2 Add(Vector2 vector2)
{
return new Vector2(X + vector2.X,Y + vector2.Y);
}
public double GetDistance(Vector2 vector2)
{
return Math.Sqrt(Squared(vector2.X - X) + Squared(vector2.Y - Y));
}
private static double Squared(double value)
{
return Math.Pow(value, 2);
}
public double AngleBetween(Vector2 vector2)
{
return Math.Atan2(vector2.Y - Y, vector2.X - X);
}
public Vector2 GetVelocity(Vector2 destination)
{
var angle = AngleBetween(destination);
return new Vector2(Math.Cos(angle),Math.Sin(angle));
}
public Vector2 ScalarMultiply(double multiplier)
{
return new Vector2(X*multiplier,Y*multiplier);
}
public double VectorMagnitude()
{
return Math.Sqrt(X*X + Y*Y);
}
}
}
|
using System;
namespace PopSim.Logic
{
public class Vector2
{
public Vector2(double x, double y)
{
X = x;
Y = y;
IsZero = Math.Abs(x) < double.Epsilon && Math.Abs(y) < double.Epsilon;
}
public bool IsZero { get; private set; }
public double X { get; private set; }
public double Y { get; private set; }
public Vector2 Add(Vector2 vector2)
{
return new Vector2(X + vector2.X,Y + vector2.Y);
}
public double GetDistance(Vector2 vector2)
{
return Math.Sqrt(Squared(vector2.X - X) + Squared(vector2.Y - Y));
}
private static double Squared(double value)
{
return Math.Pow(value, 2);
}
public double AngleBetween(Vector2 vector2)
{
return Math.Atan2(vector2.Y - Y, vector2.X - X);
}
public Vector2 GetVelocity(Vector2 destination, double speed)
{
var angle = AngleBetween(destination);
return new Vector2(Math.Cos(angle) * speed,Math.Sin(angle) * speed);
}
}
}
|
mit
|
C#
|
3fa615807254e08fec27dc8b8400a9791ac4157c
|
Change starting point.
|
EusthEnoptEron/Sketchball
|
Sketchball/Program.cs
|
Sketchball/Program.cs
|
using Sketchball.Controls;
using Sketchball.Elements;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sketchball
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Form f = new Form();
//PinballControl2 pinball = new PinballControl2();
//f.Controls.Add(pinball);
//pinball.Dock = DockStyle.Fill;
//f.Width = 500;
//f.Height = 500;
Application.Run(new SelectionForm());
//Application.Run(new PlayForm(new PinballMachine()) { Width = 800, Height = 700 });
}
}
}
|
using Sketchball.Controls;
using Sketchball.Elements;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sketchball
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Form f = new Form();
//PinballControl2 pinball = new PinballControl2();
//f.Controls.Add(pinball);
//pinball.Dock = DockStyle.Fill;
//f.Width = 500;
//f.Height = 500;
//Application.Run(new SelectionForm());
Application.Run(new PlayForm(new PinballMachine()) { Width = 800, Height = 700 });
}
}
}
|
mit
|
C#
|
a9670d4b354de301947bd6237f1443e7ecc2fe32
|
Add delegate extensions
|
insthync/LiteNetLibManager,insthync/LiteNetLibManager
|
Scripts/LiteNetLibDelegates.cs
|
Scripts/LiteNetLibDelegates.cs
|
using Cysharp.Threading.Tasks;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public delegate void MessageHandlerDelegate(MessageHandlerData messageHandler);
public delegate void RequestProceedResultDelegate<TResponse>(AckResponseCode responseCode, TResponse response, SerializerDelegate responseExtraSerializer = null)
where TResponse : INetSerializable;
public delegate void RequestProceededDelegate(long connectionId, uint requestId, AckResponseCode responseCode, INetSerializable response, SerializerDelegate responseSerializer);
public delegate UniTaskVoid RequestDelegate<TRequest, TResponse>(RequestHandlerData requestHandler, TRequest request, RequestProceedResultDelegate<TResponse> responseProceedResult)
where TRequest : INetSerializable
where TResponse : INetSerializable;
public delegate void ResponseDelegate<TResponse>(ResponseHandlerData requestHandler, AckResponseCode responseCode, TResponse response)
where TResponse : INetSerializable;
public delegate void SerializerDelegate(NetDataWriter writer);
public delegate void NetFunctionDelegate();
public delegate void NetFunctionDelegate<T1>(T1 param1);
public delegate void NetFunctionDelegate<T1, T2>(T1 param1, T2 param2);
public delegate void NetFunctionDelegate<T1, T2, T3>(T1 param1, T2 param2, T3 param3);
public delegate void NetFunctionDelegate<T1, T2, T3, T4>(T1 param1, T2 param2, T3 param3, T4 param4);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6, T7>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6, T7, T8>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9, T10 param10);
public static class DelegateExtensions
{
public static void InvokeSuccess<TResponse>(this RequestProceedResultDelegate<TResponse> target, TResponse response, SerializerDelegate responseExtraSerializer = null)
where TResponse : INetSerializable
{
target.Invoke(AckResponseCode.Success, response, responseExtraSerializer);
}
public static void InvokeError<TResponse>(this RequestProceedResultDelegate<TResponse> target, TResponse response, SerializerDelegate responseExtraSerializer = null)
where TResponse : INetSerializable
{
target.Invoke(AckResponseCode.Error, response, responseExtraSerializer);
}
}
}
|
using Cysharp.Threading.Tasks;
using LiteNetLib.Utils;
namespace LiteNetLibManager
{
public delegate void MessageHandlerDelegate(MessageHandlerData messageHandler);
public delegate void RequestProceedResultDelegate<TResponse>(AckResponseCode responseCode, TResponse response, SerializerDelegate responseExtraSerializer = null)
where TResponse : INetSerializable;
public delegate void RequestProceededDelegate(long connectionId, uint requestId, AckResponseCode responseCode, INetSerializable response, SerializerDelegate responseSerializer);
public delegate UniTaskVoid RequestDelegate<TRequest, TResponse>(RequestHandlerData requestHandler, TRequest request, RequestProceedResultDelegate<TResponse> responseProceedResult)
where TRequest : INetSerializable
where TResponse : INetSerializable;
public delegate void ResponseDelegate<TResponse>(ResponseHandlerData requestHandler, AckResponseCode responseCode, TResponse response)
where TResponse : INetSerializable;
public delegate void SerializerDelegate(NetDataWriter writer);
public delegate void NetFunctionDelegate();
public delegate void NetFunctionDelegate<T1>(T1 param1);
public delegate void NetFunctionDelegate<T1, T2>(T1 param1, T2 param2);
public delegate void NetFunctionDelegate<T1, T2, T3>(T1 param1, T2 param2, T3 param3);
public delegate void NetFunctionDelegate<T1, T2, T3, T4>(T1 param1, T2 param2, T3 param3, T4 param4);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6, T7>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6, T7, T8>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9);
public delegate void NetFunctionDelegate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 param1, T2 param2, T3 param3, T4 param4, T5 param5, T6 param6, T7 param7, T8 param8, T9 param9, T10 param10);
}
|
mit
|
C#
|
35c250c74aef99f5d5d8f656caa3f307f39adbb2
|
Make it create game log.
|
AIWolfSharp/AIWolf_NET
|
ServerStarter/ServerStarter.cs
|
ServerStarter/ServerStarter.cs
|
//
// ServerStarter.cs
//
// Copyright (c) 2016 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using AIWolf.Lib;
using System;
namespace AIWolf.Server
{
class ServerStarter
{
public static void Main(string[] args)
{
int port = 10000;
int agentNum = 12;
for (int i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("-"))
{
if (args[i].Equals("-p"))
{
i++;
port = int.Parse(args[i]);
}
else if (args[i].Equals("-n"))
{
i++;
agentNum = int.Parse(args[i]);
}
}
}
Console.WriteLine("Start AIWolf Server port:{0} playerNum:{1}", port, agentNum);
GameSetting gameSetting = GameSetting.GetDefaultGameSetting(agentNum);
TcpipServer server = new TcpipServer(port, agentNum, gameSetting);
server.WaitForConnection();
AIWolfGame game = new AIWolfGame(gameSetting, server);
game.GameLogger = new FileGameLogger(".");
game.Rand = new Random();
game.Start();
}
}
}
|
//
// ServerStarter.cs
//
// Copyright (c) 2016 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using AIWolf.Lib;
using System;
using System.Threading.Tasks;
namespace AIWolf.Server
{
class ServerStarter
{
public static void Main(string[] args)
{
int port = 10000;
int agentNum = 12;
for (int i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("-"))
{
if (args[i].Equals("-p"))
{
i++;
port = int.Parse(args[i]);
}
else if (args[i].Equals("-n"))
{
i++;
agentNum = int.Parse(args[i]);
}
}
}
Console.WriteLine("Start AIWolf Server port:{0} playerNum:{1}", port, agentNum);
GameSetting gameSetting = GameSetting.GetDefaultGameSetting(agentNum);
TcpipServer server = new TcpipServer(port, agentNum, gameSetting);
server.WaitForConnection();
AIWolfGame game = new AIWolfGame(gameSetting, server);
game.Rand = new Random();
game.Start();
}
}
}
|
mit
|
C#
|
bb8c2080ec732df11f9a8cdc2d3b700afd9a1269
|
Update OctokitEx.cs
|
Particular/SyncOMatic
|
src/GitHubSync/OctokitEx.cs
|
src/GitHubSync/OctokitEx.cs
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Octokit;
public static class OctokitEx
{
public static async Task<List<string>> GetRecursive(Credentials credentials, string sourceOwner, string sourceRepository, string path = null)
{
var items = new List<string>();
await GetRecursive(credentials, sourceOwner, sourceRepository, path, items);
return items;
}
static Task GetRecursive(Credentials credentials, string sourceOwner, string sourceRepository, string path, List<string> items)
{
var client = new GitHubClient(new ProductHeaderValue("GitHubSync"));
if (credentials != null)
{
client.Credentials = credentials;
}
return GetRecursive(client, sourceOwner, sourceRepository, path, items);
}
static async Task GetRecursive(GitHubClient client, string sourceOwner, string sourceRepository, string path, List<string> items)
{
foreach (var content in await client.Repository.Content.GetAllContentsEx(sourceOwner, sourceRepository, path))
{
var contentPath = content.Path;
if (content.Type.Value == ContentType.File)
{
items.Add(contentPath);
}
if (content.Type.Value == ContentType.Dir)
{
await GetRecursive(client, sourceOwner, sourceRepository, contentPath, items);
}
}
}
static Task<IReadOnlyList<RepositoryContent>> GetAllContentsEx(this IRepositoryContentsClient content, string owner, string repo, string path = null, string branch = null)
{
if (branch == null)
{
if (path != null)
{
return content.GetAllContents(owner, repo, path);
}
return content.GetAllContents(owner, repo);
}
if (path != null)
{
return content.GetAllContentsByRef(owner, repo, path, reference: branch);
}
return content.GetAllContentsByRef(owner, repo, reference: branch);
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Octokit;
public static class OctokitEx
{
public static async Task<List<string>> GetRecursive(Credentials credentials, string sourceOwner, string sourceRepository, string path = null)
{
var items = new List<string>();
await GetRecursive(credentials, sourceOwner, sourceRepository, path, items);
return items;
}
static async Task GetRecursive(Credentials credentials, string sourceOwner, string sourceRepository, string path, List<string> items)
{
var client = new GitHubClient(new ProductHeaderValue("GitHubSync"));
if (credentials != null)
{
client.Credentials = credentials;
}
await GetRecursive(client, sourceOwner, sourceRepository, path, items);
}
static async Task GetRecursive(GitHubClient client, string sourceOwner, string sourceRepository, string path, List<string> items)
{
foreach (var content in await client.Repository.Content.GetAllContentsEx(sourceOwner, sourceRepository, path))
{
var contentPath = content.Path;
if (content.Type.Value == ContentType.File)
{
items.Add(contentPath);
}
if (content.Type.Value == ContentType.Dir)
{
await GetRecursive(client, sourceOwner, sourceRepository, contentPath, items);
}
}
}
static Task<IReadOnlyList<RepositoryContent>> GetAllContentsEx(this IRepositoryContentsClient content, string owner, string repo, string path = null, string branch = null)
{
if (branch == null)
{
if (path != null)
{
return content.GetAllContents(owner, repo, path);
}
return content.GetAllContents(owner, repo);
}
if (path != null)
{
return content.GetAllContentsByRef(owner, repo, path, reference: branch);
}
return content.GetAllContentsByRef(owner, repo, reference: branch);
}
}
|
mit
|
C#
|
0dc422c2d9206830c32fe9ca6a32f7518fe63757
|
Fix type in Range attribute: change from double to int
|
dariusz-wozniak/TddCourse
|
TddCourse.Tests.Unit/Part08_ParameterizedTests/Parameterized_Range.cs
|
TddCourse.Tests.Unit/Part08_ParameterizedTests/Parameterized_Range.cs
|
using NUnit.Framework;
using TddCourse.CalculatorExample;
namespace TddCourse.Tests.Unit.Part08_ParameterizedTests
{
public class Parameterized_Range
{
[Test]
public void Divide_DividendIsZero_ReturnsQuotientEqualToZero(
[Range(@from: 1, to: 5, step: 1)] int divisor)
{
var calc = new Calculator();
float quotient = calc.Divide(0, divisor);
Assert.AreEqual(0, quotient);
}
}
}
|
using NUnit.Framework;
using TddCourse.CalculatorExample;
namespace TddCourse.Tests.Unit.Part08_ParameterizedTests
{
public class Parameterized_Range
{
[Test]
public void Divide_DividendIsZero_ReturnsQuotientEqualToZero(
[Range(@from: 1, to: 5, step: 1)] double divisor)
{
var calc = new Calculator();
float quotient = calc.Divide(0, divisor);
Assert.AreEqual(0, quotient);
}
}
}
|
mit
|
C#
|
89c6afc757900b044152902257149be6f025a1bd
|
Update AppSettings.cs
|
Microsoft/HealthClinic.biz,Microsoft/HealthClinic.biz,Microsoft/HealthClinic.biz,Microsoft/HealthClinic.biz,Microsoft/HealthClinic.biz,Microsoft/HealthClinic.biz,Microsoft/HealthClinic.biz
|
src/MyHealth.Client.Core/AppSettings.cs
|
src/MyHealth.Client.Core/AppSettings.cs
|
using System;
namespace MyHealth.Client.Core
{
public static class AppSettings
{
public static string ServerlUrl = "http://YOUR_WEB.azurewebsites.net/";
public static string MobileAPIUrl = "https://YOUR_WEB_MOBILE.azurewebsites.net";
public static int DefaultPatientId = __YOUR_PATIENT_ID__;
public static int CurrentPatientId = __YOUR_PATIENT_ID__;
public static int DefaultTenantId = __YOUR_TENANT_ID__;
public static string DefaultAppointmentDescription = "Follow up in order to determine the effectiveness of treatment received";
public static int MinimumRoomNumber = 1;
public static int MaximumRoomNumber = 10;
public static string NonExistingFieldDefaultValue = "-";
// HockeyApp AppId
public static string HockeyAppiOSAppID = "YOUR_HOCKEY_APP_ID";
public static string iOSAppGroupIdentifier = "group.app.client.patients";
public static string iOSAppGroupDirectory = "messageDir";
public static bool OutlookIntegration = false;
public static SecuritySettings Security
{
get
{
if (OutlookIntegration)
return OutlookSettings;
else
return AADSettings;
}
}
static SecuritySettings AADSettings = new SecuritySettings()
{
ClientId = "YOUR_AAD_CLIENT_ID",
RedirectUri = new Uri("YOUR_AAD_REDIRECT_URI"),
Authority = "YOUR_AAD_AUTHORITY",
Scope = "https://graph.microsoft.com",
Domain = "YOUR_AAD_DOMAIN"
};
static SecuritySettings OutlookSettings = new SecuritySettings()
{
ClientId = "YOUR_OUTLOOK_CLIENT_ID",
RedirectUri = new Uri("YOUR_OUTLOOK_REDIRECT_URI"),
Authority = "YOUR_OUTLOOK_AUTHORITY",
Scope = "https://graph.microsoft.com/calendars.readwrite",
Domain = "YOUR_OUTLOOK_DOMAIN"
};
}
public class SecuritySettings
{
public string ClientId { get; set; }
public Uri RedirectUri { get; set; }
public string Authority { get; set; }
public string Scope { get; set; }
public string Domain { get; set; }
}
}
|
using System;
namespace MyHealth.Client.Core
{
public static class AppSettings
{
public static string ServerlUrl = "http://YOUR_WEB.azurewebsites.net/";
public static string MobileAPIUrl = "https://YOUR_WEB_MOBILE.azurewebsites.net";
public static int DefaultPatientId = YOUR_PATIENT_ID;
public static int CurrentPatientId = YOUR_PATIENT_ID;
public static int DefaultTenantId = YOUR_TENANT_ID;
public static string DefaultAppointmentDescription = "Follow up in order to determine the effectiveness of treatment received";
public static int MinimumRoomNumber = 1;
public static int MaximumRoomNumber = 10;
public static string NonExistingFieldDefaultValue = "-";
// HockeyApp AppId
public static string HockeyAppiOSAppID = "YOUR_HOCKEY_APP_ID";
public static string iOSAppGroupIdentifier = "group.app.client.patients";
public static string iOSAppGroupDirectory = "messageDir";
public static bool OutlookIntegration = false;
public static SecuritySettings Security
{
get
{
if (OutlookIntegration)
return OutlookSettings;
else
return AADSettings;
}
}
static SecuritySettings AADSettings = new SecuritySettings()
{
ClientId = "YOUR_AAD_CLIENT_ID",
RedirectUri = new Uri("YOUR_AAD_REDIRECT_URI"),
Authority = "YOUR_AAD_AUTHORITY",
Scope = "https://graph.microsoft.com",
Domain = "YOUR_AAD_DOMAIN"
};
static SecuritySettings OutlookSettings = new SecuritySettings()
{
ClientId = "YOUR_OUTLOOK_CLIENT_ID",
RedirectUri = new Uri("YOUR_OUTLOOK_REDIRECT_URI"),
Authority = "YOUR_OUTLOOK_AUTHORITY",
Scope = "https://graph.microsoft.com/calendars.readwrite",
Domain = "YOUR_OUTLOOK_DOMAIN"
};
}
public class SecuritySettings
{
public string ClientId { get; set; }
public Uri RedirectUri { get; set; }
public string Authority { get; set; }
public string Scope { get; set; }
public string Domain { get; set; }
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.