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
1d0924116e7e1096f18bfc6fc47267dbd059c3c2
use github api key in cocoapods
bholmes/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
Util/VersionChecker/common/CocoaPods.csx
Util/VersionChecker/common/CocoaPods.csx
#load "VersionFetcher.csx" using Newtonsoft.Json.Linq; using Semver; public class CocoaPods : VersionFetcher { public CocoaPods (string component, string version, string podId, string owner) : base (component, version, owner) { PodId = podId; } public string PodId { get; private set; } public override string FetchNewestAvailableVersion () { // CocoaPods moved to using a folder prefix in their Specs repo in order to avoid // having all the specs in a single directory // The formula is the first 3 chars of the md5 value of the Pod ID // where each of the 3 letters is a folder/subfolder/subsubfolder // So we'll hash the PodID, and construct the path using this formula var podIdBytes = System.Text.Encoding.Default.GetBytes (PodId); var podIdMd5 = string.Empty; using (var md5 = System.Security.Cryptography.MD5.Create ()) { podIdMd5 = System.BitConverter.ToString (md5.ComputeHash (podIdBytes)).Replace ("-", "").ToLowerInvariant (); } var podIdPath = podIdMd5[0] + "/" + podIdMd5[1] + "/" + podIdMd5[2] + "/" + PodId; var http = new HttpClient (); http.DefaultRequestHeaders.UserAgent.ParseAdd ("Xamarin-Internal/1.0"); var tree = string.Format ("master:Specs/{0}", podIdPath); //Console.WriteLine ("https://api.github.com/repos/{0}/{1}/git/trees/{2}", "CocoaPods", "Specs", tree); var url = string.Format ("https://api.github.com/repos/{0}/{1}/git/trees/{2}", "CocoaPods", "Specs", System.Net.WebUtility.UrlEncode (tree)); if (!string.IsNullOrEmpty (githubClientId) && !string.IsNullOrEmpty (githubClientSecret)) url += "?client_id=" + githubClientId + "&client_secret=" + githubClientSecret; var data = http.GetStringAsync (url).Result; var json = JObject.Parse (data); var items = json["tree"] as JArray; var highestVersion = SemVersion.Parse ("0.0.0"); foreach (var item in items) { var path = item["path"].ToString (); try { var v = SemVersion.Parse (path); if (v > highestVersion) highestVersion = v; } catch { } } return highestVersion.ToString (); } }
#load "VersionFetcher.csx" using Newtonsoft.Json.Linq; using Semver; public class CocoaPods : VersionFetcher { public CocoaPods (string component, string version, string podId, string owner) : base (component, version, owner) { PodId = podId; } public string PodId { get; private set; } public override string FetchNewestAvailableVersion () { // CocoaPods moved to using a folder prefix in their Specs repo in order to avoid // having all the specs in a single directory // The formula is the first 3 chars of the md5 value of the Pod ID // where each of the 3 letters is a folder/subfolder/subsubfolder // So we'll hash the PodID, and construct the path using this formula var podIdBytes = System.Text.Encoding.Default.GetBytes (PodId); var podIdMd5 = string.Empty; using (var md5 = System.Security.Cryptography.MD5.Create ()) { podIdMd5 = System.BitConverter.ToString (md5.ComputeHash (podIdBytes)).Replace ("-", "").ToLowerInvariant (); } var podIdPath = podIdMd5[0] + "/" + podIdMd5[1] + "/" + podIdMd5[2] + "/" + PodId; var http = new HttpClient (); http.DefaultRequestHeaders.UserAgent.ParseAdd ("Xamarin-Internal/1.0"); var tree = string.Format ("master:Specs/{0}", podIdPath); //Console.WriteLine ("https://api.github.com/repos/{0}/{1}/git/trees/{2}", "CocoaPods", "Specs", tree); var url = string.Format ("https://api.github.com/repos/{0}/{1}/git/trees/{2}", "CocoaPods", "Specs", System.Net.WebUtility.UrlEncode (tree)); var data = http.GetStringAsync (url).Result; var json = JObject.Parse (data); var items = json["tree"] as JArray; var highestVersion = SemVersion.Parse ("0.0.0"); foreach (var item in items) { var path = item["path"].ToString (); try { var v = SemVersion.Parse (path); if (v > highestVersion) highestVersion = v; } catch { } } return highestVersion.ToString (); } }
mit
C#
849bf46d6f00935b657e642be09eeb9b2e6ad8ca
Update ObservableObject.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D.Core/ObservableObject.cs
src/Draw2D.Core/ObservableObject.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Runtime.CompilerServices; namespace Draw2D.Core { public abstract class ObservableObject : INotifyPropertyChanged { public bool IsDirty { get; set; } public event PropertyChangedEventHandler PropertyChanged; public void Notify([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!Equals(field, value)) { field = value; IsDirty = true; Notify(propertyName); return true; } return false; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Runtime.CompilerServices; namespace Draw2D.Core { public abstract class ObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void Notify([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!Equals(field, value)) { field = value; Notify(propertyName); return true; } return false; } } }
mit
C#
171e8c0eac72361802ea2cc07f6d68d163d0d81f
tweak window sizes to make interop tests pass (#154)
grpc/grpc-dotnet,grpc/grpc-dotnet,grpc/grpc-dotnet,grpc/grpc-dotnet
testassets/InteropTestsWebsite/Program.cs
testassets/InteropTestsWebsite/Program.cs
#region Copyright notice and license // Copyright 2019 The gRPC 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. #endregion using System.Runtime.InteropServices; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; namespace InteropTestsWebsite { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureKestrel((context, options) => { // Support --port and --use_tls cmdline arguments normally supported // by gRPC interop servers. int port = context.Configuration.GetValue<int>("port", 50052); bool useTls = context.Configuration.GetValue<bool>("use_tls", false); options.Limits.MinRequestBodyDataRate = null; options.ListenAnyIP(port, listenOptions => { if (useTls) { listenOptions.UseHttps(Resources.ServerPFXPath, "1111"); } listenOptions.Protocols = HttpProtocols.Http2; }); // Tweak flow control options to make large_unary test pass. // TODO(jtattermusch): remove this hack once https://github.com/aspnet/AspNetCore/pull/8200 // is fixed. options.Limits.Http2.InitialConnectionWindowSize = 4 * 1024 * 1024; options.Limits.Http2.InitialStreamWindowSize = 4 * 1024 * 1024; }) .UseStartup<Startup>(); } }
#region Copyright notice and license // Copyright 2019 The gRPC 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. #endregion using System.Runtime.InteropServices; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; namespace InteropTestsWebsite { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureKestrel((context, options) => { // Support --port and --use_tls cmdline arguments normally supported // by gRPC interop servers. int port = context.Configuration.GetValue<int>("port", 50052); bool useTls = context.Configuration.GetValue<bool>("use_tls", false); options.Limits.MinRequestBodyDataRate = null; options.ListenAnyIP(port, listenOptions => { if (useTls) { listenOptions.UseHttps(Resources.ServerPFXPath, "1111"); } listenOptions.Protocols = HttpProtocols.Http2; }); }) .UseStartup<Startup>(); } }
apache-2.0
C#
5cef2f8474cad62fbb54cd3c460b271e71018721
make sure to propagate query string and fragment when constructing request URI
WorldWideTelescope/wwt-website,WorldWideTelescope/wwt-website,WorldWideTelescope/wwt-website
src/WWT.Web/AspNetCoreWwtContext.cs
src/WWT.Web/AspNetCoreWwtContext.cs
#nullable disable using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using System; using System.IO; using System.Threading; using System.Threading.Tasks; using WWT.Providers; namespace WWT.Web { public class AspNetCoreWwtContext : IWwtContext, IRequest, IResponse, IHeaders, IParameters { private readonly HttpContext _ctx; private readonly ICache _cache; public AspNetCoreWwtContext(HttpContext ctx, ICache cache) { _ctx = ctx; _cache = cache; } string IParameters.this[string p] => _ctx.Request.Query[p]; string IHeaders.this[string p] => _ctx.Request.Headers[p]; public ICache Cache => _cache; public IRequest Request => this; public IResponse Response => this; public string MachineName => Environment.MachineName; string IResponse.ContentType { get => _ctx.Response.ContentType; set => _ctx.Response.ContentType = value; } int IResponse.StatusCode { get => _ctx.Response.StatusCode; set => _ctx.Response.StatusCode = value; } Stream IResponse.OutputStream => _ctx.Response.Body; IParameters IRequest.Params => this; string IRequest.GetParams(string name) => _ctx.Request.Query[name]; IHeaders IRequest.Headers => this; Uri IRequest.Url => new Uri(_ctx.Request.GetEncodedUrl()); string IRequest.UserAgent => _ctx.Request.Headers["User-Agent"]; Stream IRequest.InputStream => _ctx.Request.Body; void IResponse.AddHeader(string name, string value) => _ctx.Response.Headers.Add(name, value); void IResponse.Clear() { } void IResponse.ClearHeaders() { } void IResponse.Close() { } bool IRequest.ContainsCookie(string name) => _ctx.Request.Cookies.ContainsKey(name); void IResponse.End() { } void IResponse.Flush() { } Task IResponse.WriteAsync(string message, CancellationToken token) => _ctx.Response.WriteAsync(message, token); void IResponse.Redirect(string redirectUri) => _ctx.Response.Redirect(redirectUri); } }
#nullable disable using Microsoft.AspNetCore.Http; using System; using System.IO; using System.Threading; using System.Threading.Tasks; using WWT.Providers; namespace WWT.Web { public class AspNetCoreWwtContext : IWwtContext, IRequest, IResponse, IHeaders, IParameters { private readonly HttpContext _ctx; private readonly ICache _cache; public AspNetCoreWwtContext(HttpContext ctx, ICache cache) { _ctx = ctx; _cache = cache; } string IParameters.this[string p] => _ctx.Request.Query[p]; string IHeaders.this[string p] => _ctx.Request.Headers[p]; public ICache Cache => _cache; public IRequest Request => this; public IResponse Response => this; public string MachineName => Environment.MachineName; string IResponse.ContentType { get => _ctx.Response.ContentType; set => _ctx.Response.ContentType = value; } int IResponse.StatusCode { get => _ctx.Response.StatusCode; set => _ctx.Response.StatusCode = value; } Stream IResponse.OutputStream => _ctx.Response.Body; IParameters IRequest.Params => this; string IRequest.GetParams(string name) => _ctx.Request.Query[name]; IHeaders IRequest.Headers => this; Uri IRequest.Url => new Uri($"{_ctx.Request.Scheme}://{_ctx.Request.Host}{_ctx.Request.Path}"); string IRequest.UserAgent => _ctx.Request.Headers["User-Agent"]; Stream IRequest.InputStream => _ctx.Request.Body; void IResponse.AddHeader(string name, string value) => _ctx.Response.Headers.Add(name, value); void IResponse.Clear() { } void IResponse.ClearHeaders() { } void IResponse.Close() { } bool IRequest.ContainsCookie(string name) => _ctx.Request.Cookies.ContainsKey(name); void IResponse.End() { } void IResponse.Flush() { } Task IResponse.WriteAsync(string message, CancellationToken token) => _ctx.Response.WriteAsync(message, token); void IResponse.Redirect(string redirectUri) => _ctx.Response.Redirect(redirectUri); } }
mit
C#
6d3746e5b9c66f034d65876e982712517b004ba2
Handle unsubscribing
citizenmatt/ndc-london-2013
rx/rx/Program.cs
rx/rx/Program.cs
using System; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace rx { class Program { private static void Main(string[] args) { var wc = new WebClient(); var observable = Bobservable.FromTask(() => wc.DownloadStringTaskAsync("http://www.google.com/robots.txt")); var subscription = observable.Subscribe(new AnonymousBobserver<string>(s => Console.WriteLine(s), () => Console.WriteLine("Done"), exception => Console.WriteLine(exception))); // Wait for the async call Console.ReadLine(); subscription.Dispose(); } } public class Bobservable { public static IBobservable<T> FromTask<T>(Func<Task<T>> taskCreator) { return new AnonymousBobservable<T>(bobserver => { var unsubscribed = false; taskCreator().ContinueWith(t => { if (unsubscribed) return; if (t.IsFaulted) bobserver.OnError(t.Exception); else { bobserver.OnNext(t.Result); bobserver.OnCompleted(); } }); return new Disposable(() => { unsubscribed = true; }); }); } } public class AnonymousBobservable<T> : IBobservable<T> { private readonly Func<IBobserver<T>, IDisposable> onSubscribe; public AnonymousBobservable(Func<IBobserver<T>, IDisposable> onSubscribe) { this.onSubscribe = onSubscribe; } public IDisposable Subscribe(IBobserver<T> observer) { return onSubscribe(observer); } } public interface IBobservable<T> { IDisposable Subscribe(IBobserver<T> observer); } public interface IBobserver<T> { void OnNext(T result); void OnCompleted(); void OnError(Exception exception); } }
using System; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace rx { class Program { private static void Main(string[] args) { var wc = new WebClient(); var observable = Bobservable.FromTask(() => wc.DownloadStringTaskAsync("http://www.google.com/robots.txt")); var subscription = observable.Subscribe(new AnonymousBobserver<string>(s => Console.WriteLine(s), () => Console.WriteLine("Done"), exception => Console.WriteLine(exception))); // Wait for the async call Console.ReadLine(); subscription.Dispose(); } } public class Bobservable { public static IBobservable<T> FromTask<T>(Func<Task<T>> taskCreator) { return new AnonymousBobservable<T>(bobserver => { taskCreator().ContinueWith(t => { if (t.IsFaulted) bobserver.OnError(t.Exception); else { bobserver.OnNext(t.Result); bobserver.OnCompleted(); } }); return new Disposable(() => { }); }); } } public class AnonymousBobservable<T> : IBobservable<T> { private readonly Func<IBobserver<T>, IDisposable> onSubscribe; public AnonymousBobservable(Func<IBobserver<T>, IDisposable> onSubscribe) { this.onSubscribe = onSubscribe; } public IDisposable Subscribe(IBobserver<T> observer) { return onSubscribe(observer); } } public interface IBobservable<T> { IDisposable Subscribe(IBobserver<T> observer); } public interface IBobserver<T> { void OnNext(T result); void OnCompleted(); void OnError(Exception exception); } }
mit
C#
e1464678ce9dc54b3c33a7b7b5a6be806ae02156
Implement marshaling for class types as return types of managed methods.
mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000
binder/Generators/Java/JavaMarshal.cs
binder/Generators/Java/JavaMarshal.cs
using CppSharp.AST; namespace MonoEmbeddinator4000.Generators { public class JavaMarshalPrinter : CMarshalPrinter { public JavaMarshalPrinter(MarshalContext marshalContext) : base(marshalContext) { } } public class JavaMarshalManagedToNative : JavaMarshalPrinter { public JavaMarshalManagedToNative(MarshalContext marshalContext) : base(marshalContext) { } public override bool VisitManagedArrayType(ManagedArrayType array, TypeQualifiers quals) { Context.Return.Write("null"); return true; } public override bool VisitClassDecl(Class @class) { Context.Return.Write($"{Context.ArgName}.__object"); return true; } public override bool VisitEnumDecl(Enumeration @enum) { Context.Return.Write(Context.ArgName); return true; } public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { Context.Return.Write(Context.ArgName); return true; } } public class JavaMarshalNativeToManaged : JavaMarshalPrinter { public JavaMarshalNativeToManaged (MarshalContext marshalContext) : base(marshalContext) { } public override bool VisitManagedArrayType(ManagedArrayType array, TypeQualifiers quals) { Context.Return.Write("null"); return true; } public override bool VisitClassDecl(Class @class) { var typePrinter = new JavaTypePrinter(Context.Context); var typeName = @class.Visit(typePrinter); Context.Return.Write($"new {typeName}({Context.ReturnVarName})"); return true; } public override bool VisitEnumDecl(Enumeration @enum) { Context.Return.Write(Context.ReturnVarName); return true; } public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { Context.Return.Write(Context.ReturnVarName); return true; } } }
using CppSharp.AST; namespace MonoEmbeddinator4000.Generators { public class JavaMarshalPrinter : CMarshalPrinter { public JavaMarshalPrinter(MarshalContext marshalContext) : base(marshalContext) { } } public class JavaMarshalManagedToNative : JavaMarshalPrinter { public JavaMarshalManagedToNative(MarshalContext marshalContext) : base(marshalContext) { } public override bool VisitManagedArrayType(ManagedArrayType array, TypeQualifiers quals) { Context.Return.Write("null"); return true; } public override bool VisitClassDecl(Class @class) { Context.Return.Write($"{Context.ArgName}.__object"); return true; } public override bool VisitEnumDecl(Enumeration @enum) { Context.Return.Write(Context.ArgName); return true; } public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { Context.Return.Write(Context.ArgName); return true; } } public class JavaMarshalNativeToManaged : JavaMarshalPrinter { public JavaMarshalNativeToManaged (MarshalContext marshalContext) : base(marshalContext) { } public override bool VisitManagedArrayType(ManagedArrayType array, TypeQualifiers quals) { Context.Return.Write("null"); return true; } public override bool VisitClassDecl(Class @class) { Context.Return.Write("null"); return true; } public override bool VisitEnumDecl(Enumeration @enum) { Context.Return.Write(Context.ReturnVarName); return true; } public override bool VisitPrimitiveType(PrimitiveType type, TypeQualifiers quals) { Context.Return.Write(Context.ReturnVarName); return true; } } }
mit
C#
2b9437177dc4b4f69c32cc5f5b6e0a3a67741ea4
Add comments.
jcheng31/WundergroundAutocomplete.NET
WundergroundClient/Utilities.cs
WundergroundClient/Utilities.cs
using System; using System.Globalization; namespace WundergroundClient { class Utilities { /// <summary> /// Converts a Unix epoch time string into a DateTime representation. /// </summary> /// <param name="epochTime">String containing the number of seconds since January 1, 1970.</param> /// <returns></returns> public static DateTime GetDateTimeFromUnixEpochTime(string epochTime) { int secondsSince; if (!Int32.TryParse(epochTime, NumberStyles.Integer, CultureInfo.InvariantCulture, out secondsSince)) { throw new ArgumentException("Given String was not a number."); } return GetDateTimeFromUnixEpochTime(secondsSince); } /// <summary> /// Converts Unix epoch time into a DateTime representation. /// </summary> /// <param name="epochTime">The number of seconds since January 1, 1970.</param> /// <returns></returns> public static DateTime GetDateTimeFromUnixEpochTime(int epochTime) { if (epochTime < 0) { throw new ArgumentOutOfRangeException("Unix epoch time must be positive."); } var unixEpochBase = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return unixEpochBase.AddSeconds(epochTime); } } }
using System; using System.Globalization; namespace WundergroundClient { class Utilities { public static DateTime GetDateTimeFromUnixEpochTime(string epochTime) { int secondsSince; if (!Int32.TryParse(epochTime, NumberStyles.Integer, CultureInfo.InvariantCulture, out secondsSince)) { throw new ArgumentException("Given String was not a number."); } return GetDateTimeFromUnixEpochTime(secondsSince); } public static DateTime GetDateTimeFromUnixEpochTime(int epochTime) { if (epochTime < 0) { throw new ArgumentOutOfRangeException("Unix epoch time must be positive."); } var unixEpochBase = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return unixEpochBase.AddSeconds(epochTime); } } }
mit
C#
e0c5e7a77279a348486a3d77356c81b29dd29f8d
remove unused namespace.
jonnii/chinchilla
src/Chinchilla/Depot.cs
src/Chinchilla/Depot.cs
using System; namespace Chinchilla { public class Depot { public static IBus Connect(string connectionString) { var settings = new DepotSettings { ConnectionString = connectionString }; return Connect(settings); } public static IBus Connect(string connectionString, DepotSettings settings) { settings.ConnectionString = connectionString; return Connect(settings); } public static IBus Connect(DepotSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.Validate(); var connectionString = settings.ConnectionString; var connectionFactory = settings.ConnectionFactoryBuilder(); var consumerFactory = settings.ConsumerFactoryBuilder(); var modelFactory = connectionFactory.Create(new Uri(connectionString)); var messageSerializers = settings.MessageSerializers; var bus = new Bus( modelFactory, consumerFactory, new PublisherFactory(messageSerializers), new SubscriptionFactory(modelFactory, messageSerializers)); foreach (var concern in settings.StartupConcerns) { concern.Run(bus); } return bus; } } }
using System; using Chinchilla.Serializers; namespace Chinchilla { public class Depot { public static IBus Connect(string connectionString) { var settings = new DepotSettings { ConnectionString = connectionString }; return Connect(settings); } public static IBus Connect(string connectionString, DepotSettings settings) { settings.ConnectionString = connectionString; return Connect(settings); } public static IBus Connect(DepotSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } settings.Validate(); var connectionString = settings.ConnectionString; var connectionFactory = settings.ConnectionFactoryBuilder(); var consumerFactory = settings.ConsumerFactoryBuilder(); var modelFactory = connectionFactory.Create(new Uri(connectionString)); var messageSerializers = settings.MessageSerializers; var bus = new Bus( modelFactory, consumerFactory, new PublisherFactory(messageSerializers), new SubscriptionFactory(modelFactory, messageSerializers)); foreach (var concern in settings.StartupConcerns) { concern.Run(bus); } return bus; } } }
apache-2.0
C#
3c45f035d54744055c093ca469cce6f20af6594a
Use using for disposable class
ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework.Android/AndroidGameHost.cs
osu.Framework.Android/AndroidGameHost.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Android.App; using Android.Content; using osu.Framework.Android.Graphics.Textures; using osu.Framework.Android.Input; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.IO.Stores; using osu.Framework.Platform; using Uri = Android.Net.Uri; namespace osu.Framework.Android { public class AndroidGameHost : GameHost { private readonly AndroidGameView gameView; public AndroidGameHost(AndroidGameView gameView) { this.gameView = gameView; } protected override void SetupForRun() { base.SetupForRun(); AndroidGameWindow.View = gameView; Window = new AndroidGameWindow(); } protected override bool LimitedMemoryEnvironment => true; public override bool CanExit => false; public override bool OnScreenKeyboardOverlapsGameWindow => true; public override ITextInputSource GetTextInput() => new AndroidTextInput(gameView); protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() => new InputHandler[] { new AndroidKeyboardHandler(gameView), new AndroidTouchHandler(gameView) }; protected override Storage GetStorage(string baseName) => new AndroidStorage(baseName, this); public override void OpenFileExternally(string filename) => throw new NotImplementedException(); public override void OpenUrlExternally(string url) { var activity = (Activity)gameView.Context; using (var intent = new Intent(Intent.ActionView, Uri.Parse(url))) if (intent.ResolveActivity(activity.PackageManager) != null) activity.StartActivity(intent); } public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => new AndroidTextureLoaderStore(underlyingStore); protected override void PerformExit(bool immediately) { // Do not exit on Android, Window.Run() does not block } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Android.App; using Android.Content; using osu.Framework.Android.Graphics.Textures; using osu.Framework.Android.Input; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.Input.Handlers; using osu.Framework.IO.Stores; using osu.Framework.Platform; using Uri = Android.Net.Uri; namespace osu.Framework.Android { public class AndroidGameHost : GameHost { private readonly AndroidGameView gameView; public AndroidGameHost(AndroidGameView gameView) { this.gameView = gameView; } protected override void SetupForRun() { base.SetupForRun(); AndroidGameWindow.View = gameView; Window = new AndroidGameWindow(); } protected override bool LimitedMemoryEnvironment => true; public override bool CanExit => false; public override bool OnScreenKeyboardOverlapsGameWindow => true; public override ITextInputSource GetTextInput() => new AndroidTextInput(gameView); protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() => new InputHandler[] { new AndroidKeyboardHandler(gameView), new AndroidTouchHandler(gameView) }; protected override Storage GetStorage(string baseName) => new AndroidStorage(baseName, this); public override void OpenFileExternally(string filename) => throw new NotImplementedException(); public override void OpenUrlExternally(string url) { var activity = (Activity)gameView.Context; Uri webpage = Uri.Parse(url); Intent intent = new Intent(Intent.ActionView, webpage); if (intent.ResolveActivity(activity.PackageManager) != null) activity.StartActivity(intent); } public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => new AndroidTextureLoaderStore(underlyingStore); protected override void PerformExit(bool immediately) { // Do not exit on Android, Window.Run() does not block } } }
mit
C#
c6ead2bdc7e24d9e3f800946de354f2bf09cd3bb
Update "Database"
DRFP/Personal-Library
_Build/PersonalLibrary/Library/Database.cs
_Build/PersonalLibrary/Library/Database.cs
using Library.Model; using System.Collections.Generic; namespace Library { public class Database { public static List<Shelf> Shelves() { var shelves = new List<Shelf>(); shelves.Add(new Shelf { slfName = "Reading now" }); shelves.Add(new Shelf { slfName = "To read" }); shelves.Add(new Shelf { slfName = "Have read" }); return shelves; } } }
using Library.Model; using System; using System.Collections.Generic; namespace Library { public class Database { public static List<Book> Books() { var books = new List<Book>(); books.Add(new Book { slfID = 1, booTitle = "Title", booDescription = "Description", booAuthor = "Author", booPublisher = "Publisher", booPublishedDate = DateTime.Now.ToString(), booPageCount = 100, booRating = 5.0, booRatingsCount = 1000, booInformationURL = "Information URL", booPreviewURL = "Preview URL" }); return books; } public static List<Shelf> Shelves() { var shelves = new List<Shelf>(); shelves.Add(new Shelf { slfName = "Reading now" }); shelves.Add(new Shelf { slfName = "To read" }); shelves.Add(new Shelf { slfName = "Have read" }); return shelves; } } }
mit
C#
8e013682bd94fad3f019801d0d3d1792824b91ce
Fix start index for string - sub mounting modules
mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy
src/Manos/Manos.Routing/StringMatchOperation.cs
src/Manos/Manos.Routing/StringMatchOperation.cs
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Collections.Specialized; using Manos.Collections; namespace Manos.Routing { public class StringMatchOperation : IMatchOperation { private string str; public StringMatchOperation (string str) { String = str; } public string String { get { return str; } set { if (value == null) throw new ArgumentNullException ("value"); if (value.Length == 0) throw new ArgumentException ("StringMatch operations should not use empty strings."); str = value.ToLower(); } } public bool IsMatch (string input, int start, out DataDictionary data, out int end) { if (!StartsWith (input, start, String)) { data = null; end = start; return false; } data = null; end = start + String.Length; return true; } public static bool StartsWith (string input, int start, string str) { if (input.Length < str.Length + start) return false; return String.Compare (input, start, str, 0, str.Length, StringComparison.OrdinalIgnoreCase) == 0; } } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Collections.Specialized; using Manos.Collections; namespace Manos.Routing { public class StringMatchOperation : IMatchOperation { private string str; public StringMatchOperation (string str) { String = str; } public string String { get { return str; } set { if (value == null) throw new ArgumentNullException ("value"); if (value.Length == 0) throw new ArgumentException ("StringMatch operations should not use empty strings."); str = value.ToLower(); } } public bool IsMatch (string input, int start, out DataDictionary data, out int end) { if (!StartsWith (input, start, String)) { data = null; end = start; return false; } data = null; end = start + String.Length; return true; } public static bool StartsWith (string input, int start, string str) { if (input.Length < str.Length + start) return false; return String.Compare (input, 0, str, 0, str.Length, StringComparison.OrdinalIgnoreCase) == 0; } } }
mit
C#
77614189c978e4bffa18b4dee16dbfa90351944c
Make AdjustRank Bindable
smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,ZLima12/osu,2yangk23/osu,ZLima12/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,2yangk23/osu,ppy/osu,ppy/osu,johnneijzen/osu,johnneijzen/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu
osu.Game/Rulesets/Mods/ModHidden.cs
osu.Game/Rulesets/Mods/ModHidden.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Objects.Drawables; using System.Collections.Generic; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModHidden : Mod, IReadFromConfig, IApplicableToDrawableHitObjects, IApplicableToScoreProcessor { public override string Name => "Hidden"; public override string Acronym => "HD"; public override IconUsage Icon => OsuIcon.ModHidden; public override ModType Type => ModType.DifficultyIncrease; public override bool Ranked => true; protected Bindable<bool> IncreaseFirstObjectVisibility = new Bindable<bool>(); public void ReadFromConfig(OsuConfigManager config) { IncreaseFirstObjectVisibility = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility); } public virtual void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var d in drawables.Skip(IncreaseFirstObjectVisibility.Value ? 1 : 0)) d.ApplyCustomUpdateState += ApplyHiddenState; } public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { scoreProcessor.AdjustRank.Value = true; } protected virtual void ApplyHiddenState(DrawableHitObject hitObject, ArmedState state) { } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Rulesets.Objects.Drawables; using System.Collections.Generic; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics.Sprites; using osu.Game.Rulesets.Scoring; namespace osu.Game.Rulesets.Mods { public abstract class ModHidden : Mod, IReadFromConfig, IApplicableToDrawableHitObjects, IApplicableToScoreProcessor { public override string Name => "Hidden"; public override string Acronym => "HD"; public override IconUsage Icon => OsuIcon.ModHidden; public override ModType Type => ModType.DifficultyIncrease; public override bool Ranked => true; protected Bindable<bool> IncreaseFirstObjectVisibility = new Bindable<bool>(); public void ReadFromConfig(OsuConfigManager config) { IncreaseFirstObjectVisibility = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility); } public virtual void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var d in drawables.Skip(IncreaseFirstObjectVisibility.Value ? 1 : 0)) d.ApplyCustomUpdateState += ApplyHiddenState; } public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor) { scoreProcessor.AdjustRank = true; } protected virtual void ApplyHiddenState(DrawableHitObject hitObject, ArmedState state) { } } }
mit
C#
8577273675549a305afc6ddb01a06b9ca44edcb5
Rollback temp DI fix.
SkillsFundingAgency/das-referencedata,SkillsFundingAgency/das-referencedata
src/SFA.DAS.ReferenceData.Infrastructure/DependencyResolution/CachePolicy.cs
src/SFA.DAS.ReferenceData.Infrastructure/DependencyResolution/CachePolicy.cs
using System; using System.Configuration; using System.Linq; using SFA.DAS.ReferenceData.Domain.Interfaces.Caching; using SFA.DAS.ReferenceData.Infrastructure.Caching; using StructureMap; using StructureMap.Pipeline; namespace SFA.DAS.ReferenceData.Infrastructure.DependencyResolution { public class CachePolicy : ConfiguredInstancePolicy { protected override void apply(Type pluginType, IConfiguredInstance instance) { var cacheParameter = instance?.Constructor?.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(ICache)); if (cacheParameter == null) return; var cache = GetCache(); instance.Dependencies.AddForConstructorParameter(cacheParameter, cache); } private static ICache GetCache() { ICache cache; if (bool.Parse(ConfigurationManager.AppSettings["LocalConfig"])) { cache = new InMemoryCache(); } else { cache = new RedisCache(); } return cache; } } }
using System; using System.Configuration; using System.Linq; using SFA.DAS.ReferenceData.Domain.Interfaces.Caching; using SFA.DAS.ReferenceData.Infrastructure.Caching; using StructureMap; using StructureMap.Pipeline; namespace SFA.DAS.ReferenceData.Infrastructure.DependencyResolution { public class CachePolicy : ConfiguredInstancePolicy { protected override void apply(Type pluginType, IConfiguredInstance instance) { var cacheParameter = instance?.Constructor?.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(ICache)); if (cacheParameter == null) return; var cache = GetCache(); instance.Dependencies.AddForConstructorParameter(cacheParameter, cache); } private static ICache GetCache() { ICache cache; // if (bool.Parse(ConfigurationManager.AppSettings["LocalConfig"])) // { // cache = new InMemoryCache(); // } // else // { cache = new RedisCache(); //} return cache; } } }
mit
C#
8a0241347d6ee4b17831617695b2b8059266edfd
Use same null default value when JS is disabled
kendaleiv/AspNetBrowserLocale,ritterim/AspNetBrowserLocale
src/Core/HtmlHelpers.cs
src/Core/HtmlHelpers.cs
using System; using System.Web.Mvc; namespace AspNetBrowserLocale.Core { public static class HtmlHelpers { private const string NullValueDisplay = "&mdash;"; public static MvcHtmlString InitializeLocaleDateTime(this HtmlHelper htmlHelper) { return MvcHtmlString.Create(string.Format( @"<script> var elements = document.querySelectorAll('[data-aspnet-browser-locale]'); for (var i = 0; i < elements.length; i++) {{ var element = elements[i]; var msString = element.dataset.aspnetBrowserLocale; if (msString) {{ var jsDate = new Date(parseInt(msString, 10)); element.innerHTML = jsDate.toLocaleString(); }} else {{ element.innerHTML = '{0}'; }} }} </script>", NullValueDisplay)); } public static MvcHtmlString LocaleDateTime(this HtmlHelper htmlHelper, DateTime? dateTime) { long? msSinceUnixEpoch = null; if (dateTime.HasValue) { msSinceUnixEpoch = (long)((TimeSpan)(dateTime.Value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds; } return MvcHtmlString.Create(string.Format( @"<span data-aspnet-browser-locale=""{0}"">{1}</span>", msSinceUnixEpoch, dateTime.HasValue ? dateTime.Value.ToUniversalTime().ToString() + " UTC" : NullValueDisplay)); } } }
using System; using System.Web.Mvc; namespace AspNetBrowserLocale.Core { public static class HtmlHelpers { public static MvcHtmlString InitializeLocaleDateTime(this HtmlHelper htmlHelper) { return MvcHtmlString.Create( @"<script> var elements = document.querySelectorAll('[data-aspnet-browser-locale]'); for (var i = 0; i < elements.length; i++) {{ var element = elements[i]; var msString = element.dataset.aspnetBrowserLocale; if (msString) {{ var jsDate = new Date(parseInt(msString, 10)); element.innerHTML = jsDate.toLocaleString(); }} else {{ element.innerHTML = '&mdash;'; }} }} </script>"); } public static MvcHtmlString LocaleDateTime(this HtmlHelper htmlHelper, DateTime? dateTime) { long? msSinceUnixEpoch = null; if (dateTime.HasValue) { msSinceUnixEpoch = (long)((TimeSpan)(dateTime.Value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds; } return MvcHtmlString.Create(string.Format( @"<span data-aspnet-browser-locale=""{0}"">{1}</span>", msSinceUnixEpoch, dateTime.HasValue ? dateTime.Value.ToUniversalTime().ToString() + " UTC" : null)); } } }
mit
C#
4bc799fd17dc0573612ce6b8e7f7b069ceacb1e6
Add Owner to ListBucketObject
carbon/Amazon
src/Amazon.S3/Results/ListBucketObject.cs
src/Amazon.S3/Results/ListBucketObject.cs
#nullable disable using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Xml.Serialization; using Carbon.Storage; namespace Amazon.S3 { [XmlRoot("Contents", Namespace = S3Client.Namespace)] public sealed class ListBucketObject : IBlob { [XmlElement("Key")] public string Key { get; set; } [XmlElement("LastModified", DataType = "dateTime")] public DateTime LastModified { get; set; } [XmlElement("ETag")] public string ETag { get; set; } [XmlElement("Size")] public long Size { get; set; } [XmlElement("StorageClass")] public string StorageClass { get; set; } [XmlElement("Owner")] public Owner Owner { get; set; } #region IBlob DateTime IBlob.Modified => LastModified; IReadOnlyDictionary<string, string> IBlob.Properties => BlobProperties.Empty; ValueTask<Stream> IBlob.OpenAsync() { throw new NotImplementedException(); } void IDisposable.Dispose() { } #endregion } } /* <Contents> <Key>100000/800x600.jpeg</Key> <LastModified>2009-06-20T09:54:05.000Z</LastModified> <ETag>&quot;c55fad5b272947050bed993ec22c6d0d&quot;</ETag> <Size>116879</Size> <Owner> <ID>9c18bda0312b59b259789b4acf29a06efdb6193a4ef51fcafa739f5cda4f3bf0</ID> <DisplayName>jason17095</DisplayName> </Owner> <StorageClass>STANDARD</StorageClass> </Contents> */
#nullable disable using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Xml.Serialization; using Carbon.Storage; namespace Amazon.S3 { [XmlRoot("Contents", Namespace = S3Client.Namespace)] public sealed class ListBucketObject : IBlob { [XmlElement("Key")] public string Key { get; set; } [XmlElement("LastModified", DataType = "dateTime")] public DateTime LastModified { get; set; } [XmlElement("ETag")] public string ETag { get; set; } [XmlElement("Size")] public long Size { get; set; } [XmlElement("StorageClass")] public string StorageClass { get; set; } #region IBlob DateTime IBlob.Modified => LastModified; IReadOnlyDictionary<string, string> IBlob.Properties => BlobProperties.Empty; ValueTask<Stream> IBlob.OpenAsync() { throw new NotImplementedException(); } void IDisposable.Dispose() { } #endregion } } /* <Contents> <Key>100000/800x600.jpeg</Key> <LastModified>2009-06-20T09:54:05.000Z</LastModified> <ETag>&quot;c55fad5b272947050bed993ec22c6d0d&quot;</ETag> <Size>116879</Size> <Owner> <ID>9c18bda0312b59b259789b4acf29a06efdb6193a4ef51fcafa739f5cda4f3bf0</ID> <DisplayName>jason17095</DisplayName> </Owner> <StorageClass>STANDARD</StorageClass> </Contents> */
mit
C#
fddb9b631980225af23897d46433327212e8cf8c
Remove unnecessary "@" prefix from method argument variable name.
brendanjbaker/Bakery
src/Bakery/Text/StringRemoveExtensions.cs
src/Bakery/Text/StringRemoveExtensions.cs
namespace Bakery.Text { using System; public static class StringRemoveExtensions { public static String Remove(this String @string, String remove) { if (remove == null) throw new ArgumentNullException(nameof(remove)); return @string.Replace(remove, String.Empty); } } }
namespace Bakery.Text { using System; public static class StringRemoveExtensions { public static String Remove(this String @string, String @remove) { return @string.Replace(@remove, String.Empty); } } }
mit
C#
e7cd40b015032d217c950276a3565819d901abf8
Add an extra fake rehearsal to check wrapping.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Controllers/HomeController.cs
src/CGO.Web/Controllers/HomeController.cs
using System; using System.Web.Mvc; using CGO.Domain; using CGO.Web.Infrastructure; using CGO.Web.Models; namespace CGO.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Cambridge Graduate Orchestra"; ViewBag.GoogleLoginUrl = new GoogleOAuthConfiguration().MakeLoginUri(""); var model = new HomePageViewModel( new Concert(3, "Russian Heritage", new DateTime(2012, 12, 01, 20, 0, 0), "West Road Concert Hall"), new[] { new Rehearsal(1, new DateTime(2012, 10, 7, 19, 30, 00), new DateTime(2012, 10, 7, 22, 00, 00), "Hughes Hall"), new Rehearsal(2, new DateTime(2012, 10, 14, 19, 30, 00), new DateTime(2012, 10, 14, 22, 00, 00), "Hughes Hall"), new Rehearsal(3, new DateTime(2012, 10, 21, 19, 30, 00), new DateTime(2012, 10, 21, 22, 00, 00), "Hughes Hall"), new Rehearsal(3, new DateTime(2012, 10, 28, 19, 30, 00), new DateTime(2012, 10, 28, 22, 00, 00), "Hughes Hall") }); Response.AppendHeader("X-XRDS-Location", new Uri(Request.Url, Response.ApplyAppPathModifier("~/Home/xrds")).AbsoluteUri); return View(model); } public ActionResult About() { return View(); } public ActionResult Contact() { return View(); } public ActionResult Xrds() { return View("Xrds"); } } }
using System; using System.Web.Mvc; using CGO.Domain; using CGO.Web.Infrastructure; using CGO.Web.Models; namespace CGO.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Cambridge Graduate Orchestra"; ViewBag.GoogleLoginUrl = new GoogleOAuthConfiguration().MakeLoginUri(""); var model = new HomePageViewModel( new Concert(3, "Russian Heritage", new DateTime(2012, 12, 01, 20, 0, 0), "West Road Concert Hall"), new[] { new Rehearsal(1, new DateTime(2012, 10, 7, 19, 30, 00), new DateTime(2012, 10, 7, 22, 00, 00), "Hughes Hall"), new Rehearsal(2, new DateTime(2012, 10, 14, 19, 30, 00), new DateTime(2012, 10, 14, 22, 00, 00), "Hughes Hall"), new Rehearsal(3, new DateTime(2012, 10, 21, 19, 30, 00), new DateTime(2012, 10, 21, 22, 00, 00), "Hughes Hall") }); Response.AppendHeader("X-XRDS-Location", new Uri(Request.Url, Response.ApplyAppPathModifier("~/Home/xrds")).AbsoluteUri); return View(model); } public ActionResult About() { return View(); } public ActionResult Contact() { return View(); } public ActionResult Xrds() { return View("Xrds"); } } }
mit
C#
d66af28b1e219799404c542fc190ec309afdc092
Normalise line endings.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Controllers/HomeController.cs
src/CGO.Web/Controllers/HomeController.cs
using System; using System.Web.Mvc; using CGO.Domain; using CGO.Web.Infrastructure; using CGO.Web.Models; namespace CGO.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Cambridge Graduate Orchestra"; ViewBag.GoogleLoginUrl = new GoogleOAuthConfiguration().MakeLoginUri(""); var model = new HomePageViewModel( new Concert(3, "Russian Heritage", new DateTime(2012, 12, 01, 20, 0, 0), "West Road Concert Hall"), new[] { new Rehearsal(1, new DateTime(2012, 10, 7, 19, 30, 00), new DateTime(2012, 10, 7, 22, 00, 00), "Hughes Hall"), new Rehearsal(2, new DateTime(2012, 10, 14, 19, 30, 00), new DateTime(2012, 10, 14, 22, 00, 00), "Hughes Hall"), new Rehearsal(3, new DateTime(2012, 10, 21, 19, 30, 00), new DateTime(2012, 10, 21, 22, 00, 00), "Hughes Hall") }); Response.AppendHeader("X-XRDS-Location", new Uri(Request.Url, Response.ApplyAppPathModifier("~/Home/xrds")).AbsoluteUri); return View(model); } public ActionResult About() { return View(); } public ActionResult Contact() { return View(); } public ActionResult Xrds() { return View("Xrds"); } } }
using System; using System.Web.Mvc; using CGO.Domain; using CGO.Web.Infrastructure; using CGO.Web.Models; namespace CGO.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Cambridge Graduate Orchestra"; ViewBag.GoogleLoginUrl = new GoogleOAuthConfiguration().MakeLoginUri(""); var model = new HomePageViewModel( new Concert(3, "Russian Heritage", new DateTime(2012, 12, 01, 20, 0, 0), "West Road Concert Hall"), new[] { new Rehearsal(1, new DateTime(2012, 10, 7, 19, 30, 00), new DateTime(2012, 10, 7, 22, 00, 00), "Hughes Hall"), new Rehearsal(2, new DateTime(2012, 10, 14, 19, 30, 00), new DateTime(2012, 10, 14, 22, 00, 00), "Hughes Hall"), new Rehearsal(3, new DateTime(2012, 10, 21, 19, 30, 00), new DateTime(2012, 10, 21, 22, 00, 00), "Hughes Hall") }); Response.AppendHeader("X-XRDS-Location", new Uri(Request.Url, Response.ApplyAppPathModifier("~/Home/xrds")).AbsoluteUri); return View(model); } public ActionResult About() { return View(); } public ActionResult Contact() { return View(); } public ActionResult Xrds() { return View("Xrds"); } } }
mit
C#
4e665e0e3e27a1bb4b5d1024eeac33af9e059741
refactor duplication and description generation
BaylorRae/Let.cs
src/Let.cs/LetHelper.cs
src/Let.cs/LetHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace LetTestHelper { public static class LetHelper { private static Dictionary<string, object> _objects = new Dictionary<string, object>(); public static T Let<T>(string description, Func<T> func) { if (_objects.ContainsKey(description)) return (T) _objects[description]; var result = func(); _objects.Add(description, result); return result; } public static T Let<T>(Expression<Func<T>> expression) { return Let( CreateDescriptionFromExpression(expression), expression.Compile() ); } public static void Flush() { _objects.Clear(); } private static string CreateDescriptionFromExpression<T>(Expression<Func<T>> expression) { var description = expression.Body.ToString(); var genericArguments = expression.ReturnType.GenericTypeArguments; if (genericArguments.Length > 0) description += string.Join(",", genericArguments.Select(t => t.Name)); return description; } private class Defined { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace LetTestHelper { public static class LetHelper { private static Dictionary<string, object> _objects = new Dictionary<string, object>(); public static T Let<T>(string description, Func<T> func) { if (_objects.ContainsKey(description)) return (T) _objects[description]; var result = func(); _objects.Add(description, result); return result; } public static T Let<T>(Expression<Func<T>> expression) { var expressionBody = expression.Body.ToString(); var genericArguments = expression.ReturnType.GenericTypeArguments; if (genericArguments.Length > 0) expressionBody += string.Join(",", genericArguments.Select(t => t.Name)); if (_objects.ContainsKey(expressionBody)) return (T) _objects[expressionBody]; var result = expression.Compile().Invoke(); _objects.Add(expressionBody, result); return (T) result; } public static void Flush() { _objects.Clear(); } private class Defined { } } }
mit
C#
8bbf1476c29dbf97f237a6153b15f2a094b76b84
add V1Patch for patch custom obj (#530)
kubernetes-client/csharp,kubernetes-client/csharp
src/KubernetesClient/Kubernetes.Header.cs
src/KubernetesClient/Kubernetes.Header.cs
using System; using System.Net.Http.Headers; using k8s.Models; namespace k8s { public partial class Kubernetes { public virtual MediaTypeHeaderValue GetHeader(object body) { if (body == null) { throw new ArgumentNullException(nameof(body)); } if (body is V1Patch patch) { return GetHeader(patch); } return MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } public virtual MediaTypeHeaderValue GetHeader(V1Patch body) { if (body == null) { throw new ArgumentNullException(nameof(body)); } switch (body.Type) { case V1Patch.PatchType.JsonPatch: return MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); case V1Patch.PatchType.MergePatch: return MediaTypeHeaderValue.Parse("application/merge-patch+json; charset=utf-8"); case V1Patch.PatchType.StrategicMergePatch: return MediaTypeHeaderValue.Parse("application/strategic-merge-patch+json; charset=utf-8"); default: throw new ArgumentOutOfRangeException(nameof(body.Type), ""); } } } }
using System; using System.Net.Http.Headers; using k8s.Models; namespace k8s { public partial class Kubernetes { public virtual MediaTypeHeaderValue GetHeader(object body) { if (body == null) { throw new ArgumentNullException(nameof(body)); } return MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } public virtual MediaTypeHeaderValue GetHeader(V1Patch body) { if (body == null) { throw new ArgumentNullException(nameof(body)); } switch (body.Type) { case V1Patch.PatchType.JsonPatch: return MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); case V1Patch.PatchType.MergePatch: return MediaTypeHeaderValue.Parse("application/merge-patch+json; charset=utf-8"); case V1Patch.PatchType.StrategicMergePatch: return MediaTypeHeaderValue.Parse("application/strategic-merge-patch+json; charset=utf-8"); default: throw new ArgumentOutOfRangeException(nameof(body.Type), ""); } } } }
apache-2.0
C#
38e95cf3d85a3d6effcb3f79498ed1d03d1aeaec
fix template
takenet/messaginghub-client-csharp
src/Template/Program.cs
src/Template/Program.cs
using System; using System.Threading.Tasks; using Lime.Protocol; using Takenet.MessagingHub.Client; using Takenet.MessagingHub.Client.Receivers; namespace Template { internal static class Program { public static void Main(string[] args) { Init().Wait(); } private class MessageReceiver : MessageReceiverBase { public override async Task ReceiveAsync(Message message) { // Text messages sent to your application will be received here Console.WriteLine($"Message received from {message.From} at {DateTime.Now}: {message.Content}!"); await MessageSender.SendMessageAsync("It works!", message.From); } } private static async Task Init() { // Go to http://console.messaginghub.io to register your application and get your access key const string login = "yourApplicationName"; const string accessKey = "yourAccessKey"; // Instantiates a MessageHubClient using its fluent API // Since host name and domain name are not informed, the default value, 'msging.net', will be used for both parameters var client = new MessagingHubClient() .UsingAccessKey(login, accessKey) .AddMessageReceiver(new MessageReceiver(), MediaTypes.PlainText); // Starts the client await client.StartAsync(); Console.WriteLine("Press any key to stop"); Console.ReadKey(); // Stop the client await client.StopAsync(); } } }
using System; using System.Threading.Tasks; using Lime.Protocol; using Takenet.MessagingHub.Client; using Takenet.MessagingHub.Client.Receivers; namespace Template { internal static class Program { public static void Main(string[] args) { Init().Wait(); } private class MessageReceiver : MessageReceiverBase { public override async Task ReceiveAsync(Message message) { // Text messages sent to your application will be received here await MessageSender.SendMessageAsync("It works!", message.From); } } private static async Task Init() { // Go to http://console.messaginghub.io to register your application and get your access key const string login = "yourApplicationName"; const string accessKey = "yourAccessKey"; // Instantiates a MessageHubClient using its fluent API // Since host name and domain name are not informed, the default value, 'msging.net', will be used for both parameters var client = new MessagingHubClient() .UsingAccessKey(login, accessKey) .AddMessageReceiver(new MessageReceiver(), MediaTypes.PlainText); // Starts the client await client.StartAsync(); Console.WriteLine("Press any key to stop"); Console.ReadKey(); // Stop the client await client.StopAsync(); } } }
apache-2.0
C#
f5c74fd4c3773e16f913e5ef2e664886cae44664
Change Demo Trading intervall -> performance
boehla/TradeIt
DemoTrader/DTrader.cs
DemoTrader/DTrader.cs
using Main; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoTrader { public class StdTraders : Trader { public StdTraders() : base() { } public override string Name { get { return "DemoTrader"; } } public override string Version { get { return "0.0.1"; } } public override bool Active { get { return true; } } public override void Initiale() { log("Tradeengine started.... Balance: btc=" + Portfolio.btc + "; eur=" + Portfolio.eur); base.Initiale(); } public override void Update() { if (!Data.checkIfDataFalid(2)) return; double shortvl = Data.ma(2); double longvl = Data.ma(1); double mymacd = (longvl - shortvl) / longvl; plot("ma short", shortvl); plot("ma long", longvl); plot("ema short", Data.ema(2)); plot("price", Data.Candle().value.Last); plot("macd", mymacd, true); int tradeint = 100; if (TickCount % tradeint == 0) { if (TickCount % (tradeint * 2) == 0) { buyBtc(10); } else { sellBtc(10); } } base.Update(); } public override void Stop() { base.Stop(); } } }
using Main; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoTrader { public class StdTraders : Trader { public StdTraders() : base() { } public override string Name { get { return "DemoTrader"; } } public override string Version { get { return "0.0.1"; } } public override bool Active { get { return true; } } public override void Initiale() { log("Tradeengine started.... Balance: btc=" + Portfolio.btc + "; eur=" + Portfolio.eur); base.Initiale(); } public override void Update() { if (!Data.checkIfDataFalid(2)) return; double shortvl = Data.ma(2); double longvl = Data.ma(1); double mymacd = (longvl - shortvl) / longvl; plot("ma short", shortvl); plot("ma long", longvl); plot("ema short", Data.ema(2)); plot("price", Data.Candle().value.Last); plot("macd", mymacd, true); if (TickCount % 2 == 0) { buyBtc(10); } else { sellBtc(10); } base.Update(); } public override void Stop() { base.Stop(); } } }
mit
C#
eb5a21477ea97dd4785584e0cbbd6dfa6aeb4d73
Fix <= to <
bunashibu/kikan
Assets/Scripts/Hp/Hp.cs
Assets/Scripts/Hp/Hp.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Bunashibu.Kikan { public abstract class Hp : IGauge<int> { public virtual void Add(int quantity) { Cur += quantity; AdjustBoundary(); } public virtual void Subtract(int quantity) { Cur -= quantity; AdjustBoundary(); } private void AdjustBoundary() { if (Cur < Min) Cur = Min; if (Cur > Max) Cur = Max; } public int Cur { get; protected set; } public int Min { get { return 0; } } public int Max { get; protected set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Bunashibu.Kikan { public abstract class Hp : IGauge<int> { public virtual void Add(int quantity) { Cur += quantity; AdjustBoundary(); } public virtual void Subtract(int quantity) { Cur -= quantity; AdjustBoundary(); } private void AdjustBoundary() { if (Cur <= Min) Cur = Min; if (Cur > Max) Cur = Max; } public int Cur { get; protected set; } public int Min { get { return 0; } } public int Max { get; protected set; } } }
mit
C#
385148887fc72daadbcf627363b187b8dd00623f
Fix dem
Yonom/ByteNom
ByteNom.Demo/Program.cs
ByteNom.Demo/Program.cs
using System; using System.Threading; namespace ByteNom.Demo { internal class Program { private static void Main() { // Start a server var server = new Server(12345); server.ConnectionReceived += server_ConnectionReceived; server.Start(); // Start a client var client = new Client("localhost", 12345); client.MessageReceived += client_MessageReceived; client.Connect(); client.Send("hello world", "this is a message argument", 10); Thread.Sleep(Timeout.Infinite); } // Called whenever our client receives a message private static void client_MessageReceived(object sender, Message message) { if (message.Type == "HAI") { Console.WriteLine("HAI message received from server!"); } } // Called whenever our server receives a new connection private static void server_ConnectionReceived(object sender, Connection connection) { connection.MessageReceived += connection_MessageReceived; connection.Send("HAI"); } // Called whenever a client sends a message to our server private static void connection_MessageReceived(object sender, Message message) { if (message.Type == "hello world") { Console.WriteLine("hello world message received from client!"); Console.WriteLine(message.GetString(0)); Console.WriteLine("The number was: " + message.GetInt(1)); } } } }
using System; using System.Threading; namespace ByteNom.Demo { internal class Program { private static void Main() { // Start a server var server = new Server(12345); server.ConnectionReceived += server_ConnectionReceived; server.Start(); // Start a client var client = new Client("localhost", 12345); client.MessageReceived += client_MessageReceived; client.Connect(); client.Send("hello world", "this is a message argument", 10); Thread.Sleep(100); client.Disconnect(); Thread.Sleep(Timeout.Infinite); } // Called whenever our client receives a message private static void client_MessageReceived(object sender, Message message) { if (message.Type == "HAI") { Console.WriteLine("HAI message received from server!"); } } // Called whenever our server receives a new connection private static void server_ConnectionReceived(object sender, Connection connection) { connection.MessageReceived += connection_MessageReceived; while (true) { connection.Send("HAI"); } } // Called whenever a client sends a message to our server private static void connection_MessageReceived(object sender, Message message) { if (message.Type == "hello world") { Console.WriteLine("hello world message received from client!"); Console.WriteLine(message.GetString(0)); Console.WriteLine("The number was: " + message.GetInt(1)); } } } }
mit
C#
f0a7cbe0a7b43947e3cf52beafc3081b35196310
Disable authentication with empty access key
Seist/Skylight
Skylight.Outgoing/InputCodeForRoom.cs
Skylight.Outgoing/InputCodeForRoom.cs
using System; using Skylight.Miscellaneous; namespace Skylight { public class InputCodeForRoom { private readonly Out _out; public InputCodeForRoom(Out @out) { _out = @out; } /// <summary> /// Inputs the edit key. /// </summary> /// <param name="editKey">The edit key.</param> public void InputCode(string editKey) { if (String.IsNullOrWhiteSpace(editKey)) {throw new ArgumentException("editKey cannot be empty or null.");} try { _out.C.Send("access", editKey); } catch (Exception) { Tools.SkylightMessage("Error: attempted to use Out.InputCode before connecting"); } } } }
using System; using Skylight.Miscellaneous; namespace Skylight { public class InputCodeForRoom { private readonly Out _out; public InputCodeForRoom(Out @out) { _out = @out; } /// <summary> /// Inputs the edit key. /// </summary> /// <param name="editKey">The edit key.</param> public void InputCode(string editKey) { try { _out.C.Send("access", editKey); } catch (Exception) { Tools.SkylightMessage("Error: attempted to use Out.InputCode before connecting"); } } } }
mit
C#
49139fd0974edc567c14ca061b69e7f6255ee7a4
fix Desktop/DesktopUrhoInitializer.cs
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
bindings/Desktop/DesktopUrhoInitializer.cs
bindings/Desktop/DesktopUrhoInitializer.cs
using System; using System.IO; using System.Reflection; namespace Urho.Desktop { public static class DesktopUrhoInitializer { static string assetsDirectory; /// <summary> /// Path to a folder containing "Data" folder. CurrentDirectory if null /// </summary> public static string AssetsDirectory { get { return assetsDirectory; } set { assetsDirectory = value; if (!string.IsNullOrEmpty(assetsDirectory)) { if (!Directory.Exists(assetsDirectory)) { throw new InvalidDataException($"Directory {assetsDirectory} not found"); } const string coreDataFile = "CoreData.pak"; System.IO.File.Copy( sourceFileName: Path.Combine(Environment.CurrentDirectory, coreDataFile), destFileName: Path.Combine(assetsDirectory, coreDataFile), overwrite: true); Environment.CurrentDirectory = assetsDirectory; } } } internal static void OnInited() { var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //unlike the OS X, windows doesn't support FAT binaries if (Environment.OSVersion.Platform == PlatformID.Win32NT && !Environment.Is64BitProcess && Is64Bit(Path.Combine(currentPath, "mono-urho.dll"))) { throw new NotSupportedException("mono-urho.dll is 64bit, but current process is x86 (change target platform from Any CPU/x86 to x64)"); } } static bool Is64Bit(string dllPath) { using (var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read)) using (var br = new BinaryReader(fs)) { fs.Seek(0x3c, SeekOrigin.Begin); var peOffset = br.ReadInt32(); fs.Seek(peOffset, SeekOrigin.Begin); var value = br.ReadUInt16(); const ushort IMAGE_FILE_MACHINE_AMD64 = 0x8664; const ushort IMAGE_FILE_MACHINE_IA64 = 0x200; return value == IMAGE_FILE_MACHINE_AMD64 || value == IMAGE_FILE_MACHINE_IA64; } } } }
using System; using System.IO; namespace Urho.Desktop { public static class DesktopUrhoInitializer { static string assetsDirectory; /// <summary> /// Path to a folder containing "Data" folder. CurrentDirectory if null /// </summary> public static string AssetsDirectory { get { return assetsDirectory; } set { assetsDirectory = value; if (!string.IsNullOrEmpty(assetsDirectory)) { if (!Directory.Exists(assetsDirectory)) { throw new InvalidDataException($"Directory {assetsDirectory} not found"); } const string coreDataFile = "CoreData.pak"; System.IO.File.Copy( sourceFileName: Path.Combine(Environment.CurrentDirectory, coreDataFile), destFileName: Path.Combine(assetsDirectory, coreDataFile), overwrite: true); Environment.CurrentDirectory = assetsDirectory; } } } internal static void OnInited() { //unlike the OS X, windows doesn't support FAT binaries if (Environment.OSVersion.Platform == PlatformID.Win32NT && !Environment.Is64BitProcess && Is64Bit("mono-urho.dll")) { throw new NotSupportedException("mono-urho.dll is 64bit, but current process is x86 (change target platform from Any CPU/x86 to x64)"); } } static bool Is64Bit(string dllPath) { using (var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read)) using (var br = new BinaryReader(fs)) { fs.Seek(0x3c, SeekOrigin.Begin); var peOffset = br.ReadInt32(); fs.Seek(peOffset, SeekOrigin.Begin); var value = br.ReadUInt16(); const ushort IMAGE_FILE_MACHINE_AMD64 = 0x8664; const ushort IMAGE_FILE_MACHINE_IA64 = 0x200; return value == IMAGE_FILE_MACHINE_AMD64 || value == IMAGE_FILE_MACHINE_IA64; } } } }
mit
C#
f20748a60688352f0c076395e6e5ab5ba8b4b7bd
Update the test app to work with the changed library.
smaeul/7DaysToolbox
SDTD.ConfigTest/Form.cs
SDTD.ConfigTest/Form.cs
namespace SDTD.ConfigTest { using SDTD.Config; using System; using System.IO; using System.Xml.Linq; public partial class Form : System.Windows.Forms.Form { private String dataPath = @"C:\Program Files (x86)\Steam\steamapps\common\7 Days To Die\Data\Config"; private BlockCollection blocks; private ItemCollection items; private MaterialCollection materials; public Form() { items = new ItemCollection(); materials = new MaterialCollection(); blocks = new BlockCollection(items, materials); InitializeComponent(); } private void Form_Load(Object sender, EventArgs e) { statusBox.AppendText(String.Format("Reading data from \"{0}\"...{1}", dataPath, Environment.NewLine)); XDocument blocksXML = XDocument.Load(dataPath + Path.DirectorySeparatorChar + "blocks.xml"); XDocument itemsXML = XDocument.Load(dataPath + Path.DirectorySeparatorChar + "items.xml"); XDocument materialsXML = XDocument.Load(dataPath + Path.DirectorySeparatorChar + "materials.xml"); items.Load(itemsXML); materials.Load(materialsXML); blocks.Load(blocksXML); statusBox.AppendText(String.Format(" Found {0} blocks.{1}", blocks.Count, Environment.NewLine)); statusBox.AppendText(String.Format(" Found {0} items.{1}", items.Count, Environment.NewLine)); statusBox.AppendText(String.Format(" Found {0} materials.{1}", materials.Count, Environment.NewLine)); statusBox.AppendText("XML for wood frame:" + Environment.NewLine); statusBox.AppendText(blocks["woodFrame"].ToXElement().ToString()); statusBox.AppendText(Environment.NewLine); statusBox.AppendText("XML for wall candle (has CanPickup property with param1):" + Environment.NewLine); statusBox.AppendText(blocks["candleWall"].ToXElement().ToString()); statusBox.AppendText(Environment.NewLine); statusBox.AppendText("XML for material of rebarFrame (extends solidRebarFrame):" + Environment.NewLine); statusBox.AppendText(materials[blocks["rebarFrame"].GetProperty("Material")].ToXElement().ToString()); statusBox.AppendText(Environment.NewLine); } } }
using SDTD.Config; using System; using System.IO; using System.Xml.Linq; namespace SDTD.ConfigTest { public partial class Form : System.Windows.Forms.Form { public Form() { InitializeComponent(); } private void Form_Load(Object sender, EventArgs e) { statusBox.AppendText(String.Format("Reading data from \"{0}\"...{1}", dataPath, Environment.NewLine)); XDocument blocksXML = XDocument.Load(dataPath + Path.DirectorySeparatorChar + "blocks.xml"); XDocument itemsXML = XDocument.Load(dataPath + Path.DirectorySeparatorChar + "items.xml"); XDocument materialsXML = XDocument.Load(dataPath + Path.DirectorySeparatorChar + "materials.xml"); XDocument recipesXML = XDocument.Load(dataPath + Path.DirectorySeparatorChar + "recipes.xml"); blocks = BlockCollection.Load(blocksXML); statusBox.AppendText(String.Format(" Found {0} blocks.{1}", blocks.Count, Environment.NewLine)); items = ItemCollection.Load(itemsXML); statusBox.AppendText(String.Format(" Found {0} items.{1}", items.Count, Environment.NewLine)); materials = MaterialCollection.Load(materialsXML); statusBox.AppendText(String.Format(" Found {0} materials.{1}", materials.Count, Environment.NewLine)); recipes = RecipeCollection.Load(recipesXML); statusBox.AppendText(String.Format(" Found {0} recipes.{1}", recipes.Count, Environment.NewLine)); statusBox.AppendText("XML for wood frame:" + Environment.NewLine); statusBox.AppendText(blocks["woodFrame"].ToXElement().ToString()); statusBox.AppendText(Environment.NewLine); statusBox.AppendText("XML for wall candle (has CanPickup property with param1):" + Environment.NewLine); statusBox.AppendText(blocks["candleWall"].ToXElement().ToString()); statusBox.AppendText(Environment.NewLine); statusBox.AppendText("XML for material of rebarFrame (extends solidRebarFrame):" + Environment.NewLine); statusBox.AppendText(materials[blocks["rebarFrame"].GetProperty("Material")].ToXElement().ToString()); statusBox.AppendText(Environment.NewLine); } private String dataPath = @"C:\Program Files (x86)\Steam\steamapps\common\7 Days To Die\Data\Config"; private BlockCollection blocks; private ItemCollection items; private MaterialCollection materials; private RecipeCollection recipes; } }
mit
C#
8b857e4153225bb547b67cc35bce98ca24855738
Update Export-CurrentDocument-Pages.csx
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D
scripts/Export-CurrentDocument-Pages.csx
scripts/Export-CurrentDocument-Pages.csx
using System.IO; var document = Editor.Project.CurrentDocument; var dir = "D:\\"; foreach (var page in document.Pages) { foreach (var writer in Editor.FileWriters) { var path = Path.Combine(dir, page.Name + "." + writer.Extension); writer.Save(path, page, Editor.Project); } }
using System.IO; var document = Editor.Project.CurrentDocument; var dir = "D:\\"; foreach (var page in document.Pages) { foreach (var writer in Editor.FileWriters) { path = Path.Combine(dir, page.Name + "." + writer.Extension); writer.Save(path, page, Editor.Project); } }
mit
C#
f8aad35d235a0a9ae1a281d0c1fb1d80e0336be5
Update Collision.cs
vvoid-inc/VoidEngine,thakyZ/VoidEngine
VoidEngine/Collision.cs
VoidEngine/Collision.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace VoidEngine { public static class Collision { public struct MapSegment { public Point point1; public Point point2; public MapSegment(Point a, Point b) { point1 = a; point2 = b; } public Vector2 getVector() { return new Vector2(point2.X - point1.X, point2.Y - point1.Y); } public Rectangle collisionRect() { return new Rectangle(Math.Min(point1.X, point2.X), Math.Min(point1.Y, point2.Y), Math.Abs(point1.X - point2.X), Math.Abs(point1.Y - point2.Y)); } } public static float magnitude(Vector2 vector) { return (float)Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y); } public static Vector2 vectorNormal(Vector2 vector) { return new Vector2(-vector.Y, vector.X); } public static Vector2 unitVector(Vector2 vector) { return new Vector2(vector.X / (float)magnitude(vector), vector.Y / (float)magnitude(vector)); } public static float dotProduct(Vector2 unitVector, Vector2 vector) { return unitVector.X * vector.X + unitVector.Y * vector.Y; } public static Vector2 reflectedVector(Vector2 vector, Vector2 reflectVector) { Vector2 normal = vectorNormal(reflectVector); float coeficient = -2 * (dotProduct(vector, normal) / (magnitude(normal) * magnitude(normal))); Vector2 r; r.X = vector.X + coeficient * normal.X; r.Y = vector.Y + coeficient * normal.Y; return r; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace VoidEngine { public class Collision { public struct MapSegment { public Point point1; public Point point2; public MapSegment(Point a, Point b) { point1 = a; point2 = b; } public Vector2 getVector() { return new Vector2(point2.X - point1.X, point2.Y - point1.Y); } public Rectangle collisionRect() { return new Rectangle(Math.Min(point1.X, point2.X), Math.Min(point1.Y, point2.Y), Math.Abs(point1.X - point2.X), Math.Abs(point1.Y - point2.Y)); } } public static float magnitude(Vector2 vector) { return (float)Math.Sqrt(vector.X * vector.X - vector.Y * vector.Y); } public static Vector2 vectorNormal(Vector2 vector) { return new Vector2(-vector.Y, vector.X); } public static Vector2 unitVector(Vector2 vector) { return new Vector2(vector.X / magnitude(vector), vector.Y / magnitude(vector)); } public static float dotProduct(Vector2 unitVector, Vector2 vector) { return unitVector.X * vector.X + unitVector.Y * vector.Y; } public static Vector2 reflectedVector(Vector2 vector, Vector2 reflectVector) { Vector2 normal = vectorNormal(reflectVector); float coeficient = -2 * (dotProduct(vector, normal) / magnitude(normal) * magnitude(normal)); Vector2 r; r.X = vector.X + coeficient * normal.X; r.Y = vector.Y + coeficient * normal.Y; return r; } } }
mit
C#
584a671ae92c72750f9e84fd85dc318d0d88e8ee
Drop prefers items held.
Blecki/RMUD,Reddit-Mud/RMUD
RMUD/Commands/Drop.cs
RMUD/Commands/Drop.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RMUD.Commands { internal class Drop : CommandFactory { public override void Create(CommandParser Parser) { Parser.AddCommand( new Sequence( new KeyWord("DROP", false), new ObjectMatcher("TARGET", new InScopeObjectSource(), ObjectMatcher.PreferHeld)), new DropProcessor(), "Drop something"); } } internal class DropProcessor : ICommandProcessor { public void Perform(PossibleMatch Match, Actor Actor) { var target = Match.Arguments["TARGET"] as Thing; if (target == null) { if (Actor.ConnectedClient != null) Actor.ConnectedClient.Send("Drop what again?\r\n"); } else { if (!Actor.Contains(target)) { Actor.ConnectedClient.Send("You aren't holding that.\r\n"); return; } var dropRules = target as IDropRules; if (dropRules != null && !dropRules.CanDrop(Actor)) { Actor.ConnectedClient.Send("You can't drop that.\r\n"); return; } Mud.SendEventMessage(Actor, EventMessageScope.Single, "You drop " + target.Indefinite + "\r\n"); Mud.SendEventMessage(Actor, EventMessageScope.External, Actor.Short + " drops " + target.Indefinite + "\r\n"); Thing.Move(target, Actor.Location); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RMUD.Commands { internal class Drop : CommandFactory { public override void Create(CommandParser Parser) { Parser.AddCommand( new Sequence( new KeyWord("DROP", false), new ObjectMatcher("TARGET", new InScopeObjectSource())), new DropProcessor(), "Drop something"); } } internal class DropProcessor : ICommandProcessor { public void Perform(PossibleMatch Match, Actor Actor) { var target = Match.Arguments["TARGET"] as Thing; if (target == null) { if (Actor.ConnectedClient != null) Actor.ConnectedClient.Send("Drop what again?\r\n"); } else { if (!Object.ReferenceEquals(target.Location, Actor)) { Actor.ConnectedClient.Send("You aren't holding that.\r\n"); return; } var dropRules = target as IDropRules; if (dropRules != null && !dropRules.CanDrop(Actor)) { Actor.ConnectedClient.Send("You can't drop that.\r\n"); return; } Mud.SendEventMessage(Actor, EventMessageScope.Single, "You drop " + target.Indefinite + "\r\n"); Mud.SendEventMessage(Actor, EventMessageScope.External, Actor.Short + " drops " + target.Indefinite + "\r\n"); Thing.Move(target, Actor.Location); } } } }
mit
C#
c6f8cb4a673e39cfd894316de2fba4c70e959739
add Active_Changes for Device Control service
ela-compil/BACnet
Base/BacnetReinitializedStates.cs
Base/BacnetReinitializedStates.cs
namespace System.IO.BACnet { public enum BacnetReinitializedStates { BACNET_REINIT_COLDSTART = 0, BACNET_REINIT_WARMSTART = 1, BACNET_REINIT_STARTBACKUP = 2, BACNET_REINIT_ENDBACKUP = 3, BACNET_REINIT_STARTRESTORE = 4, BACNET_REINIT_ENDRESTORE = 5, BACNET_REINIT_ABORTRESTORE = 6, BACNET_REINIT_ACTIVATE_CHANGES = 7, BACNET_REINIT_IDLE = 255 } }
namespace System.IO.BACnet { public enum BacnetReinitializedStates { BACNET_REINIT_COLDSTART = 0, BACNET_REINIT_WARMSTART = 1, BACNET_REINIT_STARTBACKUP = 2, BACNET_REINIT_ENDBACKUP = 3, BACNET_REINIT_STARTRESTORE = 4, BACNET_REINIT_ENDRESTORE = 5, BACNET_REINIT_ABORTRESTORE = 6, BACNET_REINIT_IDLE = 255 } }
mit
C#
6f5d7d8d74d099492901a40d6e660689cace84f4
fix type
autumn009/TanoCSharpSamples
Chap15/C15Q4/C15Q4/Program.cs
Chap15/C15Q4/C15Q4/Program.cs
using System; class Program { static void Main(string[] args) { var a = ?; Console.WriteLine(a is object); } }
using System; class Program { static void Main(string[] args) { int a = ?; Console.WriteLine(a is object); } }
mit
C#
f2ad5515fa0ce4b8f6d3cec5a913e2f7ac48b2c7
add new AudioRenderer component and comment out the first gui
TUD-INF-IAI-MCI/BrailleIO,TUD-INF-IAI-MCI/BrailleIO,TUD-INF-IAI-MCI/BrailleIO,TUD-INF-IAI-MCI/BrailleIO
BrailleIO/Structs/BoxModel.cs
BrailleIO/Structs/BoxModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BrailleIO.Structs { public struct BoxModel { public uint Top; public uint Bottom; public uint Left; public uint Right; /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return "Box: " + Top + "," + Right + "," + Bottom + "," + Left; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return (obj is BoxModel) && (Top == ((BoxModel)obj).Top) && (Right == ((BoxModel)obj).Right) && (Bottom == ((BoxModel)obj).Bottom) && (Left == ((BoxModel)obj).Left); } public override int GetHashCode() { return base.GetHashCode(); } public BoxModel(uint top, uint right, uint bottom, uint left) { Top = top; Right = right; Bottom = bottom; Left = left; } public BoxModel(uint top, uint horizontal, uint bottom) : this(top, horizontal, bottom, horizontal) { } public BoxModel(uint vertical, uint horizontal) : this(vertical, horizontal, vertical) { } public BoxModel(uint width) : this(width, width) { } public void Clear() { Top = Right = Bottom = Left = 0; } public bool HasBox() { return (Top > 0) || (Right > 0) || (Bottom > 0) || (Left > 0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BrailleIO.Structs { public struct BoxModel { public uint Top; public uint Bottom; public uint Left; public uint Right; /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return "Box: " + Top + "," + Right + "," + Bottom + "," + Left; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return (obj is BoxModel) && (Top == ((BoxModel)obj).Top) && (Right == ((BoxModel)obj).Right) && (Bottom == ((BoxModel)obj).Bottom) && (Left == ((BoxModel)obj).Left); } public BoxModel(uint top, uint right, uint bottom, uint left) { Top = top; Right = right; Bottom = bottom; Left = left; } public BoxModel(uint top, uint horizontal, uint bottom) : this(top, horizontal, bottom, horizontal){} public BoxModel(uint vertical, uint horizontal) : this(vertical, horizontal, vertical){} public BoxModel(uint width): this(width, width){} public void Clear() { Top = Right = Bottom = Left = 0; } public bool HasBox() { return (Top > 0) || (Right > 0) || (Bottom > 0) || (Left > 0); } } }
bsd-2-clause
C#
9be8e34e886180b7d37aff9cefd1e1d10aedbf45
Add another RunProject function with args to script.
christianrondeau/SikuliSharp,christianrondeau/SikuliSharp
SikuliSharp/Sikuli.cs
SikuliSharp/Sikuli.cs
using System; using System.IO; namespace SikuliSharp { public static class Sikuli { public static ISikuliSession CreateSession() { return new SikuliSession(CreateRuntime()); } public static SikuliRuntime CreateRuntime() { return new SikuliRuntime( new AsyncDuplexStreamsHandlerFactory(), new SikuliScriptProcessFactory() ); } public static string RunProject(string projectPath) { if (projectPath == null) throw new ArgumentNullException("projectPath"); if(!Directory.Exists(projectPath)) throw new DirectoryNotFoundException(string.Format("Project not found in path '{0}'", projectPath)); var processFactory = new SikuliScriptProcessFactory(); using (var process = processFactory.Start(string.Format("-r {0}", projectPath))) { var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return output; } } public static string RunProject(string projectPath, string args) { if (projectPath == null) throw new ArgumentNullException("projectPath"); if (!Directory.Exists(projectPath)) throw new DirectoryNotFoundException(string.Format("Project not found in path '{0}'", projectPath)); var processFactory = new SikuliScriptProcessFactory(); using (var process = processFactory.Start(string.Format("-r {0} {1}", projectPath, args))) { var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return output; } } } }
using System; using System.IO; namespace SikuliSharp { public static class Sikuli { public static ISikuliSession CreateSession() { return new SikuliSession(CreateRuntime()); } public static SikuliRuntime CreateRuntime() { return new SikuliRuntime( new AsyncDuplexStreamsHandlerFactory(), new SikuliScriptProcessFactory() ); } public static string RunProject(string projectPath) { if (projectPath == null) throw new ArgumentNullException("projectPath"); if(!Directory.Exists(projectPath)) throw new DirectoryNotFoundException(string.Format("Project not found in path '{0}'", projectPath)); var processFactory = new SikuliScriptProcessFactory(); using (var process = processFactory.Start(string.Format("-r {0}", projectPath))) { var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); return output; } } } }
mit
C#
dc6464397223cb07e09bb626e2d25d5e06a5cf89
Add readonly to RenamingFunction.dict
lou1306/CIV,lou1306/CIV
CIV/Helpers/RelabelingFunction.cs
CIV/Helpers/RelabelingFunction.cs
using System; using System.Collections; using System.Collections.Generic; namespace CIV.Helpers { public class RelabelingFunction : ICollection<KeyValuePair<string, string>> { readonly IDictionary<string, string> dict = new Dictionary<string, string>(); public int Count => dict.Count; public bool IsReadOnly => dict.IsReadOnly; /// <summary> /// Allows square-bracket indexing, i.e. relabeling[key]. /// </summary> /// <param name="key">The key to access or set.</param> public string this[string key] => dict[key]; internal bool ContainsKey(string label) => dict.ContainsKey(label); public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => dict.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => dict.GetEnumerator(); public void Add(string action, string relabeled) { if (action == Const.tau) { throw new ArgumentException("Cannot relabel tau"); } if (action.IsOutput()) { action = action.Coaction(); relabeled = relabeled.Coaction(); } dict.Add(action, relabeled); } public void Add(KeyValuePair<string, string> item) => Add(item.Key, item.Value); public void Clear() => dict.Clear(); public bool Contains(KeyValuePair<string, string> item) => dict.Contains(item); public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) => dict.CopyTo(array, arrayIndex); public bool Remove(KeyValuePair<string, string> item) => dict.Remove(item); } }
using System; using System.Collections; using System.Collections.Generic; namespace CIV.Helpers { public class RelabelingFunction : ICollection<KeyValuePair<string, string>> { IDictionary<string, string> dict = new Dictionary<string, string>(); public int Count => dict.Count; public bool IsReadOnly => dict.IsReadOnly; /// <summary> /// Allows square-bracket indexing, i.e. relabeling[key]. /// </summary> /// <param name="key">The key to access or set.</param> public string this[string key] => dict[key]; internal bool ContainsKey(string label) => dict.ContainsKey(label); public IEnumerator<KeyValuePair<string, string>> GetEnumerator() => dict.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => dict.GetEnumerator(); public void Add(string action, string relabeled) { if (action == Const.tau) { throw new ArgumentException("Cannot relabel tau"); } if (action.IsOutput()) { action = action.Coaction(); relabeled = relabeled.Coaction(); } dict.Add(action, relabeled); } public void Add(KeyValuePair<string, string> item) => Add(item.Key, item.Value); public void Clear() => dict.Clear(); public bool Contains(KeyValuePair<string, string> item) => dict.Contains(item); public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) => dict.CopyTo(array, arrayIndex); public bool Remove(KeyValuePair<string, string> item) => dict.Remove(item); } }
mit
C#
2491e11a5850f03ffe19aaac7c8e0960732fa09c
Update BradleyWyatt.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/BradleyWyatt.cs
src/Firehose.Web/Authors/BradleyWyatt.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; public class BradleyWyatt : IAmACommunityMember { public string FirstName => "Bradley"; public string LastName => "Wyatt"; public string ShortBioOrTagLine => "Finding wayt to do the most work with the least effort possible"; public string StateOrRegion => "Chicago, Illinois"; public string EmailAddress => "brad@thelazyadministrator.com"; public string GravatarHash => "c4eaa00e143c7abb1362dc9a8a48da09"; public string TwitterHandle => "bwya77"; public string GitHubHandle => "bwya77"; public Uri WebSite => new Uri("https://www.thelazyadministrator.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.thelazyadministrator.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 BradleyWyatt : IAmACommunityMember { public string FirstName => "Bradley"; public string LastName => "Wyatt"; public string ShortBioOrTagLine => "Finding wayt to do the most work with the least effort possible"; public string StateOrRegion => "Chicago, Illinois"; public string EmailAddress => "brad@thelazyadministrator.com"; public string GravatarHash => "c4eaa00e143c7abb1362dc9a8a48da09"; public string TwitterHandle => "bwya77"; public string GitHubHandle => "bwya77"; public Uri WebSite => new Uri("https://www.thelazyadministrator.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.thelazyadministrator.com/feed/"); } } } }
mit
C#
cfc99746825722539aba77e7792575716b7b41f4
Fix gravity issues.
space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Shared/Physics/MoverController.cs
Content.Shared/Physics/MoverController.cs
using Content.Shared.GameObjects.Components.Movement; using Robust.Shared.Interfaces.Physics; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Physics; namespace Content.Shared.Physics { public class MoverController : VirtualController { private Vector2 _velocity; private SharedPhysicsComponent _component = null; public Vector2 Velocity { get => _velocity; set => _velocity = value; } public override SharedPhysicsComponent ControlledComponent { set => _component = value; } public MoverController() { _velocity = Vector2.Zero; } public void Move(Vector2 velocityDirection, float speed) { if (!_component.Owner.HasComponent<MovementIgnoreGravityComponent>() && IoCManager .Resolve<IPhysicsManager>().IsWeightless(_component.Owner.Transform.GridPosition)) return; Push(velocityDirection, speed); } public void Push(Vector2 velocityDirection, float speed) { Velocity = velocityDirection * speed; } public void StopMoving() { Velocity = Vector2.Zero; } public override void UpdateBeforeProcessing() { base.UpdateBeforeProcessing(); if (Velocity == Vector2.Zero) { // Try to stop movement _component.LinearVelocity = Vector2.Zero; } else { _component.LinearVelocity = Velocity; } } } }
using Content.Shared.GameObjects.Components.Movement; using Robust.Shared.Interfaces.Physics; using Robust.Shared.IoC; using Robust.Shared.Maths; using Robust.Shared.Physics; namespace Content.Shared.Physics { public class MoverController : VirtualController { private Vector2 _velocity; private SharedPhysicsComponent _component = null; public Vector2 Velocity { get => _velocity; set => _velocity = value; } public override SharedPhysicsComponent ControlledComponent { set => _component = value; } public MoverController() { _velocity = Vector2.Zero; } public void Move(Vector2 velocityDirection, float speed) { if (!_component.Owner.HasComponent<MovementIgnoreGravityComponent>() && IoCManager .Resolve<IPhysicsManager>().IsWeightless(_component.Owner.Transform.GridPosition) && false) return; Push(velocityDirection, speed); } public void Push(Vector2 velocityDirection, float speed) { Velocity = velocityDirection * speed; } public void StopMoving() { Velocity = Vector2.Zero; } public override void UpdateBeforeProcessing() { base.UpdateBeforeProcessing(); if (Velocity == Vector2.Zero) { // Try to stop movement _component.LinearVelocity = Vector2.Zero; } else { _component.LinearVelocity = Velocity; } } } }
mit
C#
d43385c04957f07ddcc900d2bcb77b23d0ee9d87
remove redundant Serializable on ScenarioOutline
mvalipour/xbehave.net,mvalipour/xbehave.net,modulexcite/xbehave.net,xbehave/xbehave.net,modulexcite/xbehave.net,hitesh97/xbehave.net,adamralph/xbehave.net,hitesh97/xbehave.net
src/Xbehave.2.Execution.desktop/ScenarioOutline.cs
src/Xbehave.2.Execution.desktop/ScenarioOutline.cs
// <copyright file="ScenarioOutline.cs" company="xBehave.net contributors"> // Copyright (c) xBehave.net contributors. All rights reserved. // </copyright> namespace Xbehave.Execution { using System; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Xunit.Abstractions; using Xunit.Sdk; public class ScenarioOutline : XunitTestCase { public ScenarioOutline( IMessageSink diagnosticMessageSink, TestMethodDisplay defaultMethodDisplay, ITestMethod testMethod) : base(diagnosticMessageSink, defaultMethodDisplay, testMethod, null) { } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Called by the de-serializer", true)] public ScenarioOutline() { } public override async Task<RunSummary> RunAsync( IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) { return await new ScenarioOutlineRunner( diagnosticMessageSink, this, this.DisplayName, this.SkipReason, constructorArguments, messageBus, aggregator, cancellationTokenSource) .RunAsync(); } } }
// <copyright file="ScenarioOutline.cs" company="xBehave.net contributors"> // Copyright (c) xBehave.net contributors. All rights reserved. // </copyright> namespace Xbehave.Execution { using System; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Xunit.Abstractions; using Xunit.Sdk; [Serializable] public class ScenarioOutline : XunitTestCase { public ScenarioOutline( IMessageSink diagnosticMessageSink, TestMethodDisplay defaultMethodDisplay, ITestMethod testMethod) : base(diagnosticMessageSink, defaultMethodDisplay, testMethod, null) { } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Called by the de-serializer", true)] public ScenarioOutline() { } public override async Task<RunSummary> RunAsync( IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) { return await new ScenarioOutlineRunner( diagnosticMessageSink, this, this.DisplayName, this.SkipReason, constructorArguments, messageBus, aggregator, cancellationTokenSource) .RunAsync(); } } }
mit
C#
fffc89e1743581ef988d5a5d8ebb7f1f246647f8
Revert "measure time of GetSharedSecret"
hanswolff/curve25519,Mun1z/curve25519
Curve25519.Tests/Curve25519TimingTests.cs
Curve25519.Tests/Curve25519TimingTests.cs
using NUnit.Framework; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Elliptic.Tests { [Explicit] [TestFixture] public class Curve25519TimingTests { [Test] public void Curve25519_GetPublicKey() { var millis = new List<long>(); for (int i = 0; i < 255; i++) { byte[] privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes((byte)i, 32)); Curve25519.GetPublicKey(privateKey); Stopwatch stopwatch = Stopwatch.StartNew(); for (int j = 0; j < 100; j++) { Curve25519.GetPublicKey(privateKey); } millis.Add(stopwatch.ElapsedMilliseconds); } var text = new StringBuilder(); foreach (var ms in millis) text.Append(ms + ","); Assert.Inconclusive(text.ToString()); } } }
using NUnit.Framework; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Elliptic.Tests { [Explicit] [TestFixture] public class Curve25519TimingTests { [Test] public void Curve25519_GetPublicKey() { var millis = new List<long>(); for (var i = 0; i < 255; i++) { var privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes((byte)i, 32)); Curve25519.GetPublicKey(privateKey); var stopwatch = Stopwatch.StartNew(); for (var j = 0; j < 100; j++) { Curve25519.GetPublicKey(privateKey); } millis.Add(stopwatch.ElapsedMilliseconds); } var text = new StringBuilder(); foreach (var ms in millis) text.Append(ms + ","); Assert.Inconclusive(text.ToString()); } [Test] public void Curve25519_GetSharedSecret() { var millis = new List<long>(); for (var i = 0; i < 255; i++) { var privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes((byte)i, 32)); var publicKey = Curve25519.GetPublicKey(privateKey); Curve25519.GetSharedSecret(privateKey, publicKey); var stopwatch = Stopwatch.StartNew(); for (var j = 0; j < 100; j++) { Curve25519.GetSharedSecret(privateKey, publicKey); } millis.Add(stopwatch.ElapsedMilliseconds); } var text = new StringBuilder(); foreach (var ms in millis) text.Append(ms + ","); Assert.Inconclusive(text.ToString()); } } }
apache-2.0
C#
515d736da51bf2dc595684b3545f8fe5a29108e5
clean up Defines from old roles constants
ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth
GalleryMVC_With_Auth/Resources/Defines.cs
GalleryMVC_With_Auth/Resources/Defines.cs
using System.Collections.Generic; namespace GalleryMVC_With_Auth.Resources { public static class Defines { public const string DbConnName = "DBcon"; public const string NPasswd = "Новый пароль"; public const string ConfNewPasswd = "Подтвердите новый пароль"; public const string CurPasswd = "Текущий(старый) пароль"; public const string Passwd = "Пароль"; public const string PhNumb = "Телефонный номер"; public const string Code = "Код"; public const string Email = "Электронная почта"; public const string RemBrws = "Запомнить этот браузер?"; public const string RemMe = "Запомнить меня?"; public const int PassMinLength = 6; public const string ErrView = "Error"; public const string LockOutView = "Lockout"; public const string SendCodeView = "SendCode"; public const string RolesName = "Name"; public const string IndexView = "Index"; public const string HomeControllerName = "Home"; public const string AccountControllName = "Account"; public const string ResetPasswdConfView = "ResetPasswordConfirmation"; public const string ConfEmailView = "ConfirmEmail"; public const string ForgotPasswdConfView = "ForgotPasswordConfirmation"; public const string ExtLoginCallbackView = "ExternalLoginCallback"; public const string ExtLogiConfView = "ExternalLoginConfirmation"; public const string ManageControllerName = "Manage"; public const string LoginView = "Login"; public const string LoginPath = "/Account/Login"; public const string ExtLoginFailView = "ExternalLoginFailure"; public const string ManageLoginsView = "ManageLogins"; public const string VerifPhoneNumbView = "VerifyPhoneNumber"; public const string LinkLoginCallbackView = "LinkLoginCallback"; public const int Painting = 3; public const int Watercolor = 5; public const int Gouache = 6; public const int Graphics = 1; public const int Batik = 2; public const int Pastel = 4; } }
namespace GalleryMVC_With_Auth.Resources { public static class Defines { public const string DbConnName = "DBcon"; public const string NPasswd = "Новый пароль"; public const string ConfNewPasswd = "Подтвердите новый пароль"; public const string CurPasswd = "Текущий(старый) пароль"; public const string Passwd = "Пароль"; public const string PhNumb = "Телефонный номер"; public const string Code = "Код"; public const string Email = "Электронная почта"; public const string RemBrws = "Запомнить этот браузер?"; public const string RemMe = "Запомнить меня?"; public const int PassMinLength = 6; public const string ErrView = "Error"; public const string LockOutView = "Lockout"; public const string SendCodeView = "SendCode"; public const string RolesName = "Name"; public const string IndexView = "Index"; public const string HomeControllerName = "Home"; public const string AccountControllName = "Account"; public const string ResetPasswdConfView = "ResetPasswordConfirmation"; public const string ConfEmailView = "ConfirmEmail"; public const string ForgotPasswdConfView = "ForgotPasswordConfirmation"; public const string ExtLoginCallbackView = "ExternalLoginCallback"; public const string ExtLogiConfView = "ExternalLoginConfirmation"; public const string ManageControllerName = "Manage"; public const string LoginView = "Login"; public const string LoginPath = "/Account/Login"; public const string ExtLoginFailView = "ExternalLoginFailure"; public const string ManageLoginsView = "ManageLogins"; public const string VerifPhoneNumbView = "VerifyPhoneNumber"; public const string LinkLoginCallbackView = "LinkLoginCallback"; public const int Painting = 3; public const int Watercolor = 5; public const int Gouache = 6; public const int Graphics = 1; public const int Batik = 2; public const int Pastel = 4; public const string AdminRole = "Administrator"; public const string UserRole = "User"; public const string Roles = AdminRole + "," + UserRole; } }
apache-2.0
C#
50c70a21ccfa007bfff01efb3245cc85ba0a9874
Make LogManager.Initialize static
SaberSnail/GoldenAnvil.Utility
GoldenAnvil.Utility/Logging/LogManager.cs
GoldenAnvil.Utility/Logging/LogManager.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace GoldenAnvil.Utility.Logging { public sealed class LogManager { public static ILogSource CreateLogSource(string name) { return new LogSource(name); } public static void Initialize(params ILogDestination[] destinations) { if (s_instance != s_nullManager) throw new InvalidOperationException($"{nameof(LogManager)} has already been initialized."); s_instance = new LogManager(destinations); } internal static LogManager Instance => s_instance; internal void LogMessage(LogSeverity severity, string message) { foreach (var destination in m_destinations) destination.LogMessage(severity, message); } private LogManager(IEnumerable<ILogDestination> destinations) { m_destinations = destinations.EmptyIfNull().ToList().AsReadOnly(); } static readonly LogManager s_nullManager = new LogManager(null); static LogManager s_instance = s_nullManager; readonly ReadOnlyCollection<ILogDestination> m_destinations; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace GoldenAnvil.Utility.Logging { public sealed class LogManager { public static ILogSource CreateLogSource(string name) { return new LogSource(name); } public void Initialize(params ILogDestination[] destinations) { if (s_instance != s_nullManager) throw new InvalidOperationException($"{nameof(LogManager)} has already been initialized."); s_instance = new LogManager(destinations); } internal static LogManager Instance => s_instance; internal void LogMessage(LogSeverity severity, string message) { foreach (var destination in m_destinations) destination.LogMessage(severity, message); } private LogManager(IEnumerable<ILogDestination> destinations) { m_destinations = destinations.EmptyIfNull().ToList().AsReadOnly(); } static readonly LogManager s_nullManager = new LogManager(null); static LogManager s_instance = s_nullManager; readonly ReadOnlyCollection<ILogDestination> m_destinations; } }
mit
C#
a30e0782b3d7dd509df5f365ad31391abaa1eaef
Update Box.cs
dimmpixeye/Unity3dTools
Runtime/LibProcessors/Box.cs
Runtime/LibProcessors/Box.cs
// Project : ACTORS // Contacts : Pixeye - ask@pixeye.games using System; using System.Collections.Generic; using UnityEngine; using Object = UnityEngine.Object; namespace Pixeye.Framework { /// <summary> /// <para>Caches / return assets that Developer takes from the Resources folder. /// Box cleans cache when scene reloads.</para> /// </summary> public class Box : IKernel, IDisposable { /// <summary> /// <para>Caches / return assets that Developer takes from the Resources folder. /// Box cleans cache when scene reloads.</para> /// </summary> public static Box Default = new Box(); public static readonly string path = "/{0}"; internal Dictionary<int, Object> items = new Dictionary<int, Object>(20, FastComparable.Default); Dictionary<int, string> itemsPaths = new Dictionary<int, string>(20, FastComparable.Default); public static int StringToHash(string val) { var hash = val.GetHashCode(); Default.itemsPaths.Add(hash, val); return hash; } public static T Load<T>(string id) where T : Object { return Resources.Load<T>(id); } public static T[] LoadAll<T>(string id) where T : Object { return Resources.LoadAll<T>(id); } public static T[] LoadAll<T>(string id, int amount) where T : UnityEngine.Object { storage = new T[amount]; for (int i = 0; i < amount; i++) storage[i] = Resources.Load<T>($"{id} {amount}"); return storage; } public static T Get<T>(string id) where T : Object { Object obj; var key = id.GetHashCode(); var hasValue = Default.items.TryGetValue(key, out obj); if (hasValue == false) { obj = Resources.Load<T>(id); Default.items.Add(key, obj); } return obj as T; } public static T Get<T>(int id) where T : Object { Object obj; if (Default.items.TryGetValue(id, out obj)) return obj as T; obj = Resources.Load(Default.itemsPaths[id]); Default.items.Add(id, obj); return obj as T; } public void Dispose() { items.Clear(); itemsPaths.Clear(); } } }
// Project : ACTORS // Contacts : Pixeye - ask@pixeye.games using System; using System.Collections.Generic; using UnityEngine; using Object = UnityEngine.Object; namespace Pixeye.Framework { /// <summary> /// <para>Caches / return assets that Developer takes from the Resources folder. /// Box cleans cache when scene reloads.</para> /// </summary> public class Box : IKernel, IDisposable { /// <summary> /// <para>Caches / return assets that Developer takes from the Resources folder. /// Box cleans cache when scene reloads.</para> /// </summary> public static Box Default = new Box(); public static readonly string path = "/{0}"; internal Dictionary<int, Object> items = new Dictionary<int, Object>(20, FastComparable.Default); Dictionary<int, string> itemsPaths = new Dictionary<int, string>(20, FastComparable.Default); public static int StringToHash(string val) { var hash = val.GetHashCode(); Default.itemsPaths.Add(hash, val); return hash; } public static T Load<T>(string id) where T : Object { return Resources.Load<T>(id); } public static T[] LoadAll<T>(string id) where T : Object { return Resources.LoadAll<T>(id); } public static T Get<T>(string id) where T : Object { Object obj; var key = id.GetHashCode(); var hasValue = Default.items.TryGetValue(key, out obj); if (hasValue == false) { obj = Resources.Load<T>(id); Default.items.Add(key, obj); } return obj as T; } public static T Get<T>(int id) where T : Object { Object obj; if (Default.items.TryGetValue(id, out obj)) return obj as T; obj = Resources.Load(Default.itemsPaths[id]); Default.items.Add(id, obj); return obj as T; } public void Dispose() { items.Clear(); itemsPaths.Clear(); } } }
mit
C#
ea4e434dfddb107661e715b3e9ffaf3b87644de1
Change HUD chat prefixes to avoid confusion with IRC player chat.
fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game
game/client/ui/hud/messageHud.cs
game/client/ui/hud/messageHud.cs
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Enter Chat Message Hud //---------------------------------------------------------------------------- //------------------------------------------------------------------------------ function MessageHud::open(%this) { %offset = 6; if(%this.isVisible()) return; if(%this.isTeamMsg) %text = "TEAM CHAT:"; else %text = "ARENA CHAT:"; MessageHud_Text.setValue(%text); %windowPos = "0 " @ ( getWord( outerChatHud.position, 1 ) + getWord( outerChatHud.extent, 1 ) + 1 ); %windowExt = getWord( OuterChatHud.extent, 0 ) @ " " @ getWord( MessageHud_Frame.extent, 1 ); %textExtent = getWord(MessageHud_Text.extent, 0) + 14; %ctrlExtent = getWord(MessageHud_Frame.extent, 0); Canvas.pushDialog(%this); messageHud_Frame.position = %windowPos; messageHud_Frame.extent = %windowExt; MessageHud_Edit.position = setWord(MessageHud_Edit.position, 0, %textExtent + %offset); MessageHud_Edit.extent = setWord(MessageHud_Edit.extent, 0, %ctrlExtent - %textExtent - (2 * %offset)); %this.setVisible(true); deactivateKeyboard(); MessageHud_Edit.makeFirstResponder(true); } //------------------------------------------------------------------------------ function MessageHud::close(%this) { if(!%this.isVisible()) return; Canvas.popDialog(%this); %this.setVisible(false); if ( $enableDirectInput ) activateKeyboard(); MessageHud_Edit.setValue(""); } //------------------------------------------------------------------------------ function MessageHud::toggleState(%this) { if(%this.isVisible()) %this.close(); else %this.open(); } //------------------------------------------------------------------------------ function MessageHud_Edit::onEscape(%this) { MessageHud.close(); } //------------------------------------------------------------------------------ function MessageHud_Edit::eval(%this) { %text = trim(%this.getValue()); if(%text !$= "") { if(MessageHud.isTeamMsg) commandToServer('teamMessageSent', %text); else commandToServer('messageSent', %text); } MessageHud.close(); }
//------------------------------------------------------------------------------ // Revenge Of The Cats: Ethernet // Copyright (C) 2008, mEthLab Interactive //------------------------------------------------------------------------------ //----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Enter Chat Message Hud //---------------------------------------------------------------------------- //------------------------------------------------------------------------------ function MessageHud::open(%this) { %offset = 6; if(%this.isVisible()) return; if(%this.isTeamMsg) %text = "TEAM:"; else %text = "GLOBAL:"; MessageHud_Text.setValue(%text); %windowPos = "0 " @ ( getWord( outerChatHud.position, 1 ) + getWord( outerChatHud.extent, 1 ) + 1 ); %windowExt = getWord( OuterChatHud.extent, 0 ) @ " " @ getWord( MessageHud_Frame.extent, 1 ); %textExtent = getWord(MessageHud_Text.extent, 0) + 14; %ctrlExtent = getWord(MessageHud_Frame.extent, 0); Canvas.pushDialog(%this); messageHud_Frame.position = %windowPos; messageHud_Frame.extent = %windowExt; MessageHud_Edit.position = setWord(MessageHud_Edit.position, 0, %textExtent + %offset); MessageHud_Edit.extent = setWord(MessageHud_Edit.extent, 0, %ctrlExtent - %textExtent - (2 * %offset)); %this.setVisible(true); deactivateKeyboard(); MessageHud_Edit.makeFirstResponder(true); } //------------------------------------------------------------------------------ function MessageHud::close(%this) { if(!%this.isVisible()) return; Canvas.popDialog(%this); %this.setVisible(false); if ( $enableDirectInput ) activateKeyboard(); MessageHud_Edit.setValue(""); } //------------------------------------------------------------------------------ function MessageHud::toggleState(%this) { if(%this.isVisible()) %this.close(); else %this.open(); } //------------------------------------------------------------------------------ function MessageHud_Edit::onEscape(%this) { MessageHud.close(); } //------------------------------------------------------------------------------ function MessageHud_Edit::eval(%this) { %text = trim(%this.getValue()); if(%text !$= "") { if(MessageHud.isTeamMsg) commandToServer('teamMessageSent', %text); else commandToServer('messageSent', %text); } MessageHud.close(); }
lgpl-2.1
C#
6eb2d842989ddfc06f4db34c4ad75578030ef746
Add pseudostatic bodies
EasyPeasyLemonSqueezy/MadCat
MadCat/NutEngine/Physics/BodiesManager.cs
MadCat/NutEngine/Physics/BodiesManager.cs
using System.Collections.Generic; namespace NutEngine.Physics { public class BodiesManager { public HashSet<Body> Bodies { get; private set; } public HashSet<Collision> Collisions { get; private set; } public BodiesManager() { Bodies = new HashSet<Body>(); Collisions = new HashSet<Collision>(); } public void CalculateCollisions() { foreach (var body in Bodies) { // Here will be only rigid bodies foreach (var body2 in Bodies) { if (body != body2) { if (Collider.Collide(body.Shape, body2.Shape, out var manifold)) { Collisions.Add(new Collision(body, body2, manifold)); } } } } } public void ResolveCollisions() { foreach (var collision in Collisions) { Collider.ResolveCollision(collision); // After resolve collision we have to zeroes velocity (After position correction), // or we can add some "bounce" effect, it'll be awesome. // Probably we should do it in .ResolveCollision. } } public void ApplyImpulses() { foreach (var body in Bodies) { // Dirty hack for pseudostatic bodies. if (body.Mass.MassInv != 0) { body.ApplyImpulse(); } } } /// <summary> /// May the Force be with you. /// </summary> public void ApplyForces(float delta) { foreach (var body in Bodies) { // Dirty hack for pseudostatic bodies. if (body.Mass.MassInv != 0) { body.ApplyForce(delta); } } } } }
using System.Collections.Generic; namespace NutEngine.Physics { public class BodiesManager { public HashSet<Body> Bodies { get; private set; } public HashSet<Collision> Collisions { get; private set; } public BodiesManager() { Bodies = new HashSet<Body>(); Collisions = new HashSet<Collision>(); } public void CalculateCollisions() { foreach (var body in Bodies) { // Here will be only rigid bodies foreach (var body2 in Bodies) { if (body != body2) { if (Collider.Collide(body.Shape, body2.Shape, out var manifold)) { Collisions.Add(new Collision(body, body2, manifold)); } } } } } public void ResolveCollisions() { foreach (var collision in Collisions) { Collider.ResolveCollision(collision); // After resolve collision we have to zeroes velocity (After position correction), // or we can add some "bounce" effect, it'll be awesome. // Probably we should do it in .ResolveCollision. } } public void ApplyImpulses() { foreach (var body in Bodies) { body.ApplyImpulse(); } } /// <summary> /// May the Force be with you. /// </summary> public void ApplyForces(float delta) { foreach (var body in Bodies) { body.ApplyForce(delta); } } } }
mit
C#
2cdece6ae4b74f23b16076d711ff54d1ec80f327
Update Viktor.cs
FireBuddy/adevade
AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs
AdEvade/AdEvade/Data/Spells/SpecialSpells/Viktor.cs
using System; using EloBuddy; using EloBuddy.SDK; namespace AdEvade.Data.Spells.SpecialSpells { class Viktor : IChampionPlugin { static Viktor() { } public const string ChampionName = "Viktor"; public string GetChampionName() { return ChampionName; } public void LoadSpecialSpell(SpellData spellData) { if (spellData.SpellName == "ViktorDeathRay") { Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3; } } private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender != null && sender.Team != ObjectManager.Player.Team && args.SData.Name != null && args.SData.Name == "ViktorDeathRay") { var end = sender.GetWaypoints().Last().To3D(); // var missileDist = End.To2D().Distance(args.Start.To2D()); // var delay = missileDist / 1.5f + 600; // spellData.SpellDelay = delay; // SpellDetector.CreateSpellData(sender, args.Start, End, spellData); } } } }
using System; using EloBuddy; using EloBuddy.SDK; namespace AdEvade.Data.Spells.SpecialSpells { class Viktor : IChampionPlugin { static Viktor() { } public const string ChampionName = "Viktor"; public string GetChampionName() { return ChampionName; } public void LoadSpecialSpell(SpellData spellData) { if (spellData.SpellName == "ViktorDeathRay") { Obj_AI_Base.OnProcessSpellCast += Obj_AI_Base_OnProcessSpellCast3; } } private static void Obj_AI_Base_OnProcessSpellCast3(Obj_AI_Base sender, GameObjectProcessSpellCastEventArgs args) { if (sender != null && sender.Team != ObjectManager.Player.Team && args.SData.Name != null && args.SData.Name == "ViktorDeathRay") { . var End = sender.GetWaypoints().Last().To3D(); // var missileDist = End.To2D().Distance(args.Start.To2D()); // var delay = missileDist / 1.5f + 600; // spellData.SpellDelay = delay; // SpellDetector.CreateSpellData(sender, args.Start, End, spellData); } } } }
mit
C#
6c2133f1a9a279f8e833cbe86ab9e23936083908
add 2do
MartinRL/SlackTurnus,MartinRL/SlackTurnus
SlackTurnus/Controllers/HomeController.cs
SlackTurnus/Controllers/HomeController.cs
using System; using System.Collections; using System.Linq; using System.Web.Mvc; using SlackTurnus.DomainModel; using SlackTurnus.ViewModel; namespace SlackTurnus.Controllers { public class HomeController : Controller { private const string PRIMARY_SLACKER_TURNUS = "primarySlackerTurnus"; private const string SECONDARY_SLACKER_TURNUS = "secondarySlackerTurnus"; private readonly IGetSlackTurnus _getSlackTurnus; private readonly IUpdateSlackTurnus _updateSlackTurnus; public HomeController(IGetSlackTurnus getSlackTurnus, IUpdateSlackTurnus updateSlackTurnus) { _getSlackTurnus = getSlackTurnus; _updateSlackTurnus = updateSlackTurnus; } public ActionResult Index() { var primarySlackerTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var secondarySlackerTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var slackerNamePairs = primarySlackerTurnus.Zip(secondarySlackerTurnus, (primaryDictionaryEntry, secondaryDictionaryEntry) => new Tuple<string, string>((string)primaryDictionaryEntry.Key, (string)secondaryDictionaryEntry.Key)); return View(new HomeViewModel(slackerNamePairs.Reverse())); } // 2do: remove dupes public ActionResult NextPrimary() { var slackTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, PRIMARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult SkipPrimary() { var slackTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, PRIMARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult NextSecondary() { var slackTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, SECONDARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult SkipSecondary() { var slackTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, SECONDARY_SLACKER_TURNUS); return RedirectToAction("Index"); } } }
using System; using System.Collections; using System.Linq; using System.Web.Mvc; using SlackTurnus.DomainModel; using SlackTurnus.ViewModel; namespace SlackTurnus.Controllers { public class HomeController : Controller { private const string PRIMARY_SLACKER_TURNUS = "primarySlackerTurnus"; private const string SECONDARY_SLACKER_TURNUS = "secondarySlackerTurnus"; private readonly IGetSlackTurnus _getSlackTurnus; private readonly IUpdateSlackTurnus _updateSlackTurnus; public HomeController(IGetSlackTurnus getSlackTurnus, IUpdateSlackTurnus updateSlackTurnus) { _getSlackTurnus = getSlackTurnus; _updateSlackTurnus = updateSlackTurnus; } public ActionResult Index() { var primarySlackerTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var secondarySlackerTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var slackerNamePairs = primarySlackerTurnus.Zip(secondarySlackerTurnus, (primaryDictionaryEntry, secondaryDictionaryEntry) => new Tuple<string, string>((string)primaryDictionaryEntry.Key, (string)secondaryDictionaryEntry.Key)); return View(new HomeViewModel(slackerNamePairs.Reverse())); } public ActionResult NextPrimary() { var slackTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, PRIMARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult SkipPrimary() { var slackTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, PRIMARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult NextSecondary() { var slackTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, SECONDARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult SkipSecondary() { var slackTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, SECONDARY_SLACKER_TURNUS); return RedirectToAction("Index"); } } }
mit
C#
cfa224a2fe23e04455a2994fac06bd370db621f2
delete code dupe
MartinRL/SlackTurnus,MartinRL/SlackTurnus
SlackTurnus/Controllers/HomeController.cs
SlackTurnus/Controllers/HomeController.cs
using System; using System.Collections; using System.Linq; using System.Web.Mvc; using System.Web.UI.WebControls; using SlackTurnus.DomainModel; using SlackTurnus.ViewModel; namespace SlackTurnus.Controllers { public class HomeController : Controller { private const string PRIMARY_SLACKER_TURNUS = "primarySlackerTurnus"; private const string SECONDARY_SLACKER_TURNUS = "secondarySlackerTurnus"; private readonly IGetSlackTurnus _getSlackTurnus; private readonly IUpdateSlackTurnus _updateSlackTurnus; public HomeController(IGetSlackTurnus getSlackTurnus, IUpdateSlackTurnus updateSlackTurnus) { _getSlackTurnus = getSlackTurnus; _updateSlackTurnus = updateSlackTurnus; } public ActionResult Index() { var primarySlackerTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var secondarySlackerTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var slackerNamePairs = primarySlackerTurnus.Zip(secondarySlackerTurnus, (primaryDictionaryEntry, secondaryDictionaryEntry) => new Tuple<string, string>((string)primaryDictionaryEntry.Key, (string)secondaryDictionaryEntry.Key)); return View(new HomeViewModel(slackerNamePairs.Reverse())); } private ActionResult Next(string turnus) { var slackTurnus = _getSlackTurnus.Execute(turnus); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, turnus); return RedirectToAction("Index"); } public ActionResult NextPrimary() { return Next(PRIMARY_SLACKER_TURNUS); } public ActionResult NextSecondary() { return Next(SECONDARY_SLACKER_TURNUS); } public ActionResult SkipPrimary() { var slackTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, PRIMARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult SkipSecondary() { var slackTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, SECONDARY_SLACKER_TURNUS); return RedirectToAction("Index"); } } }
using System; using System.Collections; using System.Linq; using System.Web.Mvc; using SlackTurnus.DomainModel; using SlackTurnus.ViewModel; namespace SlackTurnus.Controllers { public class HomeController : Controller { private const string PRIMARY_SLACKER_TURNUS = "primarySlackerTurnus"; private const string SECONDARY_SLACKER_TURNUS = "secondarySlackerTurnus"; private readonly IGetSlackTurnus _getSlackTurnus; private readonly IUpdateSlackTurnus _updateSlackTurnus; public HomeController(IGetSlackTurnus getSlackTurnus, IUpdateSlackTurnus updateSlackTurnus) { _getSlackTurnus = getSlackTurnus; _updateSlackTurnus = updateSlackTurnus; } public ActionResult Index() { var primarySlackerTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var secondarySlackerTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var slackerNamePairs = primarySlackerTurnus.Zip(secondarySlackerTurnus, (primaryDictionaryEntry, secondaryDictionaryEntry) => new Tuple<string, string>((string)primaryDictionaryEntry.Key, (string)secondaryDictionaryEntry.Key)); return View(new HomeViewModel(slackerNamePairs.Reverse())); } // 2do: remove dupes public ActionResult NextPrimary() { var slackTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, PRIMARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult SkipPrimary() { var slackTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, PRIMARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult NextSecondary() { var slackTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, SECONDARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult SkipSecondary() { var slackTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, SECONDARY_SLACKER_TURNUS); return RedirectToAction("Index"); } } }
mit
C#
e8b2d8c27ec259ba5a1d0b255c768058462eaa1e
Make use of Header endianness field
tmds/Tmds.DBus
Message.cs
Message.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.IO; namespace NDesk.DBus { class Message { public Message () { Header.Endianness = Connection.NativeEndianness; Header.MessageType = MessageType.MethodCall; Header.Flags = HeaderFlag.NoReplyExpected; //TODO: is this the right place to do this? Header.MajorVersion = Protocol.Version; Header.Fields = new Dictionary<FieldCode,object> (); } public Header Header; public Connection Connection; public Signature Signature { get { object o; if (Header.Fields.TryGetValue (FieldCode.Signature, out o)) return (Signature)o; else return Signature.Empty; } set { if (value == Signature.Empty) Header.Fields.Remove (FieldCode.Signature); else Header.Fields[FieldCode.Signature] = value; } } public bool ReplyExpected { get { return (Header.Flags & HeaderFlag.NoReplyExpected) == HeaderFlag.None; } set { if (value) Header.Flags &= ~HeaderFlag.NoReplyExpected; //flag off else Header.Flags |= HeaderFlag.NoReplyExpected; //flag on } } //public HeaderField[] HeaderFields; //public Dictionary<FieldCode,object>; public byte[] Body; //TODO: make use of Locked /* protected bool locked = false; public bool Locked { get { return locked; } } */ public void SetHeaderData (byte[] data) { EndianFlag endianness = (EndianFlag)data[0]; MessageReader reader = new MessageReader (endianness, data); Header = (Header)reader.ReadStruct (typeof (Header)); } public byte[] GetHeaderData () { if (Body != null) Header.Length = (uint)Body.Length; MessageWriter writer = new MessageWriter (Header.Endianness); writer.WriteValueType (Header, typeof (Header)); writer.CloseWrite (); return writer.ToArray (); } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.IO; namespace NDesk.DBus { class Message { public Message () { Header.Endianness = Connection.NativeEndianness; Header.MessageType = MessageType.MethodCall; Header.Flags = HeaderFlag.NoReplyExpected; //TODO: is this the right place to do this? Header.MajorVersion = Protocol.Version; Header.Fields = new Dictionary<FieldCode,object> (); } public Header Header; public Connection Connection; public Signature Signature { get { object o; if (Header.Fields.TryGetValue (FieldCode.Signature, out o)) return (Signature)o; else return Signature.Empty; } set { if (value == Signature.Empty) Header.Fields.Remove (FieldCode.Signature); else Header.Fields[FieldCode.Signature] = value; } } public bool ReplyExpected { get { return (Header.Flags & HeaderFlag.NoReplyExpected) == HeaderFlag.None; } set { if (value) Header.Flags &= ~HeaderFlag.NoReplyExpected; //flag off else Header.Flags |= HeaderFlag.NoReplyExpected; //flag on } } //public HeaderField[] HeaderFields; //public Dictionary<FieldCode,object>; public byte[] Body; //TODO: make use of Locked /* protected bool locked = false; public bool Locked { get { return locked; } } */ public void SetHeaderData (byte[] data) { EndianFlag endianness = (EndianFlag)data[0]; MessageReader reader = new MessageReader (endianness, data); Header = (Header)reader.ReadStruct (typeof (Header)); } public byte[] GetHeaderData () { if (Body != null) Header.Length = (uint)Body.Length; MessageWriter writer = new MessageWriter (Connection.NativeEndianness); writer.WriteValueType (Header, typeof (Header)); writer.CloseWrite (); return writer.ToArray (); } } }
mit
C#
961428b3ac684d70ca82a8f0daaee7d5ed399213
fix indent
pocketberserker/Data.HList,pocketberserker/Data.HList
examples/HList.CSharpExamples/Program.cs
examples/HList.CSharpExamples/Program.cs
using System; using CSharp.Data; namespace CSharpExamples { class Program { static void Main(string[] args) { var a = HList.Nil().Extend(true).Extend(3).Extend("Foo"); var b = HList.Nil().Extend(new [] { 1, 2 }).Extend("Bar").Extend(4.0); var zero = HAppend.Append<HCons<double, HCons<string, HCons<int[], HNil>>>>(); var one = HAppend.Append<bool, HNil, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<double, HCons<string, HCons<int[], HNil>>>, HAppend<HNil, HCons<double, HCons<string, HCons<int[], HNil>>>,HCons<double, HCons<string, HCons<int[], HNil>>>>>(zero); var two = HAppend.Append<int, HCons<bool, HNil>, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<bool, HCons<double, HCons<string, HCons<int[], HNil>>>>, HAppend<HCons<bool, HNil>, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<bool, HCons<double, HCons<string, HCons<int[], HNil>>>>>>(one); var three = HAppend.Append<string, HCons<int, HCons<bool, HNil>>, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<int, HCons<bool, HCons<double, HCons<string, HCons<int[], HNil>>>>>, HAppend<HCons<int, HCons<bool, HNil>>, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<int, HCons<bool, HCons<double, HCons<string, HCons<int[], HNil>>>>>>>(two); var x = three.Append(a, b); Console.WriteLine(x.Head); Console.WriteLine(x.Tail.Tail.Tail.Tail.Head); } } }
using System; using CSharp.Data; namespace CSharpExamples { class Program { static void Main(string[] args) { var a = HList.Nil().Extend(true).Extend(3).Extend("Foo"); var b = HList.Nil().Extend(new [] { 1, 2 }).Extend("Bar").Extend(4.0); var zero = HAppend.Append<HCons<double, HCons<string, HCons<int[], HNil>>>>(); var one = HAppend.Append<bool, HNil, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<double, HCons<string, HCons<int[], HNil>>>, HAppend<HNil, HCons<double, HCons<string, HCons<int[], HNil>>>,HCons<double, HCons<string, HCons<int[], HNil>>>>>(zero); var two = HAppend.Append<int, HCons<bool, HNil>, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<bool, HCons<double, HCons<string, HCons<int[], HNil>>>>, HAppend<HCons<bool, HNil>, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<bool, HCons<double, HCons<string, HCons<int[], HNil>>>>>>(one); var three = HAppend.Append<string, HCons<int, HCons<bool, HNil>>, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<int, HCons<bool, HCons<double, HCons<string, HCons<int[], HNil>>>>>, HAppend<HCons<int, HCons<bool, HNil>>, HCons<double, HCons<string, HCons<int[], HNil>>>, HCons<int, HCons<bool, HCons<double, HCons<string, HCons<int[], HNil>>>>>>>(two); var x = three.Append(a, b); Console.WriteLine(x.Head); Console.WriteLine(x.Tail.Tail.Tail.Tail.Head); } } }
mit
C#
4674a80cffa2f36f06fb56d8c8f8172d0366188b
Update variable names to reflect class name changes
CamTechConsultants/CvsntGitImporter
Program.cs
Program.cs
/* * John Hall <john.hall@xjtag.com> * Copyright (c) Midas Yellow Ltd. All rights reserved. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CvsGitConverter { class Program { static void Main(string[] args) { if (args.Length != 1) throw new ArgumentException("Need a cvs.log file"); var parser = new CvsLogParser(args[0]); var revisions = parser.Parse(); var commits = new Dictionary<string, Commit>(); foreach (var revision in revisions) { Commit changeSet; if (commits.TryGetValue(revision.CommitId, out changeSet)) { changeSet.Add(revision); } else { changeSet = new Commit(revision.CommitId) { revision }; commits.Add(changeSet.CommitId, changeSet); } } foreach (var commit in commits.Values.OrderBy(c => c.Time)) { Console.Out.WriteLine("Commit: {0} {1}", commit.CommitId, commit.Time); foreach (var revision in commit) Console.Out.WriteLine(" {0} r{1}", revision.File, revision.Revision); } } } }
/* * John Hall <john.hall@xjtag.com> * Copyright (c) Midas Yellow Ltd. All rights reserved. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CvsGitConverter { class Program { static void Main(string[] args) { if (args.Length != 1) throw new ArgumentException("Need a cvs.log file"); var parser = new CvsLogParser(args[0]); var commits = parser.Parse(); var changeSets = new Dictionary<string, ChangeSet>(); foreach (var commit in commits) { ChangeSet changeSet; if (changeSets.TryGetValue(commit.CommitId, out changeSet)) { changeSet.Add(commit); } else { changeSet = new ChangeSet(commit.CommitId) { commit }; changeSets.Add(changeSet.CommitId, changeSet); } } foreach (var changeSet in changeSets.Values.OrderBy(c => c.Time)) { Console.Out.WriteLine("Commit: {0} {1}", changeSet.CommitId, changeSet.Time); foreach (var commit in changeSet) Console.Out.WriteLine(" {0} r{1}", commit.File, commit.Revision); } } } }
mit
C#
e0a6ebbe5f4ca410aede12b356c16251633a9788
Fix scope of SnakeCasecontractResolver
keenlabs/keen-sdk-net
Keen/ContractResolvers/SnakeCaseContractResolver.cs
Keen/ContractResolvers/SnakeCaseContractResolver.cs
using Newtonsoft.Json.Serialization; namespace Keen.Core.ContractResolvers { /* * Found on GithubGist https://gist.github.com/crallen/9238178 * * Credit to Chris Allen https://github.com/crallen */ internal class SnakeCaseContractResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { return GetSnakeCase(propertyName); } private string GetSnakeCase(string input) { if (string.IsNullOrEmpty(input)) return input; var buffer = ""; for (var i = 0; i < input.Length; i++) { var isLast = (i == input.Length - 1); var isSecondFromLast = (i == input.Length - 2); var curr = input[i]; var next = !isLast ? input[i + 1] : '\0'; var afterNext = !isSecondFromLast && !isLast ? input[i + 2] : '\0'; buffer += char.ToLower(curr); if (!char.IsDigit(curr) && char.IsUpper(next)) { if (char.IsUpper(curr)) { if (!isLast && !isSecondFromLast && !char.IsUpper(afterNext)) buffer += "_"; } else buffer += "_"; } if (!char.IsDigit(curr) && char.IsDigit(next)) buffer += "_"; if (char.IsDigit(curr) && !char.IsDigit(next) && !isLast) buffer += "_"; } return buffer; } } }
using Newtonsoft.Json.Serialization; namespace Keen.Core.ContractResolvers { /* * Found on GithubGist https://gist.github.com/crallen/9238178 * * Credit to Chris Allen https://github.com/crallen */ public class SnakeCaseContractResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { return GetSnakeCase(propertyName); } private string GetSnakeCase(string input) { if (string.IsNullOrEmpty(input)) return input; var buffer = ""; for (var i = 0; i < input.Length; i++) { var isLast = (i == input.Length - 1); var isSecondFromLast = (i == input.Length - 2); var curr = input[i]; var next = !isLast ? input[i + 1] : '\0'; var afterNext = !isSecondFromLast && !isLast ? input[i + 2] : '\0'; buffer += char.ToLower(curr); if (!char.IsDigit(curr) && char.IsUpper(next)) { if (char.IsUpper(curr)) { if (!isLast && !isSecondFromLast && !char.IsUpper(afterNext)) buffer += "_"; } else buffer += "_"; } if (!char.IsDigit(curr) && char.IsDigit(next)) buffer += "_"; if (char.IsDigit(curr) && !char.IsDigit(next) && !isLast) buffer += "_"; } return buffer; } } }
mit
C#
f72e371c04d3aed88cd22412bbd3489b3a0534cf
Remove checking debug flag while running application.
tempbottle/VisualRust,Muraad/VisualRust,yacoder/VisualRust,drewet/VisualRust,PistonDevelopers/VisualRust,cmr/VisualRust,xilec/VisualRust,Boddlnagg/VisualRust,dlsteuer/VisualRust,yacoder/VisualRust,PistonDevelopers/VisualRust,xilec/VisualRust,drewet/VisualRust,cmr/VisualRust,Vbif/VisualRust,vadimcn/VisualRust,Stitchous/VisualRust,Stitchous/VisualRust,vosen/VisualRust,Vbif/VisualRust,vosen/VisualRust,Muraad/VisualRust,tempbottle/VisualRust,Connorcpu/VisualRust,Boddlnagg/VisualRust,dlsteuer/VisualRust,Connorcpu/VisualRust,vadimcn/VisualRust
VisualRust.Project/DefaultRustLauncher.cs
VisualRust.Project/DefaultRustLauncher.cs
using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Project; namespace VisualRust.Project { /// <summary> /// Simple realization of project launcher for executable file /// TODO need realize for library /// </summary> sealed class DefaultRustLauncher : IProjectLauncher { private readonly RustProjectNode _project; public DefaultRustLauncher(RustProjectNode project) { Utilities.ArgumentNotNull("project", project); _project = project; } public int LaunchProject(bool debug) { var startupFilePath = GetProjectStartupFile(); return LaunchFile(startupFilePath, debug); } private string GetProjectStartupFile() { var startupFilePath = Path.Combine(_project.GetProjectProperty("TargetDir"), _project.GetProjectProperty("TargetFileName")); //var startupFilePath = _project.GetStartupFile(); if (string.IsNullOrEmpty(startupFilePath)) { throw new ApplicationException("Startup file is not defined in project"); } return startupFilePath; } public int LaunchFile(string file, bool debug) { StartWithoutDebugger(file); return VSConstants.S_OK; } private void StartWithoutDebugger(string startupFile) { var processStartInfo = CreateProcessStartInfoNoDebug(startupFile); Process.Start(processStartInfo); } private ProcessStartInfo CreateProcessStartInfoNoDebug(string startupFile) { // TODO add command line arguments var commandLineArgs = string.Empty; var startInfo = new ProcessStartInfo(startupFile, commandLineArgs); startInfo.UseShellExecute = false; startInfo.WorkingDirectory = _project.GetWorkingDirectory(); return startInfo; } } }
using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Project; namespace VisualRust.Project { /// <summary> /// Simple realization of project launcher for executable file /// TODO need realize for library /// </summary> sealed class DefaultRustLauncher : IProjectLauncher { private readonly RustProjectNode _project; public DefaultRustLauncher(RustProjectNode project) { Utilities.ArgumentNotNull("project", project); _project = project; } public int LaunchProject(bool debug) { var startupFilePath = GetProjectStartupFile(); return LaunchFile(startupFilePath, debug); } private string GetProjectStartupFile() { var startupFilePath = Path.Combine(_project.GetProjectProperty("TargetDir"), _project.GetProjectProperty("TargetFileName")); //var startupFilePath = _project.GetStartupFile(); if (string.IsNullOrEmpty(startupFilePath)) { throw new ApplicationException("Startup file is not defined in project"); } return startupFilePath; } public int LaunchFile(string file, bool debug) { if (debug) { StartWithDebugger(file); } else { StartWithoutDebugger(file); } return VSConstants.S_OK; } private void StartWithoutDebugger(string startupFile) { var processStartInfo = CreateProcessStartInfoNoDebug(startupFile); Process.Start(processStartInfo); } private ProcessStartInfo CreateProcessStartInfoNoDebug(string startupFile) { // TODO add command line arguments var commandLineArgs = string.Empty; var startInfo = new ProcessStartInfo(startupFile, commandLineArgs); startInfo.UseShellExecute = false; startInfo.WorkingDirectory = _project.GetWorkingDirectory(); return startInfo; } private void StartWithDebugger(string filePath) { throw new NotImplementedException(); } } }
mit
C#
27ad04c8701cbde36559bb726c293e30f6910b96
Extend Demo Project
tommcclean/LogBook
LogBook.Demo/Program.cs
LogBook.Demo/Program.cs
using LogBook.Services; using LogBook.Services.Models; using System; namespace LogBook.Demo { internal class Program { private static void Main() { // Step 1: Initialise The Log Handler (Add Config Database Credential for LogBookEntityModel) var logHandler = new LogHandler(); // Step 2: Log Basic Information Messages logHandler.WriteLog(LogType.Information, "Welcome to LogBook", string.Empty); // Step 3: Log Exception Details try { throw new NotImplementedException("This is an example Exception"); } catch (Exception ex) { logHandler.WriteLog(LogType.Error, "LogBook.Demo.Program.cs", ex, ex.Message, string.Empty); } Console.WriteLine("Demo Log Entries have been logged. Press any key to retrieve the latest Log Entries."); Console.ReadKey(); var logEntries = logHandler.ReadLatestLogEntries(100); foreach (var entry in logEntries) { Console.WriteLine($"Log Entry: {entry.LogEntryId}. Message: {entry.Message}. Time: {entry.LogTime}. Host: {entry.HostName}."); } Console.WriteLine("Demo Log Entries have been retrieved. Press any key to terminate review number of errors today."); Console.ReadKey(); var today = DateTime.Now; var errorsToday = logHandler.ErrorsSinceTime(new DateTime(today.Year, today.Month, today.Day, 0, 0, 0)); Console.WriteLine($"Errors Today: {errorsToday}"); Console.WriteLine("Press any key to terminate the demo."); Console.ReadKey(); } } }
using LogBook.Services; using LogBook.Services.Models; using System; namespace LogBook.Demo { internal class Program { private static void Main() { // Step 1: Initialise The Log Handler (Add Config Database Credential for LogBookEntityModel) var logHandler = new LogHandler(); // Step 2: Log Basic Information Messages logHandler.WriteLog(LogType.Information, "Welcome to LogBook", string.Empty); // Step 3: Log Exception Details try { throw new NotImplementedException("This is an example Exception"); } catch (Exception ex) { logHandler.WriteLog(LogType.Error, "LogBook.Demo.Program.cs", ex, ex.Message, string.Empty); } Console.WriteLine("Demo Log Entries have been logged. Press any key to retrieve the latest Log Entries."); Console.ReadKey(); var logEntries = logHandler.ReadLatestLogEntries(100); foreach (var entry in logEntries) { Console.WriteLine($"Log Entry: {entry.LogEntryId}. Message: {entry.Message}. Time: {entry.LogTime}. Host: {entry.HostName}."); } Console.WriteLine("Demo Log Entries have been retrieved. Press any key to terminate the Demo."); Console.ReadKey(); } } }
mit
C#
ad2e2590a72976c31a09e4c058fafbb11274f7ce
test fix
clementpeihengtan/cogs,Colectica/cogs,kevinchristianson/cogs
Cogs.Tests/CogsLoaderTests.cs
Cogs.Tests/CogsLoaderTests.cs
using Cogs.Dto; using Cogs.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace Cogs.Tests { public class CogsLoaderTests { [Fact] public void LoadHamburgerModelTest() { string path = "..\\..\\..\\..\\cogsburger"; var directoryReader = new CogsDirectoryReader(); var cogsDtoModel = directoryReader.Load(path); var modelBuilder = new CogsModelBuilder(); var cogsModel = modelBuilder.Build(cogsDtoModel); // Verify we read all the item types. Assert.Equal(10, cogsModel.ItemTypes.Count); Assert.Equal(3, cogsModel.ReusableDataTypes.Count); // Verify we read all the inheritance correctly. var rollType = cogsModel.ItemTypes.First(x => x.Name == "Roll"); Assert.Equal("Breading", rollType.ExtendsTypeName); // Verify we read Topics correctly. Assert.Equal(1, cogsModel.TopicIndices.Count); // TODO Verify we read properties correctly. } } }
using Cogs.Dto; using Cogs.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xunit; namespace Cogs.Tests { public class CogsLoaderTests { [Fact] public void LoadHamburgerModelTest() { string path = "..\\..\\..\\..\\cogsburger"; var directoryReader = new CogsDirectoryReader(); var cogsDtoModel = directoryReader.Load(path); var modelBuilder = new CogsModelBuilder(); var cogsModel = modelBuilder.Build(cogsDtoModel); // Verify we read all the item types. Assert.Equal(10, cogsModel.ItemTypes.Count); Assert.Equal(2, cogsModel.ReusableDataTypes.Count); // Verify we read all the inheritance correctly. var rollType = cogsModel.ItemTypes.First(x => x.Name == "Roll"); Assert.Equal("Breading", rollType.ExtendsTypeName); // Verify we read Topics correctly. Assert.Equal(1, cogsModel.TopicIndices.Count); // TODO Verify we read properties correctly. } } }
mit
C#
ddd81c4fb88f5fcc30ebda3d888f2f246c009726
Fix for missing author info
romatthe/WPMGMT.BESScraper,TheGameSquid/WPMGMT.BESScraper
WPMGMT.BESScraper/Program.cs
WPMGMT.BESScraper/Program.cs
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Net; using RestSharp; using Dapper; using DapperExtensions; using WPMGMT.BESScraper.Model; namespace WPMGMT.BESScraper { class Program { static void Main(string[] args) { BesApi besApi = new BesApi(new Uri("https://pc120006933:52311/api/"), "iemadmin", "bigfix"); //WPMGMT.BESScraper.Model.Action action = besApi.GetAction(1854); //Actions actions = besApi.GetActions(); //ActionDetail detail = besApi.GetActionDetail(1854); WPMGMT.BESScraper.Model.Action action = new Model.Action(); action.ID = 1855; action.Name = "TEST POC TROLL"; using (SqlConnection cn = new SqlConnection(@"Data Source=10.50.20.128\YPTOSQL002LP;Initial Catalog=YPTO_WPMGMT;Integrated Security=SSPI;")) { cn.Open(); // TEST var id = cn.Insert(action); cn.Close(); } Console.Read(); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Net; using RestSharp; using Dapper; using DapperExtensions; using WPMGMT.BESScraper.Model; namespace WPMGMT.BESScraper { class Program { static void Main(string[] args) { BesApi besApi = new BesApi(new Uri("https://pc120006933:52311/api/"), "iemadmin", "bigfix"); //WPMGMT.BESScraper.Model.Action action = besApi.GetAction(1854); //Actions actions = besApi.GetActions(); //ActionDetail detail = besApi.GetActionDetail(1854); WPMGMT.BESScraper.Model.Action action = new Model.Action(); action.ID = 1855; action.Name = "TEST POC TROLL"; using (SqlConnection cn = new SqlConnection(@"Data Source=10.50.20.128\YPTOSQL002LP;Initial Catalog=YPTO_WPMGMT;Integrated Security=SSPI;")) { cn.Open(); var id = cn.Insert(action); cn.Close(); } Console.Read(); } } }
mit
C#
4456f950d448d4c998573f783f63da59e5be06a2
Remove public setter of Job properties.
mans0954/f-spot,mono/f-spot,mono/f-spot,dkoeb/f-spot,dkoeb/f-spot,mono/f-spot,mans0954/f-spot,mono/f-spot,mono/f-spot,dkoeb/f-spot,mans0954/f-spot,dkoeb/f-spot,dkoeb/f-spot,mans0954/f-spot,mans0954/f-spot,mono/f-spot,mans0954/f-spot,dkoeb/f-spot
src/Core/FSpot.Database/Jobs/Job.cs
src/Core/FSpot.Database/Jobs/Job.cs
// // Job.cs // // Author: // Mike Gemünde <mike@gemuende.de> // Stephane Delcroix <sdelcroix@src.gnome.org> // // Copyright (C) 2007-2010 Novell, Inc. // Copyright (C) 2010 Mike Gemünde // Copyright (C) 2007-2008 Stephane Delcroix // // 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 Banshee.Kernel; using FSpot.Core; using FSpot.Jobs; namespace FSpot.Database.Jobs { public abstract class Job : DbItem, IJob { public Job (IDb db, JobData jobData) : base (jobData.Id) { JobOptions = jobData.JobOptions; JobPriority = jobData.JobPriority; RunAt = jobData.RunAt; Persistent = jobData.Persistent; Db = db; } public string JobOptions { get; private set; } internal JobPriority JobPriority { get; private set; } //Not in use yet ! public DateTime RunAt { get; private set; } public bool Persistent { get; private set; } protected IDb Db { get; private set; } public event EventHandler Finished; private JobStatus status; public JobStatus Status { get { return status; } set { status = value; switch (value) { case JobStatus.Finished: case JobStatus.Failed: if (Finished != null) Finished (this, new EventArgs ()); break; default: break; } } } public void Run () { Status = JobStatus.Running; if (Execute ()) Status = JobStatus.Finished; else Status = JobStatus.Failed; } protected abstract bool Execute (); } }
// // Job.cs // // Author: // Mike Gemünde <mike@gemuende.de> // Stephane Delcroix <sdelcroix@src.gnome.org> // // Copyright (C) 2007-2010 Novell, Inc. // Copyright (C) 2010 Mike Gemünde // Copyright (C) 2007-2008 Stephane Delcroix // // 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 Banshee.Kernel; using FSpot.Core; using FSpot.Jobs; namespace FSpot.Database.Jobs { public abstract class Job : DbItem, IJob { public Job (IDb db, JobData jobData) : base (jobData.Id) { JobOptions = jobData.JobOptions; JobPriority = jobData.JobPriority; RunAt = jobData.RunAt; Persistent = jobData.Persistent; Db = db; } public string JobOptions { get; set; } internal JobPriority JobPriority { get; set; } //Not in use yet ! public DateTime RunAt { get; private set; } public bool Persistent { get; private set; } protected IDb Db { get; private set; } public event EventHandler Finished; private JobStatus status; public JobStatus Status { get { return status; } set { status = value; switch (value) { case JobStatus.Finished: case JobStatus.Failed: if (Finished != null) Finished (this, new EventArgs ()); break; default: break; } } } public void Run () { Status = JobStatus.Running; if (Execute ()) Status = JobStatus.Finished; else Status = JobStatus.Failed; } protected abstract bool Execute (); } }
mit
C#
dc5952629219a8727fe3d77cd38c5f09d6a3b8b3
Check Environment.UserInteractive instead of argument
fredrikn/PolymeliaDeploy,fredrikn/PolymeliaDeploy
src/PolymeliaDeployAgent/Program.cs
src/PolymeliaDeployAgent/Program.cs
using System; using System.Linq; using System.ServiceProcess; namespace PolymeliaDeployAgent { using PolymeliaDeploy; using PolymeliaDeploy.Controller; static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { var service = new Service(); DeployServices.ReportClient = new ReportRemoteClient(); DeployServices.ActivityClient = new ActivityRemoteClient(); if (Environment.UserInteractive) { Console.WriteLine("Start polling deploy controller for tasks..."); using(var poller = new DeployPoller()) { poller.StartPoll(); Console.ReadLine(); } return; } ServiceBase.Run(service); } } }
using System; using System.Linq; using System.ServiceProcess; namespace PolymeliaDeployAgent { using PolymeliaDeploy; using PolymeliaDeploy.Controller; static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { var service = new Service(); DeployServices.ReportClient = new ReportRemoteClient(); DeployServices.ActivityClient = new ActivityRemoteClient(); if (args.Any(arg => arg == "/c")) { Console.WriteLine("Start polling deploy controller for tasks..."); using(var poller = new DeployPoller()) { poller.StartPoll(); Console.ReadLine(); } return; } ServiceBase.Run(service); } } }
mit
C#
d5fd93b32915eabd6719e95791e87c4a373fed6c
Simplify code a little bit.
YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,davidrynn/monotouch-samples,W3SS/monotouch-samples,albertoms/monotouch-samples,andypaul/monotouch-samples,andypaul/monotouch-samples,hongnguyenpro/monotouch-samples,labdogg1003/monotouch-samples,andypaul/monotouch-samples,YOTOV-LIMITED/monotouch-samples,haithemaraissia/monotouch-samples,davidrynn/monotouch-samples,labdogg1003/monotouch-samples,xamarin/monotouch-samples,haithemaraissia/monotouch-samples,nelzomal/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,sakthivelnagarajan/monotouch-samples,hongnguyenpro/monotouch-samples,YOTOV-LIMITED/monotouch-samples,robinlaide/monotouch-samples,haithemaraissia/monotouch-samples,hongnguyenpro/monotouch-samples,kingyond/monotouch-samples,markradacz/monotouch-samples,nelzomal/monotouch-samples,robinlaide/monotouch-samples,labdogg1003/monotouch-samples,nervevau2/monotouch-samples,davidrynn/monotouch-samples,sakthivelnagarajan/monotouch-samples,a9upam/monotouch-samples,andypaul/monotouch-samples,markradacz/monotouch-samples,sakthivelnagarajan/monotouch-samples,nelzomal/monotouch-samples,W3SS/monotouch-samples,xamarin/monotouch-samples,albertoms/monotouch-samples,iFreedive/monotouch-samples,iFreedive/monotouch-samples,hongnguyenpro/monotouch-samples,labdogg1003/monotouch-samples,xamarin/monotouch-samples,peteryule/monotouch-samples,markradacz/monotouch-samples,iFreedive/monotouch-samples,davidrynn/monotouch-samples,a9upam/monotouch-samples,nervevau2/monotouch-samples,peteryule/monotouch-samples,robinlaide/monotouch-samples,a9upam/monotouch-samples,W3SS/monotouch-samples,kingyond/monotouch-samples,nelzomal/monotouch-samples,peteryule/monotouch-samples,kingyond/monotouch-samples,nervevau2/monotouch-samples,a9upam/monotouch-samples,haithemaraissia/monotouch-samples,albertoms/monotouch-samples
TextKitDemo/TextKitDemo/CollectionViewController.cs
TextKitDemo/TextKitDemo/CollectionViewController.cs
using System; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace TextKitDemo { public partial class CollectionViewController : UICollectionViewController { NSString key = new NSString ("collectionViewCell"); public CollectionViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); NavigationController.NavigationBar.BarTintColor = UIColor.White; NavigationItem.BackBarButtonItem = new UIBarButtonItem ("", UIBarButtonItemStyle.Plain, null, null); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); foreach (CollectionViewCell cell in CollectionView.VisibleCells) { var indexPath = CollectionView.IndexPathForCell (cell); cell.FormatCell (DemoModel.GetDemo(indexPath)); } } public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { CollectionViewCell cell = (CollectionViewCell) CollectionView.DequeueReusableCell (key, indexPath); if (cell == null) return null; cell.FormatCell (DemoModel.GetDemo (indexPath)); return cell; } public override int NumberOfSections (UICollectionView collectionView) { return 1; } public override int GetItemsCount (UICollectionView collectionView, int section) { return DemoModel.Demos.Count; } public override void ItemSelected (UICollectionView collectionView, NSIndexPath indexPath) { DemoModel demo = DemoModel.GetDemo (indexPath); var newViewController = (TextViewController) Storyboard.InstantiateViewController (demo.ViewControllerIdentifier); newViewController.Title = demo.Title; newViewController.model = demo; NavigationController.PushViewController (newViewController, true); return; } } }
using System; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace TextKitDemo { public partial class CollectionViewController : UICollectionViewController { NSString key = new NSString ("collectionViewCell"); public CollectionViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); NavigationController.NavigationBar.BarTintColor = UIColor.White; NavigationItem.BackBarButtonItem = new UIBarButtonItem ("", UIBarButtonItemStyle.Plain, null, null); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); foreach (CollectionViewCell cell in CollectionView.VisibleCells) { var indexPath = CollectionView.IndexPathForCell (cell); cell.FormatCell (DemoModel.GetDemo(indexPath)); } } public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { CollectionViewCell cell = (CollectionViewCell) CollectionView.DequeueReusableCell (key, indexPath); if (cell == null) return null; cell.FormatCell (DemoModel.GetDemo (indexPath)); return cell; } public override int NumberOfSections (UICollectionView collectionView) { return 1; } public override int GetItemsCount (UICollectionView collectionView, int section) { return DemoModel.Demos.Count; } public override void ItemSelected (UICollectionView collectionView, NSIndexPath indexPath) { DemoModel demo = DemoModel.GetDemo (indexPath); var newViewController = (TextViewController) Storyboard.InstantiateViewController (demo.ViewControllerIdentifier); newViewController.Title = demo.Title; newViewController.model = demo; if (newViewController != null) NavigationController.PushViewController (newViewController,true); return; } } }
mit
C#
42657a77cf51b866564c8ff2f4751173351aacac
Improve MenuItem debugger experience
MatterHackers/agg-sharp,larsbrubaker/agg-sharp,jlewin/agg-sharp
Gui/Menu/MenuItem.cs
Gui/Menu/MenuItem.cs
using System; using System.Diagnostics; namespace MatterHackers.Agg.UI { [DebuggerDisplay("{Text}:{Value}")] public class MenuItem : GuiWidget { public class MenuClosedMessage { } public event EventHandler Selected; public delegate bool CheckIfShouldClick(); public CheckIfShouldClick DoClickFunction; public string Value { get; set; } public MenuItem(GuiWidget viewItem, string value = null) { Value = value; HAnchor = UI.HAnchor.ParentLeftRight | UI.HAnchor.FitToChildren; VAnchor = UI.VAnchor.FitToChildren; AddChild(viewItem); } public override void OnMouseUp(MouseEventArgs mouseEvent) { if (DoClickFunction != null && DoClickFunction()) { if (PositionWithinLocalBounds(mouseEvent.X, mouseEvent.Y)) { if (Selected != null) { Selected(this, mouseEvent); } } } base.OnMouseUp(mouseEvent); } } }
using System; namespace MatterHackers.Agg.UI { public class MenuItem : GuiWidget { public class MenuClosedMessage { } public event EventHandler Selected; public delegate bool CheckIfShouldClick(); public CheckIfShouldClick DoClickFunction; public string Value { get; set; } public MenuItem(GuiWidget viewItem, string value = null) { Value = value; HAnchor = UI.HAnchor.ParentLeftRight | UI.HAnchor.FitToChildren; VAnchor = UI.VAnchor.FitToChildren; AddChild(viewItem); } public override void OnMouseUp(MouseEventArgs mouseEvent) { if (DoClickFunction != null && DoClickFunction()) { if (PositionWithinLocalBounds(mouseEvent.X, mouseEvent.Y)) { if (Selected != null) { Selected(this, mouseEvent); } } } base.OnMouseUp(mouseEvent); } } }
bsd-2-clause
C#
79570f88080d65254dc43facdd0ce76e6dec1380
Update Main.cs
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
LoginPasswordUtil/C-Sharp-Version/Main.cs
LoginPasswordUtil/C-Sharp-Version/Main.cs
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) 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. */ /* This is my first draft of this (C# version), it may not pass the build. */ using System; using System.Diagnostics.Process; namespace ACLoginPasswordUtil{ class Main{ int decrypt(String[] originalArgs){ int first = Int32.Parse(originalArgs[0]); int second = Int32.Parse(originalArgs[1]); int result = first + second; return result; } } }
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) 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. */ /* This is my first draft of this (C# version), it may not pass the build. */ using System.Diagnostics.Process; namespace ACLoginPasswordUtil{ class Main{ int decrypt(String[] originalArgs){ // Finding parse methods. return 0; } } }
apache-2.0
C#
e0c9a77fba9e22737d91c5158a66e96c2171d571
fix param name to match api
naveensrinivasan/octokit.net,gabrielweyer/octokit.net,khellang/octokit.net,TattsGroup/octokit.net,darrelmiller/octokit.net,SmithAndr/octokit.net,nsnnnnrn/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,editor-tools/octokit.net,octokit/octokit.net,yonglehou/octokit.net,dampir/octokit.net,shiftkey-tester/octokit.net,kolbasov/octokit.net,gdziadkiewicz/octokit.net,SLdragon1989/octokit.net,alfhenrik/octokit.net,mminns/octokit.net,brramos/octokit.net,takumikub/octokit.net,devkhan/octokit.net,dampir/octokit.net,ChrisMissal/octokit.net,shana/octokit.net,shana/octokit.net,thedillonb/octokit.net,rlugojr/octokit.net,SamTheDev/octokit.net,Sarmad93/octokit.net,ivandrofly/octokit.net,magoswiat/octokit.net,rlugojr/octokit.net,yonglehou/octokit.net,eriawan/octokit.net,khellang/octokit.net,kdolan/octokit.net,hahmed/octokit.net,thedillonb/octokit.net,shiftkey/octokit.net,hitesh97/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,michaKFromParis/octokit.net,Sarmad93/octokit.net,SamTheDev/octokit.net,octokit/octokit.net,chunkychode/octokit.net,cH40z-Lord/octokit.net,hahmed/octokit.net,Red-Folder/octokit.net,gabrielweyer/octokit.net,gdziadkiewicz/octokit.net,TattsGroup/octokit.net,octokit-net-test/octokit.net,bslliw/octokit.net,fake-organization/octokit.net,shiftkey/octokit.net,SmithAndr/octokit.net,fffej/octokit.net,ivandrofly/octokit.net,M-Zuber/octokit.net,shiftkey-tester/octokit.net,chunkychode/octokit.net,octokit-net-test-org/octokit.net,daukantas/octokit.net,alfhenrik/octokit.net,eriawan/octokit.net,editor-tools/octokit.net,forki/octokit.net,nsrnnnnn/octokit.net,geek0r/octokit.net,mminns/octokit.net,dlsteuer/octokit.net,devkhan/octokit.net,adamralph/octokit.net,octokit-net-test-org/octokit.net,M-Zuber/octokit.net
Octokit/Models/Request/NewTeam.cs
Octokit/Models/Request/NewTeam.cs
using Octokit.Internal; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; namespace Octokit { public class NewTeam { public NewTeam(string name) { Name = name; RepoNames = new Collection<string>(); Permission = Octokit.Permission.Pull; } /// <summary> /// team name /// </summary> public string Name { get; set; } /// <summary> /// permission associated to this team /// </summary> public Permission Permission { get; set; } /// <summary> /// array of repo_names this team has permissions to /// </summary> [Parameter(Key="repo_names")] public Collection<string> RepoNames { get; private set; } } }
using Octokit.Internal; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; namespace Octokit { public class NewTeam { public NewTeam(string name) { Name = name; RepoNames = new Collection<string>(); Permission = Octokit.Permission.Pull; } /// <summary> /// team name /// </summary> public string Name { get; set; } /// <summary> /// permission associated to this team /// </summary> public Permission Permission { get; set; } /// <summary> /// array of repo_names this team has permissions to /// </summary> //[Parameter(Key="repo_names")] public Collection<string> RepoNames { get; private set; } } }
mit
C#
dababde0a8b99a4c01cc9ed4a232e1b5f82e25bc
remove a suppression no longer needed
acple/ParsecSharp
ParsecSharp/GlobalSuppressions.cs
ParsecSharp/GlobalSuppressions.cs
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")]
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")] [assembly: SuppressMessage("Style", "IDE0071WithoutSuggestion")]
mit
C#
e1a0438475118492e1fe53a363b94680baa5106a
Add ProgramUnit documentation (closes #29)
felipebz/ndapi
Ndapi/ProgramUnit.cs
Ndapi/ProgramUnit.cs
using Ndapi.Core; using Ndapi.Core.Handles; using Ndapi.Enums; namespace Ndapi { /// <summary> /// Represents a program unit object. /// </summary> public class ProgramUnit : NdapiObject { /// <summary> /// Creates a program unit. /// </summary> /// <param name="module">Program unit owner.</param> /// <param name="name">Program unit name.</param> public ProgramUnit(FormModule module, string name) { Create(name, ObjectType.ProgramUnit, module); } /// <summary> /// Creates a program unit. /// </summary> /// <param name="module">Program unit owner.</param> /// <param name="name">Program unit name.</param> public ProgramUnit(MenuModule module, string name) { Create(name, ObjectType.ProgramUnit, module); } /// <summary> /// Creates a program unit. /// </summary> /// <param name="module">Program unit owner.</param> /// <param name="name">Program unit name.</param> public ProgramUnit(ObjectGroup module, string name) { Create(name, ObjectType.ProgramUnit, module); } /// <summary> /// Creates a program unit. /// </summary> /// <param name="module">Program unit owner.</param> /// <param name="name">Program unit name.</param> public ProgramUnit(ObjectLibrary module, string name) { Create(name, ObjectType.ProgramUnit, module); } internal ProgramUnit(ObjectSafeHandle handle) : base(handle) { } /// <summary> /// Gets or sets the comment. /// </summary> public string Comment { get { return GetStringProperty(NdapiConstants.D2FP_COMMENT); } set { SetStringProperty(NdapiConstants.D2FP_COMMENT, value); } } /// <summary> /// Gets or sets the program unit code. /// </summary> public string Text { get { return GetStringProperty(NdapiConstants.D2FP_PGU_TXT); } set { SetStringProperty(NdapiConstants.D2FP_PGU_TXT, value); } } /// <summary> /// Gets the program unit type. /// </summary> public ProgramUnitType Type => GetNumberProperty<ProgramUnitType>(NdapiConstants.D2FP_PGU_TYP); /// <summary> /// Compile the program unit. /// </summary> public void Compile() { var status = NativeMethods.d2fpguco_CompileObj(NdapiContext.Context, _handle); Ensure.Success(status); } } }
using Ndapi.Core; using Ndapi.Core.Handles; using Ndapi.Enums; namespace Ndapi { public class ProgramUnit : NdapiObject { public ProgramUnit(FormModule module, string name) { Create(name, ObjectType.ProgramUnit, module); } internal ProgramUnit(ObjectSafeHandle handle) : base(handle) { } public string Comment { get { return GetStringProperty(NdapiConstants.D2FP_COMMENT); } set { SetStringProperty(NdapiConstants.D2FP_COMMENT, value); } } public string Text { get { return GetStringProperty(NdapiConstants.D2FP_PGU_TXT); } set { SetStringProperty(NdapiConstants.D2FP_PGU_TXT, value); } } public ProgramUnitType Type => GetNumberProperty<ProgramUnitType>(NdapiConstants.D2FP_PGU_TYP); public void Compile() { var status = NativeMethods.d2fpguco_CompileObj(NdapiContext.Context, _handle); Ensure.Success(status); } } }
mit
C#
78992b5acfe2a558a8daade4db187cb761aa5c8e
Clean up fluent node builder to not leak implementation details
akatakritos/SassSharp
SassSharp/Ast/FluentAstBuilder.cs
SassSharp/Ast/FluentAstBuilder.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SassSharp.Ast { public class FluentAstBuilder { private IList<Node> nodes; public FluentAstBuilder() { nodes = new List<Node>(); } public FluentAstBuilder Node(string selector, Action<FluentNodeBuilder> nodeBuilder) { nodes.Add(FluentNodeBuilder.CreateNode(selector, nodeBuilder)); return this; } public SassSyntaxTree Build() { return new SassSyntaxTree(nodes); } public class FluentNodeBuilder { private IList<Declaration> declarations; private IList<Node> children; public FluentNodeBuilder(IList<Declaration> declarations, IList<Node> children) { this.declarations = declarations; this.children = children; } public void Declaration(string property, string value) { declarations.Add(new Declaration(property, value)); } public void Child(string selector, Action<FluentNodeBuilder> nodeBuilder) { children.Add(FluentNodeBuilder.CreateNode(selector, nodeBuilder)); } public static Node CreateNode(string selector, Action<FluentNodeBuilder> nodeBuilder) { var declarations = new List<Declaration>(); var children = new List<Node>(); var builder = new FluentNodeBuilder(declarations, children); nodeBuilder(builder); return Ast.Node.Create(selector, DeclarationSet.FromList(declarations), children); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SassSharp.Ast { public class FluentAstBuilder { private IList<Node> nodes; public FluentAstBuilder() { nodes = new List<Node>(); } public FluentAstBuilder Node(string selector, Action<FluentNodeBuilder> nodeBuilder) { var builder = new FluentNodeBuilder(); nodeBuilder(builder); nodes.Add(Ast.Node.Create(selector, DeclarationSet.FromList(builder.Declarations), builder.Children)); return this; } public SassSyntaxTree Build() { return new SassSyntaxTree(nodes); } public class FluentNodeBuilder { private IList<Declaration> declarations; private IList<Node> children; public FluentNodeBuilder() { declarations = new List<Declaration>(); children = new List<Node>(); } public IList<Declaration> Declarations { get { return declarations; } } public IEnumerable<Node> Children { get { return children; } } public void Declaration(string property, string value) { declarations.Add(new Declaration(property, value)); } public void Child(string selector, Action<FluentNodeBuilder> nodeBuilder) { var builder = new FluentNodeBuilder(); nodeBuilder(builder); children.Add(Ast.Node.Create(selector, DeclarationSet.FromList(builder.Declarations), builder.Children)); } } } }
mit
C#
3cbd3af925eeaa12cde145cdfb0678e8a7312b42
Fix UserAgent
Kingloo/Rdr
RdrLib/UserAgents.cs
RdrLib/UserAgents.cs
using System.Linq; namespace RdrLib.Common { public static class UserAgents { public const string Firefox_89_Windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"; public const string Edge_91_Windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59"; public const string Safari_13_1_MacOSX = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15"; public const string Chrome_85_Windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"; public const string Opera_66_Windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36 OPR/66.0.3515.72"; public const string Firefox_78ESR_Linux = "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0"; [System.Diagnostics.DebuggerStepThrough] public static string GetRandomUserAgent() { // .TickCount, measured in milliseconds, increments so quickly that the last digit is random enough for our needs return System.Environment.TickCount.ToString().Last() switch { '1' => Firefox_89_Windows, '2' => Edge_91_Windows, '3' => Safari_13_1_MacOSX, '4' => Chrome_85_Windows, '5' => Opera_66_Windows, _ => Firefox_78ESR_Linux }; } } }
using System.Linq; namespace RdrLib.Common { public static class UserAgents { public const string Firefox_89_Windows = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"; public const string Edge_91_Windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 Edg/91.0.864.59"; public const string Safari_13_1_MacOSX = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15"; public const string Chrome_85_Windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"; public const string Opera_66_Windows = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36 OPR/66.0.3515.72"; public const string Firefox_78ESR_Linux = "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0"; [System.Diagnostics.DebuggerStepThrough] public static string GetRandomUserAgent() { // .TickCount, measured in milliseconds, increments so quickly that the last digit is random enough for our needs return System.Environment.TickCount.ToString().Last() switch { '1' => Firefox_89_Windows, '2' => Edge_91_Windows, '3' => Safari_13_1_MacOSX, '4' => Chrome_85_Windows, '5' => Opera_66_Windows, _ => Firefox_78ESR_Linux }; } } }
unlicense
C#
2c37924754661ef578739f951e4387935b14167c
Remove work-in progress enum, not presently required.
PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto
Source/Eto/Forms/Menu/MenuItem.cs
Source/Eto/Forms/Menu/MenuItem.cs
#if DESKTOP using System; using System.Collections.ObjectModel; namespace Eto.Forms { public interface IMenuItem : IMenu { } public abstract class MenuItem : BaseAction { protected MenuItem (Generator g, Type type, bool initialize = true) : base(g, type, initialize) { } } public class MenuItemCollection : Collection<MenuItem> { readonly ISubMenu subMenu; public ISubMenuWidget Parent { get; private set; } public MenuItemCollection (ISubMenuWidget parent, ISubMenu parentMenu) { this.Parent = parent; this.subMenu = parentMenu; } protected override void InsertItem (int index, MenuItem item) { base.InsertItem (index, item); subMenu.AddMenu (index, item); } protected override void RemoveItem (int index) { var item = this [index]; base.RemoveItem (index); subMenu.RemoveMenu (item); } protected override void ClearItems () { base.ClearItems (); subMenu.Clear (); } } } #endif
#if DESKTOP using System; using System.Collections.ObjectModel; namespace Eto.Forms { public interface IMenuItem : IMenu { } public enum MenuItemType { Check, Image, Radio, Separator, } public abstract class MenuItem : BaseAction { protected MenuItem (Generator g, Type type, bool initialize = true) : base(g, type, initialize) { } } public class MenuItemCollection : Collection<MenuItem> { readonly ISubMenu subMenu; public ISubMenuWidget Parent { get; private set; } public MenuItemCollection (ISubMenuWidget parent, ISubMenu parentMenu) { this.Parent = parent; this.subMenu = parentMenu; } protected override void InsertItem (int index, MenuItem item) { base.InsertItem (index, item); subMenu.AddMenu (index, item); } protected override void RemoveItem (int index) { var item = this [index]; base.RemoveItem (index); subMenu.RemoveMenu (item); } protected override void ClearItems () { base.ClearItems (); subMenu.Clear (); } } } #endif
bsd-3-clause
C#
66f094d49ef59844aa3b2b4052d1467064b03fc3
fix test assembly resolver
LinqToDB4iSeries/linq2db,linq2db/linq2db,MaceWindu/linq2db,ronnyek/linq2db,LinqToDB4iSeries/linq2db,linq2db/linq2db,MaceWindu/linq2db
Tests/Linq/TestsInitialization.cs
Tests/Linq/TestsInitialization.cs
using NUnit.Framework; using System; using System.Data.Common; using System.Reflection; using Tests; /// <summary> /// 1. Don't add namespace to this class! It's intentional /// 2. This class implements test assembly setup/teardown methods. /// </summary> [SetUpFixture] public class TestsInitialization { [OneTimeSetUp] public void TestAssemblySetup() { #if !NETSTANDARD1_6 && !NETSTANDARD2_0 // configure assembly redirect for referenced assemblies to use version from GAC // this solves exception from provider-specific tests, when it tries to load version from redist folder // but loaded from GAC assembly has other version AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { var requestedAssembly = new AssemblyName(args.Name); if (requestedAssembly.Name == "IBM.Data.DB2") return DbProviderFactories.GetFactory("IBM.Data.DB2").GetType().Assembly; if (requestedAssembly.Name == "IBM.Data.Informix") return DbProviderFactories.GetFactory("IBM.Data.Informix").GetType().Assembly; return null; }; #endif // register test providers TestNoopProvider.Init(); // disabled for core, as default loader doesn't allow multiple assemblies with same name // https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/assemblyloadcontext.md #if !NETSTANDARD1_6 && !NETSTANDARD2_0 Npgsql4PostgreSQLDataProvider.Init(); #endif } [OneTimeTearDown] public void TestAssemblyTeardown() { } }
using NUnit.Framework; using System; using System.Data.Common; using System.Reflection; using Tests; /// <summary> /// 1. Don't add namespace to this class! It's intentional /// 2. This class implements test assembly setup/teardown methods. /// </summary> [SetUpFixture] public class TestsInitialization { [OneTimeSetUp] public void TestAssemblySetup() { #if !NETSTANDARD1_6 && !NETSTANDARD2_0 // configure assembly redirect for referenced assemblies to use version from GAC // this solves exception from provider-specific tests, when it tries to load version from redist folder // but loaded from GAC assembly has other version AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { var requestedAssembly = new AssemblyName(args.Name); if (requestedAssembly.Name == "IBM.Data.DB2") return DbProviderFactories.GetFactory("IBM.Data.DB2").GetType().Assembly; if (requestedAssembly.Name == "IBM.Data.Informix") //return DbProviderFactories.GetFactory("IBM.Data.Informix").GetType().Assembly; return typeof(IBM.Data.Informix.IfxTimeSpan).Assembly; return null; }; #endif // register test providers TestNoopProvider.Init(); // disabled for core, as default loader doesn't allow multiple assemblies with same name // https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/assemblyloadcontext.md #if !NETSTANDARD1_6 && !NETSTANDARD2_0 Npgsql4PostgreSQLDataProvider.Init(); #endif } [OneTimeTearDown] public void TestAssemblyTeardown() { } }
mit
C#
52eb843d51e4e7cc3ff55db3e2f8ca7dcb7014f5
Implement natural number
sakapon/Samples-2014,sakapon/Samples-2014,sakapon/Samples-2014
VerificationSample/MathConsole/Program.cs
VerificationSample/MathConsole/Program.cs
/* * このプログラムには、架空の機能が含まれます。 */ using System; namespace MathConsole { class Program { static void Main(string[] args) { NaturalNumber n = 1; // OK NaturalNumber m = -1; // Error Console.WriteLine(n + m); } } public class NaturalNumber { int i; public NaturalNumber(int i) // where i > 0 { this.i = i; } public static implicit operator int(NaturalNumber n) { return n.i; } public static implicit operator NaturalNumber(int i) { return new NaturalNumber(i); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MathConsole { class Program { static void Main(string[] args) { } } }
mit
C#
5113610b57f3ab7c1e8620b8fe580f3d095f3029
Update MainMenu.cs
afroraydude/First_Unity_Game,afroraydude/First_Unity_Game,afroraydude/First_Unity_Game
Real_Game/Assets/Scripts/MainMenu.cs
Real_Game/Assets/Scripts/MainMenu.cs
using UnityEngine; using System.Collections; using System.Runtime.Serialization.Formatters.Binary; public class MainMenu : MonoBehaviour { public GUISkin skin; public Rect title; public Rect version; public Rect playButton; public Rect quitButton; public GameManager manager; // Mostly only used to read the components in void Start () { manager = manager.GetComponent<GameManager>(); manager.StartGame(); //Destroy(gameObject); } // GUI void OnGUI() { GUI.skin = skin; /** * Offset x, offset y, object width, object height * To set the offset height of a gui item that is under another * gui item correctly, add 20 to the above gui item's * height/y offset. */ GUI.Label (title, "Afroraydude's Puzzle Game"); GUI.Label (version, "Pre Alpha Version 4"); if (GUI.Button(playButton, "Play")) { print ("Button 'Play' has been pressed!"); manager.MainMenuToLevelOne(); } if (GUI.Button(quitButton, "Quit")) { print ("Button 'Quit' has been pressed!"); Application.Quit (); } } }
using UnityEngine; using System.Collections; using System.Runtime.Serialization.Formatters.Binary; public class MainMenu : MonoBehaviour { public GUISkin skin; public Rect title; public Rect version; public Rect playButton; public Rect quitButton; public GameManager manager; // Mostly only used to read the components in void Start () { manager = manager.GetComponent<GameManager>(); //Destroy(gameObject); } // GUI void OnGUI() { GUI.skin = skin; /** * Offset x, offset y, object width, object height * To set the offset height of a gui item that is under another * gui item correctly, add 20 to the above gui item's * height/y offset. */ GUI.Label (title, "Afroraydude's Puzzle Game"); GUI.Label (version, "Pre Alpha Version 4"); if (GUI.Button(playButton, "Play")) { print ("Button 'Play' has been pressed!"); manager.MainMenuToLevelOne(); } if (GUI.Button(quitButton, "Quit")) { print ("Button 'Quit' has been pressed!"); Application.Quit (); } } }
mit
C#
6417cb21f07786efad2df51c28b848a6ec543e89
Add missing header for UnixSocket.cs file
stormleoxia/xsp,stormleoxia/xsp,arthot/xsp,arthot/xsp,arthot/xsp,murador/xsp,stormleoxia/xsp,murador/xsp,murador/xsp,arthot/xsp,stormleoxia/xsp,murador/xsp
src/Mono.WebServer.FastCgi/UnixSocket.cs
src/Mono.WebServer.FastCgi/UnixSocket.cs
// // UnixSocket.cs: Provides a wrapper around a unix domain socket file. // // Author: // Brian Nickel (brian.nickel@gmail.com) // // Copyright (C) 2007 Brian Nickel // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; namespace Mono.FastCgi { internal class UnixSocket : StandardSocket, IDisposable { string path = null; protected UnixSocket (Mono.Unix.UnixEndPoint localEndPoint) : base (System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP, localEndPoint) { } public UnixSocket (string path) : this (CreateEndPoint (path)) { this.path = path; } protected static Mono.Unix.UnixEndPoint CreateEndPoint (string path) { if (path == null) throw new ArgumentNullException ("path"); Mono.Unix.UnixEndPoint ep = new Mono.Unix.UnixEndPoint ( path); if (System.IO.File.Exists (path)) { System.Net.Sockets.Socket conn = new System.Net.Sockets.Socket ( System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); try { conn.Connect (ep); conn.Close (); throw new InvalidOperationException ( string.Format (CultureInfo.CurrentCulture, Strings.UnixSocket_AlreadyExists, path)); } catch (System.Net.Sockets.SocketException) { } System.IO.File.Delete (path); } return ep; } public void Dispose () { if (path != null) { string f = path; path = null; System.IO.File.Delete (f); } } ~UnixSocket () { Dispose (); } } }
using System; using System.Globalization; namespace Mono.FastCgi { internal class UnixSocket : StandardSocket, IDisposable { string path = null; protected UnixSocket (Mono.Unix.UnixEndPoint localEndPoint) : base (System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP, localEndPoint) { } public UnixSocket (string path) : this (CreateEndPoint (path)) { this.path = path; } protected static Mono.Unix.UnixEndPoint CreateEndPoint (string path) { if (path == null) throw new ArgumentNullException ("path"); Mono.Unix.UnixEndPoint ep = new Mono.Unix.UnixEndPoint ( path); if (System.IO.File.Exists (path)) { System.Net.Sockets.Socket conn = new System.Net.Sockets.Socket ( System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); try { conn.Connect (ep); conn.Close (); throw new InvalidOperationException ( string.Format (CultureInfo.CurrentCulture, Strings.UnixSocket_AlreadyExists, path)); } catch (System.Net.Sockets.SocketException) { } System.IO.File.Delete (path); } return ep; } public void Dispose () { if (path != null) { string f = path; path = null; System.IO.File.Delete (f); } } ~UnixSocket () { Dispose (); } } }
mit
C#
5f182c24d177bba1e00dd3b16f8ad04ab01b52c1
refactor sitesettings to dto
momcms/MoM.Modules,RolfVeinoeSorensen/MoM.Modules,momcms/MoM.Modules,RolfVeinoeSorensen/MoM.Modules,momcms/MoM.Modules,RolfVeinoeSorensen/MoM.Modules
MoM.Blog/Startup.cs
MoM.Blog/Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.EntityFrameworkCore.Infrastructure; using MoM.Module.Dtos; namespace MoM.Blog { public class Startup { public IConfigurationRoot Configuration { get; set; } IOptions<SiteSettingDto> SiteSetting; public Startup(IHostingEnvironment env, IOptions<SiteSettingDto> siteSetting) { var builder = new ConfigurationBuilder() .SetBasePath(env.WebRootPath) .AddJsonFile("../../MoM/MoM.Web/appsettings.json"); Configuration = builder.Build(); SiteSetting = siteSetting; } public void ConfigureServices(IServiceCollection services) { services.AddEntityFramework() .AddDbContext<Models.ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); } public void Configure(IApplicationBuilder app) { } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.EntityFrameworkCore.Infrastructure; using MoM.Module.Models; using MoM.Module.Config; namespace MoM.Blog { public class Startup { public IConfigurationRoot Configuration { get; set; } IOptions<SiteSetting> SiteSetting; public Startup(IHostingEnvironment env, IOptions<SiteSetting> siteSetting) { var builder = new ConfigurationBuilder() .SetBasePath(env.WebRootPath) .AddJsonFile("../../MoM/MoM.Web/appsettings.json"); Configuration = builder.Build(); SiteSetting = siteSetting; } public void ConfigureServices(IServiceCollection services) { services.AddEntityFramework() .AddDbContext<Models.ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); } public void Configure(IApplicationBuilder app) { } } }
mit
C#
a15456cbae787e591a10d98ed3da30736844e72c
Add size adjustment paramters to tunnel.
saschb2b/mugo
mugo/TunnelObject3D.cs
mugo/TunnelObject3D.cs
using System.Collections.Generic; using Engine.cgimin.object3d; using OpenTK; namespace Mugo { class TunnelObject3D : BaseObject3D { public TunnelObject3D() { Positions = new List<Vector3>(); UVs = new List<Vector2>(); Normals = new List<Vector3>(); Indices = new List<int>(); const int width = 2, height = 3, depth = 10; //left addTriangle( new Vector3(0, height, -depth), new Vector3(0, height, 0), new Vector3(0, 0, 0), Vector3.One, Vector3.One, Vector3.One, new Vector2(1, 0), new Vector2(0, 0), new Vector2(0, 1)); addTriangle( new Vector3(0, 0, 0), new Vector3(0, 0, -depth), new Vector3(0, height, -depth), Vector3.One, Vector3.One, Vector3.One, new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0)); //right addTriangle( new Vector3(width, 0, 0), new Vector3(width, height, 0), new Vector3(width, height, -depth), Vector3.One, Vector3.One, Vector3.One, new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 0)); addTriangle( new Vector3(width, height, -depth), new Vector3(width, 0, -depth), new Vector3(width, 0, 0), Vector3.One, Vector3.One, Vector3.One, new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)); //bottom addTriangle( new Vector3(width, 0, 0), new Vector3(0, 0, -depth), new Vector3(0, 0, 0), Vector3.One, Vector3.One, Vector3.One, new Vector2(0, 1), new Vector2(1, 0), new Vector2(0, 0)); addTriangle( new Vector3(width, 0, 0), new Vector3(width, 0, -depth), new Vector3(0, 0, -depth), Vector3.One, Vector3.One, Vector3.One, new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0)); //top addTriangle( new Vector3(0, height, 0), new Vector3(0, height, -depth), new Vector3(width, height, 0), Vector3.One, Vector3.One, Vector3.One, new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1)); addTriangle( new Vector3(0, height, -depth), new Vector3(width, height, -depth), new Vector3(width, height, 0), Vector3.One, Vector3.One, Vector3.One, new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)); CreateVAO(); } } }
using System.Collections.Generic; using Engine.cgimin.object3d; using OpenTK; namespace Mugo { class TunnelObject3D : BaseObject3D { public TunnelObject3D() { Positions = new List<Vector3>(); UVs = new List<Vector2>(); Normals = new List<Vector3>(); Indices = new List<int>(); const int height = 3; //left addTriangle( new Vector3(0, height, -10), new Vector3(0, height, 0), new Vector3(0, 0, 0), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(1, 0), new Vector2(0, 0), new Vector2(0, 1)); addTriangle( new Vector3(0, 0, 0), new Vector3(0, 0, -10), new Vector3(0, height, -10), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0)); //right addTriangle( new Vector3(2, 0, 0), new Vector3(2, height, 0), new Vector3(2, height, -10), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(0, 1), new Vector2(0, 0), new Vector2(1, 0)); addTriangle( new Vector3(2, height, -10), new Vector3(2, 0, -10), new Vector3(2, 0, 0), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)); //bottom addTriangle( new Vector3(2, 0, 0), new Vector3(0, 0, -10), new Vector3(0, 0, 0), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(0, 1), new Vector2(1, 0), new Vector2(0, 0)); addTriangle( new Vector3(2, 0, 0), new Vector3(2, 0, -10), new Vector3(0, 0, -10), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0)); //top addTriangle( new Vector3(0, height, 0), new Vector3(0, height, -10), new Vector3(2, height, 0), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1)); addTriangle( new Vector3(0, height, -10), new Vector3(2, height, -10), new Vector3(2, height, 0), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1)); CreateVAO(); } } }
mit
C#
82c2269e29cd7ec947c930302d421ee69e2519b1
undo changes to member code behind
neekgreen/daxko-kafka-webapp,neekgreen/daxko-kafka-webapp,neekgreen/daxko-kafka-webapp,neekgreen/daxko-kafka-webapp,neekgreen/daxko-kafka-webapp
src/WebApp/Pages/Members/Index.cshtml.cs
src/WebApp/Pages/Members/Index.cshtml.cs
namespace WebApp.Pages.Members { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Hangfire; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; public class IndexModel : PageModel { public string Message { get; set; } public void OnGet() { } public IActionResult OnPostAsync() { BackgroundJob.Enqueue(() => Console.WriteLine("this is a member job")); return Page(); } } }
namespace WebApp.Pages.Members { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Hangfire; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using MediatR; public class IndexModel : PageModel { private readonly IMediator mediator; public IndexModel(IMediator mediator) { this.mediator = mediator; } public string Message { get; set; } public void OnGet() { } public IActionResult OnPostAsync() { this.mediator.Send(new CreateCommand { NumberToCreate = 5 }); //BackgroundJob.Enqueue(() => Console.WriteLine("this is a member job")); return Page(); } } }
mit
C#
e7c71d6905264054d1a2fea31dc1c766a0bdf45c
update rotation
TheMagnificentSeven/MakeItRain
Assets/Scripts/Rotate.cs
Assets/Scripts/Rotate.cs
using UnityEngine; using System.Collections; public class Rotate : MonoBehaviour { public float speed = 1f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey (KeyCode.J)) { if(gameObject.transform.rotation.z* Time.deltaTime * speed <8.1) transform.Rotate (Vector3.back * Time.deltaTime * speed); } /*if (Input.GetKey (KeyCode.L)) transform.Rotate (Vector3.forward *speed); if (Input.GetKey (KeyCode.F)) transform.position += new Vector3 (0.0f,0.0f,speed * Time.deltaTime); if (Input.GetKey (KeyCode.S)) transform.position += new Vector3 (0.0f, 0.0f,speed * Time.deltaTime);*/ } }
using UnityEngine; using System.Collections; public class Rotate : MonoBehaviour { public float speed = 1f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey (KeyCode.J)) { Debug.Log (gameObject.transform.rotation.z* Time.deltaTime * speed); if(gameObject.transform.rotation.z* Time.deltaTime * speed <8.1) transform.Rotate (Vector3.back * Time.deltaTime * speed); } /*if (Input.GetKey (KeyCode.L)) transform.Rotate (Vector3.forward *speed); if (Input.GetKey (KeyCode.F)) transform.position += new Vector3 (0.0f,0.0f,speed * Time.deltaTime); if (Input.GetKey (KeyCode.S)) transform.position += new Vector3 (0.0f, 0.0f,speed * Time.deltaTime);*/ } }
mit
C#
614b2c95b791e696be5bfdf6ac4e1f181c73f2e7
update version
gaochundong/Cowboy.WebSockets
Cowboy.WebSockets/SolutionVersion.cs
Cowboy.WebSockets/SolutionVersion.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyDescription("Cowboy.WebSockets is a C# based library for building WebSocket services.")] [assembly: AssemblyCompany("Dennis Gao")] [assembly: AssemblyProduct("Cowboy.WebSockets")] [assembly: AssemblyCopyright("Copyright © 2015-2016 Dennis Gao")] [assembly: AssemblyTrademark("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.7.0")] [assembly: AssemblyFileVersion("1.3.7.0")] [assembly: ComVisible(false)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyDescription("Cowboy.WebSockets is a C# based library for building WebSocket services.")] [assembly: AssemblyCompany("Dennis Gao")] [assembly: AssemblyProduct("Cowboy.WebSockets")] [assembly: AssemblyCopyright("Copyright © 2015-2016 Dennis Gao")] [assembly: AssemblyTrademark("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.6.0")] [assembly: AssemblyFileVersion("1.3.6.0")] [assembly: ComVisible(false)]
mit
C#
51e9c028e7ef814210488f556b8fa1e7f6b04dae
make static
nicklasjepsen/GravatarSharp
GravatarSharp/Hashing.cs
GravatarSharp/Hashing.cs
using System.Security.Cryptography; using System.Text; namespace GravatarSharp { /// <summary> /// Used to calculate the hash /// </summary> public static class Hashing { /// <summary> /// Calculate the hash based on this MSDN post: /// http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx /// </summary> /// <param name="input">The input to hash</param> /// <returns>The hashed and lowered string</returns> public static string CalculateMd5Hash(string input) { // step 1, calculate MD5 hash from input var md5 = MD5.Create(); var inputBytes = Encoding.ASCII.GetBytes(input); var hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string var sb = new StringBuilder(); foreach (var t in hash) sb.Append(t.ToString("X2")); return sb.ToString().ToLower(); } } }
using System.Security.Cryptography; using System.Text; namespace GravatarSharp { /// <summary> /// Used to calculate the hash /// </summary> public class Hashing { /// <summary> /// Calculate the hash based on this MSDN post: /// http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx /// </summary> /// <param name="input">The input to hash</param> /// <returns>The hashed and lowered string</returns> public static string CalculateMd5Hash(string input) { // step 1, calculate MD5 hash from input var md5 = MD5.Create(); var inputBytes = Encoding.ASCII.GetBytes(input); var hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string var sb = new StringBuilder(); foreach (var t in hash) sb.Append(t.ToString("X2")); return sb.ToString().ToLower(); } } }
mit
C#
3e77378ffb47e2dc2d5bc38221b9ff196fdf3cbf
Allow full urls
mcintyre321/Noodles,mcintyre321/Noodles
Noodles/PathExtension.cs
Noodles/PathExtension.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Walkies; namespace Noodles { public static class PathExtension { static ConditionalWeakTable<object, object> urlRoots = new ConditionalWeakTable<object, object>(); public static T SetUrlRoot<T>(this T root, string urlRoot) { urlRoots.Remove(root); urlRoots.GetValue(root, r => urlRoot); return root; } public static T SetUrlRoot<T>(this T root, Func<string> getUrlRoot) { urlRoots.Remove(root); urlRoots.GetValue(root, r => getUrlRoot); return root; } public static string GetUrlRoot<T>(this T root) { var value = urlRoots.GetValue(root, r => null); if (value as Func<string> != null) return ((Func<string>) value)(); return value as string; } public static string Path(this object o) { return o.WalkedPath("/"); } public static string Url(this object o) { var walked = o.Walked(); var rootPrefix = walked.First().GetUrlRoot() ?? ""; if (!rootPrefix.EndsWith("/")) rootPrefix += "/"; if (!rootPrefix.StartsWith("/") && rootPrefix.StartsWith("http:") == false) rootPrefix = "/" + rootPrefix; return rootPrefix + String.Join("/", o.Walked().Skip(1).Select(w => w.GetFragment())); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Walkies; namespace Noodles { public static class PathExtension { static ConditionalWeakTable<object, object> urlRoots = new ConditionalWeakTable<object, object>(); public static T SetUrlRoot<T>(this T root, string urlRoot) { urlRoots.Remove(root); urlRoots.GetValue(root, r => urlRoot); return root; } public static T SetUrlRoot<T>(this T root, Func<string> getUrlRoot) { urlRoots.Remove(root); urlRoots.GetValue(root, r => getUrlRoot); return root; } public static string GetUrlRoot<T>(this T root) { var value = urlRoots.GetValue(root, r => null); if (value as Func<string> != null) return ((Func<string>) value)(); return value as string; } public static string Path(this object o) { return o.WalkedPath("/"); } public static string Url(this object o) { var walked = o.Walked(); var rootPrefix = walked.First().GetUrlRoot() ?? ""; if (!rootPrefix.EndsWith("/")) rootPrefix += "/"; if (!rootPrefix.StartsWith("/")) rootPrefix = "/" + rootPrefix; return rootPrefix + String.Join("/", o.Walked().Skip(1).Select(w => w.GetFragment())); } } }
mit
C#
327061fbc56bd484df030296bee82dd77748c1d7
Fix use of `ThreadsResponse` (type changed for threads container)
PowerShell/PowerShellEditorServices
src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ThreadsHandler.cs
src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ThreadsHandler.cs
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; namespace Microsoft.PowerShell.EditorServices.Handlers { internal class ThreadsHandler : IThreadsHandler { public Task<ThreadsResponse> Handle(ThreadsArguments request, CancellationToken cancellationToken) { return Task.FromResult(new ThreadsResponse { // TODO: This is an empty container of threads...do we need to make a thread? Threads = new Container<System.Threading.Thread>() }); } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; namespace Microsoft.PowerShell.EditorServices.Handlers { internal class ThreadsHandler : IThreadsHandler { public Task<ThreadsResponse> Handle(ThreadsArguments request, CancellationToken cancellationToken) { return Task.FromResult(new ThreadsResponse { // TODO: What do I do with these? Threads = new Container<OmniSharp.Extensions.DebugAdapter.Protocol.Models.Thread>( new OmniSharp.Extensions.DebugAdapter.Protocol.Models.Thread { Id = 1, Name = "Main Thread" }) }); } } }
mit
C#
404e47c5aefb1cbe50f70c50e81fdd1f681b0247
Revert "Revert "Revert "added try catch, test commit"""
MaurizioPz/PnP,bbojilov/PnP,durayakar/PnP,OzMakka/PnP,rbarten/PnP,weshackett/PnP,machadosantos/PnP,IvanTheBearable/PnP,comblox/PnP,biste5/PnP,Rick-Kirkham/PnP,jeroenvanlieshout/PnP,sandhyagaddipati/PnPSamples,rroman81/PnP,OfficeDev/PnP,chrisobriensp/PnP,rbarten/PnP,svarukala/PnP,andreasblueher/PnP,worksofwisdom/PnP,NavaneethaDev/PnP,Rick-Kirkham/PnP,sjuppuh/PnP,timothydonato/PnP,selossej/PnP,NexploreDev/PnP-PowerShell,Chowdarysandhya/PnPTest,erwinvanhunen/PnP,levesquesamuel/PnP,rahulsuryawanshi/PnP,SimonDoy/PnP,rbarten/PnP,miksteri/OfficeDevPnP,OneBitSoftware/PnP,bstenberg64/PnP,ifaham/Test,PieterVeenstra/PnP,erwinvanhunen/PnP,sjuppuh/PnP,JonathanHuss/PnP,IvanTheBearable/PnP,perolof/PnP,IDTimlin/PnP,kendomen/PnP,timschoch/PnP,zrahui/PnP,kendomen/PnP,pdfshareforms/PnP,gavinbarron/PnP,levesquesamuel/PnP,SuryaArup/PnP,darei-fr/PnP,pascalberger/PnP,sndkr/PnP,rgueldenpfennig/PnP,pdfshareforms/PnP,grazies/PnP,joaopcoliveira/PnP,NexploreDev/PnP-PowerShell,OneBitSoftware/PnP,OzMakka/PnP,srirams007/PnP,kevhoyt/PnP,PieterVeenstra/PnP,IDTimlin/PnP,ifaham/Test,aammiitt2/PnP,rencoreab/PnP,rgueldenpfennig/PnP,bbojilov/PnP,tomvr2610/PnP,rahulsuryawanshi/PnP,kendomen/PnP,baldswede/PnP,selossej/PnP,Anil-Lakhagoudar/PnP,BartSnyckers/PnP,GSoft-SharePoint/PnP,werocool/PnP,JBeerens/PnP,GSoft-SharePoint/PnP,JBeerens/PnP,Anil-Lakhagoudar/PnP,RickVanRousselt/PnP,sndkr/PnP,kevhoyt/PnP,valt83/PnP,grazies/PnP,Arknev/PnP,gavinbarron/PnP,werocool/PnP,gautekramvik/PnP,GeiloStylo/PnP,russgove/PnP,OfficeDev/PnP,yagoto/PnP,8v060htwyc/PnP,OneBitSoftware/PnP,valt83/PnP,srirams007/PnP,MaurizioPz/PnP,Arknev/PnP,markcandelora/PnP,machadosantos/PnP,GSoft-SharePoint/PnP,markcandelora/PnP,ifaham/Test,afsandeberg/PnP,bstenberg64/PnP,mauricionr/PnP,srirams007/PnP,edrohler/PnP,yagoto/PnP,vnathalye/PnP,PieterVeenstra/PnP,hildabarbara/PnP,pascalberger/PnP,ivanvagunin/PnP,kendomen/PnP,gavinbarron/PnP,SimonDoy/PnP,PaoloPia/PnP,patrick-rodgers/PnP,jlsfernandez/PnP,jlsfernandez/PnP,worksofwisdom/PnP,JilleFloridor/PnP,lamills1/PnP,baldswede/PnP,tomvr2610/PnP,SuryaArup/PnP,JonathanHuss/PnP,gautekramvik/PnP,mauricionr/PnP,miksteri/OfficeDevPnP,vman/PnP,r0ddney/PnP,spdavid/PnP,selossej/PnP,timothydonato/PnP,8v060htwyc/PnP,jeroenvanlieshout/PnP,ivanvagunin/PnP,NavaneethaDev/PnP,worksofwisdom/PnP,perolof/PnP,jlsfernandez/PnP,SPDoctor/PnP,joaopcoliveira/PnP,NexploreDev/PnP-PowerShell,sjuppuh/PnP,lamills1/PnP,BartSnyckers/PnP,durayakar/PnP,yagoto/PnP,8v060htwyc/PnP,rencoreab/PnP,SteenMolberg/PnP,miksteri/OfficeDevPnP,sndkr/PnP,vman/PnP,narval32/Shp,bbojilov/PnP,JilleFloridor/PnP,dalehhirt/PnP,andreasblueher/PnP,jeroenvanlieshout/PnP,zrahui/PnP,andreasblueher/PnP,SPDoctor/PnP,weshackett/PnP,vnathalye/PnP,r0ddney/PnP,Claire-Hindhaugh/PnP,IvanTheBearable/PnP,OzMakka/PnP,timothydonato/PnP,werocool/PnP,afsandeberg/PnP,SuryaArup/PnP,nishantpunetha/PnP,rroman81/PnP,hildabarbara/PnP,comblox/PnP,nishantpunetha/PnP,Anil-Lakhagoudar/PnP,edrohler/PnP,RickVanRousselt/PnP,darei-fr/PnP,russgove/PnP,weshackett/PnP,8v060htwyc/PnP,briankinsella/PnP,pbjorklund/PnP,JonathanHuss/PnP,tomvr2610/PnP,gautekramvik/PnP,grazies/PnP,ivanvagunin/PnP,grazies/PnP,bhoeijmakers/PnP,pbjorklund/PnP,r0ddney/PnP,NavaneethaDev/PnP,pascalberger/PnP,nishantpunetha/PnP,zrahui/PnP,markcandelora/PnP,brennaman/PnP,chrisobriensp/PnP,JBeerens/PnP,rroman81/PnP,PaoloPia/PnP,rgueldenpfennig/PnP,sandhyagaddipati/PnPSamples,durayakar/PnP,aammiitt2/PnP,OfficeDev/PnP,bbojilov/PnP,Rick-Kirkham/PnP,rencoreab/PnP,SteenMolberg/PnP,edrohler/PnP,perolof/PnP,Claire-Hindhaugh/PnP,shankargurav/PnP,vnathalye/PnP,BartSnyckers/PnP,PaoloPia/PnP,bhoeijmakers/PnP,timschoch/PnP,svarukala/PnP,mauricionr/PnP,pbjorklund/PnP,Chowdarysandhya/PnPTest,briankinsella/PnP,shankargurav/PnP,MaurizioPz/PnP,brennaman/PnP,Chowdarysandhya/PnPTest,Claire-Hindhaugh/PnP,patrick-rodgers/PnP,biste5/PnP,rencoreab/PnP,chrisobriensp/PnP,briankinsella/PnP,Arknev/PnP,narval32/Shp,ebbypeter/PnP,PaoloPia/PnP,darei-fr/PnP,brennaman/PnP,SteenMolberg/PnP,baldswede/PnP,ebbypeter/PnP,lamills1/PnP,biste5/PnP,OneBitSoftware/PnP,comblox/PnP,svarukala/PnP,GeiloStylo/PnP,SPDoctor/PnP,pdfshareforms/PnP,dalehhirt/PnP,vman/PnP,OfficeDev/PnP,shankargurav/PnP,aammiitt2/PnP,IDTimlin/PnP,russgove/PnP,spdavid/PnP,patrick-rodgers/PnP,narval32/Shp,JilleFloridor/PnP,SimonDoy/PnP,afsandeberg/PnP,ebbypeter/PnP,dalehhirt/PnP,Arknev/PnP,JonathanHuss/PnP,yagoto/PnP,GeiloStylo/PnP,spdavid/PnP,erwinvanhunen/PnP,levesquesamuel/PnP,valt83/PnP,ivanvagunin/PnP,kevhoyt/PnP,rahulsuryawanshi/PnP,machadosantos/PnP,pbjorklund/PnP,bstenberg64/PnP,sandhyagaddipati/PnPSamples,joaopcoliveira/PnP,RickVanRousselt/PnP,timschoch/PnP,hildabarbara/PnP,bhoeijmakers/PnP
Samples/Core.CrossDomainImages/Core.CrossDomainImagesWeb/Pages/Default.aspx.cs
Samples/Core.CrossDomainImages/Core.CrossDomainImagesWeb/Pages/Default.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Core.CrossDomainImagesWeb { public partial class Default : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { //set access token in hidden field for client calls hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb; //set images Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png"; Services.ImgService svc = new Services.ImgService(); Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Core.CrossDomainImagesWeb { public partial class Default : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { try { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { //set access token in hidden field for client calls hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb; //set images Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png"; Services.ImgService svc = new Services.ImgService(); Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png"); } } catch (Exception) { throw; } } } }
mit
C#
7d655211dba39d5affa9ae668aa62195bd17cdfd
Fix InvalidRFC3339DateTime unit test
messagebird/csharp-rest-api
Tests/UnitTests/MessageBirdUnitTests/Resources/RFC3339DateTimeConverterTest.cs
Tests/UnitTests/MessageBirdUnitTests/Resources/RFC3339DateTimeConverterTest.cs
using System; using MessageBird.Exceptions; using MessageBird.Objects; using MessageBird.Resources; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; namespace MessageBirdTests.Resources { [TestClass] public class RFC3339DateTimeConverterTest { [TestMethod] public void InvalidRFC3339DateTime() { // The following message has an invalid createDateTime format. const string JsonResultFromCreateMessage = @"{ 'id':'e7028180453e8a69d318686b17179500', 'href':'https:\/\/rest.messagebird.com\/messages\/e7028180453e8a69d318686b17179500', 'direction':'mt', 'type':'sms', 'originator':'MsgBirdSms', 'body':'Welcome to MessageBird', 'reference':null, 'validity':null, 'gateway':56, 'typeDetails':{ }, 'datacoding':'plain', 'mclass':1, 'scheduledDatetime':null, 'createdDatetime':'2014-08-11T11:18:53', 'recipients':{ 'totalCount':1, 'totalSentCount':1, 'totalDeliveredCount':0, 'totalDeliveryFailedCount':0, 'items':[ { 'recipient':31612345678, 'status':'sent', 'statusDatetime':'2014-08-11T11:18:53+00:00' } ] } }"; var recipients = new Recipients(); var message = new Message("", "", recipients); var messages = new Messages(message); try { messages.Deserialize(JsonResultFromCreateMessage); Assert.Fail("Expected an error exception, because there is an invalid rfc3339 datetime."); } catch (ErrorException e) { // The exception is thrown by the RFC3339DateTimeConverter, so the inner exception // must be of type JsonSerializationException. Assert.IsInstanceOfType(e.InnerException, typeof(JsonSerializationException)); } } } }
using MessageBird.Objects; using MessageBird.Resources; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; namespace MessageBirdTests.Resources { [TestClass] public class RFC3339DateTimeConverterTest { [TestMethod] [ExpectedException(typeof(JsonSerializationException), "A date time other than RFC3339 format was inappropriately allowed.")] public void InvalidRFC3339DateTime() { // The following message has an invalid createDateTime format. const string JsonResultFromCreateMessage = @"{ 'id':'e7028180453e8a69d318686b17179500', 'href':'https:\/\/rest.messagebird.com\/messages\/e7028180453e8a69d318686b17179500', 'direction':'mt', 'type':'sms', 'originator':'MsgBirdSms', 'body':'Welcome to MessageBird', 'reference':null, 'validity':null, 'gateway':56, 'typeDetails':{ }, 'datacoding':'plain', 'mclass':1, 'scheduledDatetime':null, 'createdDatetime':'2014-08-11T11:18:53', 'recipients':{ 'totalCount':1, 'totalSentCount':1, 'totalDeliveredCount':0, 'totalDeliveryFailedCount':0, 'items':[ { 'recipient':31612345678, 'status':'sent', 'statusDatetime':'2014-08-11T11:18:53+00:00' } ] } }"; var recipients = new Recipients(); var message = new Message("", "", recipients); var messages = new Messages(message); messages.Deserialize(JsonResultFromCreateMessage); } } }
isc
C#
df01fc82eef3fd3068a42c44776b9571b0de2fc6
Add reminder to number samples
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Order/Confirmation.cshtml
Anlab.Mvc/Views/Order/Confirmation.cshtml
@using Humanizer @model AnlabMvc.Models.Order.OrderReviewModel @{ ViewData["Title"] = "Confirmation"; } @section ActionButtons { <p> <form asp-controller="order" asp-action="Delete" asp-route-id="@Model.Order.Id" method="post" class="form-horizontal" style="margin-left: 5px;margin-right: 5px"> <button type="submit" class="btn btn-small"><i class="fa fa-trash" aria-hidden="true"></i> Delete</button> </form> <a asp-action="Edit" asp-route-id="@Model.Order.Id" class="btn btn-small">Edit Order</a> <form asp-controller="order" asp-action="Confirmation" asp-route-id="@Model.Order.Id" method="post" class="form-horizontal" style="margin-left: 5px;margin-right: 5px"> @Html.Hidden("confirm", true) <button type="submit" class="btn btn-small"> @(string.Format("{0:C}", Model.OrderDetails.Total)) Confirm Order</button> </form> </p> } <div class="col"> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> <p><strong>Please remember:</strong></p> <p>All samples must be numbered sequentially starting at #1</p> <p>If you need to send an excel file with sample descriptions, you can do that by replying to the email this order generates and attaching the file.</p> </div> @Html.Partial("_OrderDetails") </div> @section AdditionalStyles { @{ await Html.RenderPartialAsync("_DataTableStylePartial"); } } @section Scripts { @{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); } <script type="text/javascript"> $(function() { $("#table").dataTable(); }); </script> <script type="text/javascript"> $(function() { $(".showTooltip").tooltip(); }); </script> @{ await Html.RenderPartialAsync("_ShowdownScriptsPartial"); } }
@using Humanizer @model AnlabMvc.Models.Order.OrderReviewModel @{ ViewData["Title"] = "Confirmation"; } @section ActionButtons { <p> <form asp-controller="order" asp-action="Delete" asp-route-id="@Model.Order.Id" method="post" class="form-horizontal" style="margin-left: 5px;margin-right: 5px"> <button type="submit" class="btn btn-small"><i class="fa fa-trash" aria-hidden="true"></i> Delete</button> </form> <a asp-action="Edit" asp-route-id="@Model.Order.Id" class="btn btn-small">Edit Order</a> <form asp-controller="order" asp-action="Confirmation" asp-route-id="@Model.Order.Id" method="post" class="form-horizontal" style="margin-left: 5px;margin-right: 5px"> @Html.Hidden("confirm", true) <button type="submit" class="btn btn-small"> @(string.Format("{0:C}", Model.OrderDetails.Total)) Confirm Order</button> </form> </p> } <div class="col"> @Html.Partial("_OrderDetails") </div> @section AdditionalStyles { @{ await Html.RenderPartialAsync("_DataTableStylePartial"); } } @section Scripts { @{ await Html.RenderPartialAsync("_DataTableScriptsPartial"); } <script type="text/javascript"> $(function() { $("#table").dataTable(); }); </script> <script type="text/javascript"> $(function() { $(".showTooltip").tooltip(); }); </script> @{ await Html.RenderPartialAsync("_ShowdownScriptsPartial"); } }
mit
C#
e0d0e65e40cb03936c9063e5ff3e6d5038032cda
Change log verbosity stuff to be simpler.
sgrassie/wp2md.net
wp2md/Program.cs
wp2md/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Fclp; namespace wp2md { class Program { static void Main(string[] args) { Action<string> logger = msg => Console.WriteLine(msg); var parser = CreateArgsParser(); var results = parser.Parse(args); if (results.HasErrors) { Console.WriteLine(results.ErrorText); Environment.Exit(-2); } new Application(logger).Execute(parser.Object); } static FluentCommandLineBuilder<Options> CreateArgsParser() { var parser = new FluentCommandLineBuilder<Options>(); parser .SetupHelp("?", "h", "help") .UseForEmptyArgs() .Callback(help => Console.WriteLine(help)); parser .Setup(arg => arg.SourceFile).As('s', "source") .Required() .WithDescription("WordPress eXtended RSS source file."); parser .Setup(arg => arg.OutputPath) .As('o', "outputPath") .Required() .WithDescription("The output folder for generated files."); parser .Setup(arg => arg.Verbose) .As('v', "verbose") .SetDefault(false) .WithDescription("Whether to output log messages or not. (All or nothing)."); return parser; } } class Options { public string SourceFile { get; set; } public bool Verbose { get; set; } public string OutputPath { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Fclp; namespace wp2md { class Program { static void Main(string[] args) { var parser = CreateArgsParser(); var results = parser.Parse(args); if (results.HasErrors) { Console.WriteLine(results.ErrorText); Environment.Exit(-2); } var options = parser.Object; } static FluentCommandLineBuilder<Options> CreateArgsParser() { var parser = new FluentCommandLineBuilder<Options>(); parser .SetupHelp("?", "h", "help") .UseForEmptyArgs() .Callback(help => Console.WriteLine(help)); parser .Setup(arg => arg.SourceFile).As('s', "source") .Required() .WithDescription("WordPress eXtended RSS source file."); parser .Setup(arg => arg.OutputPath) .As('o', "outputPath") .Required() .WithDescription("The output folder for generated files."); parser .Setup(arg => arg.LogToFile) .As('l', "logfile") .SetDefault(string.Empty) .WithDescription("If given, logs to the specified file, instead of outputting to console"); parser .Setup(arg => arg.Verbosity) .As('v', "verbosity") .SetDefault(0) .WithDescription("Log verbosity level. 0 for no logging, 1 for only vaguely interesting stuff, 2 for... everything"); return parser; } } class Options { public string SourceFile { get; set; } public string LogToFile { get; set; } public int Verbosity { get; set; } public string OutputPath { get; set; } } }
mit
C#
fbf559c1095f4b64851595ed336801a639d78362
Remove unnecessary strings
mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati
Duplicati/Library/Backend/Storj/Strings.cs
Duplicati/Library/Backend/Storj/Strings.cs
using Duplicati.Library.Localization.Short; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Duplicati.Library.Backend.Strings { internal static class Storj { public static string DisplayName { get { return LC.L(@"Storj DCS (Decentralized Cloud Storage)"); } } public static string Description { get { return LC.L(@"This backend can read and write data to the Storj DCS."); } } public static string TestConnectionFailed { get { return LC.L(@"The connection-test failed."); } } public static string StorjAuthMethodDescriptionShort { get { return LC.L(@"The authentication method"); } } public static string StorjAuthMethodDescriptionLong { get { return LC.L(@"The authentication method describes which way to use to connect to the network - either via API key or via an access grant."); } } public static string StorjSatelliteDescriptionShort { get { return LC.L(@"The satellite"); } } public static string StorjSatelliteDescriptionLong { get { return LC.L(@"The satellite that keeps track of all metadata. Use a Storj DCS server for high-performance SLA-backed connectivity or use a community server. Or even host your own."); } } public static string StorjAPIKeyDescriptionShort { get { return LC.L(@"The API key"); } } public static string StorjAPIKeyDescriptionLong { get { return LC.L(@"The API key grants access to a specific project on your chosen satellite. Head over to the dashboard of your satellite to create one if you do not already have an API key."); } } public static string StorjSecretDescriptionShort { get { return LC.L(@"The encryption passphrase"); } } public static string StorjSecretDescriptionLong { get { return LC.L(@"The encryption passphrase is used to encrypt your data before sending it to the Storj network. This passphrase can be the only secret to provide - for Storj you do not necessary need any additional encryption (from Duplicati) in place."); } } public static string StorjSharedAccessDescriptionShort { get { return LC.L(@"The access grant"); } } public static string StorjSharedAccessDescriptionLong { get { return LC.L(@"An access grant contains all information in one encrypted string. You may use it instead of a satellite, API key and secret."); } } public static string StorjBucketDescriptionShort { get { return LC.L(@"The bucket"); } } public static string StorjBucketDescriptionLong { get { return LC.L(@"The bucket where the backup will reside in."); } } public static string StorjFolderDescriptionShort { get { return LC.L(@"The folder"); } } public static string StorjFolderDescriptionLong { get { return LC.L(@"The folder within the bucket where the backup will reside in."); } } } }
using Duplicati.Library.Localization.Short; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Duplicati.Library.Backend.Strings { internal static class Storj { public static string DisplayName { get { return LC.L(@"Storj DCS (Decentralized Cloud Storage)"); } } public static string Description { get { return LC.L(@"This backend can read and write data to the Storj DCS."); } } public static string TestConnectionFailed { get { return LC.L(@"The connection-test failed."); } } public static string StorjAuthMethodDescriptionShort { get { return LC.L(@"The authentication method"); } } public static string StorjAuthMethodDescriptionLong { get { return LC.L(@"The authentication method describes which way to use to connect to the network - either via API key or via an access grant."); } } public static string StorjSatelliteDescriptionShort { get { return LC.L(@"The satellite"); } } public static string StorjSatelliteDescriptionLong { get { return LC.L(@"The satellite that keeps track of all metadata. Use a Storj DCS server for high-performance SLA-backed connectivity or use a community server. Or even host your own."); } } public static string StorjAPIKeyDescriptionShort { get { return LC.L(@"The API key"); } } public static string StorjAPIKeyDescriptionLong { get { return LC.L(@"The API key grants access to a specific project on your chosen satellite. Head over to the dashboard of your satellite to create one if you do not already have an API key."); } } public static string StorjSecretDescriptionShort { get { return LC.L(@"The encryption passphrase"); } } public static string StorjSecretDescriptionLong { get { return LC.L(@"The encryption passphrase is used to encrypt your data before sending it to the Storj network. This passphrase can be the only secret to provide - for Storj you do not necessary need any additional encryption (from Duplicati) in place."); } } public static string StorjSecretVerifyDescriptionShort { get { return LC.L(@"The encryption passphrase (for verification)"); } } public static string StorjSecretVerifyDescriptionLong { get { return LC.L(@"The encryption passphrase verification to make sure you provided the expected value."); } } public static string StorjSharedAccessDescriptionShort { get { return LC.L(@"The access grant"); } } public static string StorjSharedAccessDescriptionLong { get { return LC.L(@"An access grant contains all information in one encrypted string. You may use it instead of a satellite, API key and secret."); } } public static string StorjBucketDescriptionShort { get { return LC.L(@"The bucket"); } } public static string StorjBucketDescriptionLong { get { return LC.L(@"The bucket where the backup will reside in."); } } public static string StorjFolderDescriptionShort { get { return LC.L(@"The folder"); } } public static string StorjFolderDescriptionLong { get { return LC.L(@"The folder within the bucket where the backup will reside in."); } } public static string StorjEncryptionPassphrasesDoNotMatchError { get { return LC.L(@"The encryption passphrases do not match"); } } } }
lgpl-2.1
C#
4736497fe4780446417975940a0601ccdc90a63a
Update ForceAdapter.cs
spaceappsnyc/issie,spaceappsnyc/issie,spaceappsnyc/issie,spaceappsnyc/issie,spaceappsnyc/issie
ISSIE-unity/Assets/Scripts/ForceAdapter.cs
ISSIE-unity/Assets/Scripts/ForceAdapter.cs
using UnityEngine; // Demo class // inherits of WebSocketUnityDelegate to receive WebSockets events public class ForceAdapter : MonoBehaviour { public WebSocketController socket; private const int NUM_STEPS_TO_HYPERDRIVE = 500; private const int HYPERDRIVE_FACTOR = 100; private bool wasNeg = true; private int numSteps = 0; // Use this for initialization void Start() { //init socket here } private WebSocketController.PowerSignal getRawPower() { return socket.getHumanPower(); } public float getHumanPower() { Debug.Log ("\nGot here!!"); //socket is initialized in the websocketcontroller onGUI() load the first time if (socket == null) { Debug.Log ("\nNo connection, no power!"); return (float)0.0; } WebSocketController.PowerSignal signal = getRawPower(); //this is raw human power //this should only return when it gets both steps not just one. if ((signal.getForce() < 0 && !wasNeg) || (signal.getForce() > 0 && wasNeg)) { wasNeg = !wasNeg; float power = getForceFactoredByExerciseType(signal.getForce(), signal.getDirection()); power = getForceFactoredByNumSteps(power, numSteps); numSteps++; return power; } return (float)0.0; } public float getForceFactoredByExerciseType(float force, WebSocketController.DIRECTION direction) { //hardcode for now float multiplier = (direction == WebSocketController.DIRECTION.UP || direction == WebSocketController.DIRECTION.DOWN) ? 2.0f : 1.0f; /* * All the logic to determine exercise types goes here * For example, if using an exercise bike, we may need multiplier = 5.0 (assume) * * */ return multiplier * force; } public float getForceFactoredByNumSteps(float force, int numSteps) { //hardcode for now if (numSteps > NUM_STEPS_TO_HYPERDRIVE) { numSteps = 0; return force * HYPERDRIVE_FACTOR; } return force; } }
using UnityEngine; // Demo class // inherits of WebSocketUnityDelegate to receive WebSockets events public class ForceAdapter : MonoBehaviour { public WebSocketController socket; private const int NUM_STEPS_TO_HYPERDRIVE = 500; private const int HYPERDRIVE_FACTOR = 100; private bool wasNeg = true; private int numSteps = 0; // Use this for initialization void Start() { //init socket here } private float getRawPower() { return socket.getHumanPower(); } public float getHumanPower() { Debug.Log ("\nGot here!!"); //socket is initialized in the websocketcontroller onGUI() load the first time if (socket == null) { Debug.Log ("\nNo connection, no power!"); return (float)0.0; } float power = getRawPower(); //this is raw human power //this should only return when it gets both steps not just one. if ((power < 0 && !wasNeg) || (power > 0 && wasNeg)) { wasNeg = !wasNeg; power = getForceFactoredByExerciseType(power); power = getForceFactoredByNumSteps(power, numSteps); numSteps++; return power; } return (float)0.0; } public float getForceFactoredByExerciseType(float force) { //hardcode for now float multiplier = (float)1.0; /* * All the logic to determine exercise types goes here * For example, if using an exercise bike, we may need multiplier = 5.0 (assume) * * */ return multiplier * force; } public float getForceFactoredByNumSteps(float force, int numSteps) { //hardcode for now if (numSteps > NUM_STEPS_TO_HYPERDRIVE) { numSteps = 0; return force * HYPERDRIVE_FACTOR; } return force; } }
mit
C#
4d48667b20fe69c968dde9e5b3148bdc2d8bdac2
Change AssemblyInfo
GAMELASTER/SteamBot,tarun200897/SteamBot,stackia/SteamBot,Alex-Nabu/CSGOWinBig-SteamBot,MadBender/SteamBot,stigping/SteamBot,alanfort/CSGOWinBig-SteamBot,TheRod1990/SteamBot,niachris/SteamBotNew,Alex-Nabu/CSGOWinBig-SteamBot,wowzone/gamerpro,fjch1997/SteamBot,Murzyneczka/CSGOWinBig-SteamBot,Schwehn42/SteamBot,ChalkyBrush/SteamBots,alanfort/CSGOWinBig-SteamBot,zigagrcar/SteamTradeOffersBot,trervorx/SteamBot,novasdream/SteamBot,MattrAus/SteamBot,terryhau/SteamBot,nuller1joe/SteamBot,wqbill/SteamBot,JackHarknes/Bot1,StormReaper/SteamBot,zigagrcar/SteamTradeOffersBot,Wendt9222/SteamBot-1,darren1998s/SteambotTest,stigping/SteamBot,icodingforfood/SteamBot,wqbill/SteamBot,BuzzyOG/CSGOWinBig-SteamBot,StormReaper/SteamBot,GAMELASTER/SteamBot,ChalkyBrush/SteamBots,Bottswana/SteamBot,ztizzlegaming/CSGOWinBig-SteamBot,BuzzyOG/CSGOWinBig-SteamBot,avoak/SteamBot,Bottswana/SteamBot,BlueRaja/SteamBot,Banana23/Tryout,niachris/SteamBotNew,xversial/SteamBot,Wendt9222/SteamBot-1,Schwehn42/SteamBot,GoeGaming/SteamBot,martingabriel/SteamBot,Moondarker/CSGOWinBig-SteamBot,23RDGit/CSGOWinBig-SteamBot,wowzone/gamerpro,Moondarker/CSGOWinBig-SteamBot,ztizzlegaming/CSGOWinBig-SteamBot,fjch1997/SteamBot,xversial/SteamBot,trervorx/SteamBot,martingabriel/SteamBot,Jessecar96/SteamBot,GoeGaming/SteamBot,Banana23/Tryout,MadBender/SteamBot,waylaidwanderer/SteamTradeOffersBot,novasdream/SteamBot,MattrAus/SteamBot,avoak/SteamBot,nuller1joe/SteamBot,icodingforfood/SteamBot,tarun200897/SteamBot,JackHarknes/Bot1,terryhau/SteamBot,TheRod1990/SteamBot,23RDGit/CSGOWinBig-SteamBot,JackHarknes/Bot1,Murzyneczka/CSGOWinBig-SteamBot,stackia/SteamBot
SteamBot/AssemblyInfo.cs
SteamBot/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("SteamBot")] [assembly: AssemblyDescription("SteamBot is a bot for the purpose of interacting with Steam Chat and Steam Trade.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("SteamBot")] [assembly: AssemblyCopyright("(C) 2012 SteamBot Contributors")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // "{Major}.{Minor}.{Build}.*" will automatically update the revision. // SteamBot uses Semantic Versioning (http://semver.org/) [assembly: AssemblyVersion("0.0.1.*")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("SteamBot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("jesse")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
f078ea07a934c4ac03b0d3783ee23f64ab4580fb
Make it easy to switch config file and log file location like const.h #define LIVE
AAccount/dt_call_server-windows-
DTOperator/Const.cs
DTOperator/Const.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DTOperator { class Const { public static readonly String VERSION = "4.1:{git revision}_win"; private static readonly bool LIVE = false; private static readonly String PREFIX_LIVE = @"C:\Program Files\dtoperator\"; private static readonly String PREFIX_KVM = @"C:\Users\A\dtoperator\"; private static readonly String PREFIX = LIVE ? PREFIX_LIVE : PREFIX_KVM; public static readonly String USERSFILE = PREFIX + @"users.conf"; public static readonly String CONFFILE = PREFIX + @"dtoperator.conf"; public static readonly String LOGFOLDER = PREFIX + @"log\"; public static readonly int COMMANDSIZE = 2048; public static readonly int MEDIASIZE = 1200; public static readonly int MAXLISTENWAIT = 5; public static readonly int MARGIN_OF_ERROR = 5; public static readonly int CHALLENGE_LENGTH = 200; public static readonly int SESSIONKEY_LENGTH = 59; public static readonly String ENCAES_PLACEHOLDER = "ENCRYPTED_AES_HERE"; public static readonly String SESSIONKEY_PLACEHOLDER = "SESSION_KEY_HERE"; public static readonly String JBYTE = "D"; public static readonly int UNAUTHTIMEOUT = 500; public static readonly int AUTHTIMEOUT = 3000; public static readonly int DEFAULTCMD = 1991; public static readonly int DEFAULTMEDIA = 1961; public static readonly int IPTOS_DSCP_EF = 0xB8; public enum ustate { NONE, INIT, INCALL, INVALID }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DTOperator { class Const { public static readonly String VERSION = "4.1:{git revision}_win"; public static readonly String USERSFILE = "C:\\Users\\A\\dtoperator\\users.conf"; public static readonly String CONFFILE = "C:\\Users\\A\\dtoperator\\dtoperator.conf"; public static readonly int COMMANDSIZE = 2048; public static readonly int MEDIASIZE = 1200; public static readonly int MAXLISTENWAIT = 5; public static readonly int MARGIN_OF_ERROR = 5; public static readonly int CHALLENGE_LENGTH = 200; public static readonly int SESSIONKEY_LENGTH = 59; public static readonly String ENCAES_PLACEHOLDER = "ENCRYPTED_AES_HERE"; public static readonly String SESSIONKEY_PLACEHOLDER = "SESSION_KEY_HERE"; public static readonly String JBYTE = "D"; public static readonly int UNAUTHTIMEOUT = 500; public static readonly int AUTHTIMEOUT = 3000; public static readonly String LOGFOLDER = "C:\\Users\\A\\dtoperator\\log\\"; public static readonly int DEFAULTCMD = 1991; public static readonly int DEFAULTMEDIA = 1961; public static readonly int IPTOS_DSCP_EF = 0xB8; public enum ustate { NONE, INIT, INCALL, INVALID }; } }
agpl-3.0
C#
11c0a7e1f04d06d53bbbc66e1f6d56a28e4a3b30
test commit
ncguy2/MOD003263
Mod003263/Mod003263/db/DatabaseAccessor.cs
Mod003263/Mod003263/db/DatabaseAccessor.cs
using Mod003263.interview; /** * Author: Callum Highley * Date: 14/11/2016 * Contains: DatabaseAccessor */ namespace Mod003263.DBstuff { class DatabaseAccessor { // TODO fix connection insert calls /// <summary> /// Insert statement /// </summary> /// <param name="applicant"></param> public void Insert(Applicant applicant) { string q = "INSERT INTO Current_JA (First_Name, Last_Name, Dob, EmailAddress, Applying_Position, Picture, Phone_Number) " + $"VALUES('{applicant.First_Name}','{applicant.Last_Name}','{applicant.Dob}','{applicant.Email}'," + $"'{applicant.Applying_Position}','{applicant.Picture}','{applicant.Phone_Number}')"; //DatabaseConnection.Insert(q); } public void Insert(Question question) { string q = $"INSERT INTO Questions (Question, Category) VALUES('{question.Text()}', '{question.Cat()}')"; //DatabaseConnection.Insert(q); } public void Insert(int questionId, Answer answer) { string q = $"INSERT INTO Question_Answers (Question_ID, Value, Weight) " + $"VALUES( '{questionId}','{answer.Text}', '{answer.Weight}')"; //DatabaseConnection.Insert(q); } public void PullAllData(string table) { int i; } } }
using Mod003263.interview; /** * Author: Callum Highley * Date: 14/11/2016 * Contains: DatabaseAccessor */ namespace Mod003263.DBstuff { class DatabaseAccessor { // TODO fix connection insert calls /// <summary> /// Insert statement /// </summary> /// <param name="applicant"></param> public void Insert(Applicant applicant) { string q = "INSERT INTO Current_JA (First_Name, Last_Name, Dob, EmailAddress, Applying_Position, Picture, Phone_Number) " + $"VALUES('{applicant.First_Name}','{applicant.Last_Name}','{applicant.Dob}','{applicant.Email}'," + $"'{applicant.Applying_Position}','{applicant.Picture}','{applicant.Phone_Number}')"; //DatabaseConnection.Insert(q); } public void Insert(Question question) { string q = $"INSERT INTO Questions (Question, Category) VALUES('{question.Text()}', '{question.Cat()}')"; //DatabaseConnection.Insert(q); } public void Insert(int questionId, Answer answer) { string q = $"INSERT INTO Question_Answers (Question_ID, Value, Weight) " + $"VALUES( '{questionId}','{answer.Text}', '{answer.Weight}')"; //DatabaseConnection.Insert(q); } public void PullAllData(string table) { } } }
unlicense
C#
253d113106b4d8e48ce2dd4c377c264c9fe04fa7
Update version
Yonom/MuffinFramework
MuffinFramework/Properties/AssemblyInfo.cs
MuffinFramework/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; // 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("MuffinFramework")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MuffinFramework")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System.Reflection; using System.Resources; // 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("MuffinFramework")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MuffinFramework")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
eac14ae72eeda1fb12c4c2198484e96cf87b767d
Fix whitespaces
rlugojr/octokit.net,octokit-net-test/octokit.net,brramos/octokit.net,hitesh97/octokit.net,Sarmad93/octokit.net,nsrnnnnn/octokit.net,mminns/octokit.net,michaKFromParis/octokit.net,M-Zuber/octokit.net,shiftkey/octokit.net,shiftkey-tester/octokit.net,shiftkey-tester/octokit.net,chunkychode/octokit.net,geek0r/octokit.net,SamTheDev/octokit.net,editor-tools/octokit.net,eriawan/octokit.net,thedillonb/octokit.net,cH40z-Lord/octokit.net,SLdragon1989/octokit.net,ivandrofly/octokit.net,ChrisMissal/octokit.net,devkhan/octokit.net,dampir/octokit.net,TattsGroup/octokit.net,bslliw/octokit.net,devkhan/octokit.net,khellang/octokit.net,takumikub/octokit.net,SmithAndr/octokit.net,forki/octokit.net,eriawan/octokit.net,yonglehou/octokit.net,yonglehou/octokit.net,hahmed/octokit.net,alfhenrik/octokit.net,thedillonb/octokit.net,shana/octokit.net,octokit/octokit.net,gabrielweyer/octokit.net,chunkychode/octokit.net,SamTheDev/octokit.net,ivandrofly/octokit.net,shana/octokit.net,kolbasov/octokit.net,kdolan/octokit.net,dlsteuer/octokit.net,gabrielweyer/octokit.net,magoswiat/octokit.net,Sarmad93/octokit.net,daukantas/octokit.net,octokit/octokit.net,octokit-net-test-org/octokit.net,fake-organization/octokit.net,dampir/octokit.net,M-Zuber/octokit.net,editor-tools/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,alfhenrik/octokit.net,Red-Folder/octokit.net,adamralph/octokit.net,darrelmiller/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,rlugojr/octokit.net,SmithAndr/octokit.net,shiftkey/octokit.net,nsnnnnrn/octokit.net,gdziadkiewicz/octokit.net,khellang/octokit.net,gdziadkiewicz/octokit.net,fffej/octokit.net,octokit-net-test-org/octokit.net,naveensrinivasan/octokit.net,hahmed/octokit.net,mminns/octokit.net,TattsGroup/octokit.net
Octokit.Reactive/ObservableGitHubClient.cs
Octokit.Reactive/ObservableGitHubClient.cs
using System; using System.Net.Http.Headers; using Octokit.Reactive.Clients; namespace Octokit.Reactive { public class ObservableGitHubClient : IObservableGitHubClient { readonly IGitHubClient _gitHubClient; public ObservableGitHubClient(ProductHeaderValue productInformation) : this(new GitHubClient(productInformation)) { } public ObservableGitHubClient(ProductHeaderValue productInformation, ICredentialStore credentialStore) :this(new GitHubClient(productInformation, credentialStore)) { } public ObservableGitHubClient(ProductHeaderValue productInformation, Uri baseAddress) :this(new GitHubClient(productInformation, baseAddress)) { } public ObservableGitHubClient(ProductHeaderValue productInformation, ICredentialStore credentialStore, Uri baseAddress) :this(new GitHubClient(productInformation, credentialStore, baseAddress)) { } public ObservableGitHubClient(IGitHubClient gitHubClient) { Ensure.ArgumentNotNull(gitHubClient, "githubClient"); _gitHubClient = gitHubClient; Authorization = new ObservableAuthorizationsClient(gitHubClient); Miscellaneous = new ObservableMiscellaneousClient(gitHubClient.Miscellaneous); Notification = new ObservableNotificationsClient(gitHubClient); Organization = new ObservableOrganizationsClient(gitHubClient); Repository = new ObservableRepositoriesClient(gitHubClient); SshKey = new ObservableSshKeysClient(gitHubClient); User = new ObservableUsersClient(gitHubClient); Release = new ObservableReleasesClient(gitHubClient); } public IConnection Connection { get { return _gitHubClient.Connection; } } public IObservableAuthorizationsClient Authorization { get; private set; } public IObservableMiscellaneousClient Miscellaneous { get; private set; } public IObservableNotificationsClient Notification { get; private set; } public IObservableOrganizationsClient Organization { get; private set; } public IObservableRepositoriesClient Repository { get; private set; } public IObservableReleasesClient Release { get; private set; } public IObservableSshKeysClient SshKey { get; private set; } public IObservableUsersClient User { get; private set; } } }
using System; using System.Net.Http.Headers; using Octokit.Reactive.Clients; namespace Octokit.Reactive { public class ObservableGitHubClient : IObservableGitHubClient { readonly IGitHubClient _gitHubClient; public ObservableGitHubClient(ProductHeaderValue productInformation) : this(new GitHubClient(productInformation)) { } public ObservableGitHubClient(ProductHeaderValue productInformation, ICredentialStore credentialStore) :this (new GitHubClient(productInformation, credentialStore)) { } public ObservableGitHubClient(ProductHeaderValue productInformation, Uri baseAddress) :this(new GitHubClient(productInformation, baseAddress)) { } public ObservableGitHubClient(ProductHeaderValue productInformation, ICredentialStore credentialStore, Uri baseAddress) :this(new GitHubClient(productInformation, credentialStore, baseAddress)) { } public ObservableGitHubClient(IGitHubClient gitHubClient) { Ensure.ArgumentNotNull(gitHubClient, "githubClient"); _gitHubClient = gitHubClient; Authorization = new ObservableAuthorizationsClient(gitHubClient); Miscellaneous = new ObservableMiscellaneousClient(gitHubClient.Miscellaneous); Notification = new ObservableNotificationsClient(gitHubClient); Organization = new ObservableOrganizationsClient(gitHubClient); Repository = new ObservableRepositoriesClient(gitHubClient); SshKey = new ObservableSshKeysClient(gitHubClient); User = new ObservableUsersClient(gitHubClient); Release = new ObservableReleasesClient(gitHubClient); } public IConnection Connection { get { return _gitHubClient.Connection; } } public IObservableAuthorizationsClient Authorization { get; private set; } public IObservableMiscellaneousClient Miscellaneous { get; private set; } public IObservableNotificationsClient Notification { get; private set; } public IObservableOrganizationsClient Organization { get; private set; } public IObservableRepositoriesClient Repository { get; private set; } public IObservableReleasesClient Release { get; private set; } public IObservableSshKeysClient SshKey { get; private set; } public IObservableUsersClient User { get; private set; } } }
mit
C#
741a29cb9493eca5951f3454bb7d492b41d86b77
Define and use Game#ShownLetterFor
12joan/hangman
game.cs
game.cs
using System; using System.Collections.Generic; using System.Text; namespace Hangman { public class Game { public string Word; private List<char> GuessedLetters; public Game(string word) { Word = word; GuessedLetters = new List<char>(); } public string ShownWord() { StringBuilder obscuredWord = new StringBuilder(); foreach (char letter in Word) { obscuredWord.Append(ShownLetterFor(letter)); } return obscuredWord.ToString(); } private char ShownLetterFor(char originalLetter) { return '_'; } private bool LetterWasGuessed(char letter) { return GuessedLetters.Contains(letter); } private bool LetterIsCorrect(char letter) { return Word.Contains(letter.ToString()); } } }
using System; using System.Collections.Generic; namespace Hangman { public class Game { public string Word; private List<char> GuessedLetters; public Game(string word) { Word = word; GuessedLetters = new List<char>(); } public string ShownWord() { return Word; } private bool LetterWasGuessed(char letter) { return GuessedLetters.Contains(letter); } private bool LetterIsCorrect(char letter) { return Word.Contains(letter); } } }
unlicense
C#
01e92b1e7a274a0559c9d977cf0c7d0a4e550456
修改了PathException异常类的实现。
huoxudong125/Zongsoft.CoreLibrary,Zongsoft/Zongsoft.CoreLibrary,MetSystem/Zongsoft.CoreLibrary
IO/PathException.cs
IO/PathException.cs
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2010-2014 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.CoreLibrary. * * Zongsoft.CoreLibrary is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Zongsoft.CoreLibrary 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. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.CoreLibrary; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Runtime.Serialization; namespace Zongsoft.IO { [Serializable] public class PathException : ApplicationException { #region 成员字段 private string _path; #endregion #region 构造函数 public PathException(string message) : base(message) { } public PathException(string message, Exception innerException) : base(message, innerException) { } protected PathException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion } }
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2010-2014 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.CoreLibrary. * * Zongsoft.CoreLibrary is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Zongsoft.CoreLibrary 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. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.CoreLibrary; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; namespace Zongsoft.IO { [Serializable] public class PathException : ApplicationException { #region 成员字段 private string _path; #endregion #region 构造函数 public PathException(string path) { _path = path; } #endregion #region 公共属性 public string Path { get { return _path; } } #endregion #region 重写方法 public override string ToString() { return _path ?? string.Empty; } #endregion } }
lgpl-2.1
C#
bf5637700d1822a92698653d9ce70e043356020a
Update Manufacturer name
bozaro/octobuild,bozaro/octobuild,bozaro/octobuild,bozaro/octobuild,bozaro/octobuild
wixcs/setup.cs
wixcs/setup.cs
using System; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; using WixSharp; class Script { enum Target { i686, x86_64, } static public string ReadVersion(string path) { System.IO.StreamReader file = new System.IO.StreamReader(path); Regex regex = new Regex("^\\s*version\\s*=\\s*\"(\\S+)\""); string line; while ((line = file.ReadLine()) != null) { Match match = regex.Match(line); if (match.Success) { return match.Groups[1].Value; } } return null; } static Target ReadTarget(string path) { String target = System.IO.File.ReadAllText(path); switch (target) { case "x86_64-pc-windows-gnu": return Target.x86_64; case "i686-pc-windows-gnu": return Target.i686; default: throw new Exception("Unknown target: " + target); } } static public void Main(string[] args) { Target target = ReadTarget(@"target\release\target.txt"); String version = ReadVersion(@"Cargo.toml"); Feature featureBuilder = new Feature("Octobuild Builder", true, false); String programFile = (target == Target.x86_64) ? "%ProgramFiles64Folder%" : "%ProgramFilesFolder%"; Project project = new Project("Octobuild", new Dir(programFile + @"\Octobuild", new File(featureBuilder, @"target\release\xgconsole.exe"), new File(featureBuilder, @"LICENSE") ), new EnvironmentVariable(featureBuilder, "PATH", "[INSTALLDIR]") { Permanent = false, Part = EnvVarPart.last, Action = EnvVarAction.set, System = true, } ); project.LicenceFile = @"LICENSE.rtf"; project.LicenceFile = @"LICENSE.rtf"; project.GUID = new Guid("b4505233-6377-406b-955b-2547d86a99a7"); project.UI = WUI.WixUI_InstallDir; project.Version = new Version(version); project.Manufacturer = "Artem V. Navrotskiy"; project.OutFileName = @"target\octobuild-" + version + "-" + target; if (target == Target.x86_64) { project.Package.AttributesDefinition = @"Platform=x64;InstallScope=perMachine"; Compiler.WixSourceGenerated += new XDocumentGeneratedDlgt(Compiler_WixSourceGenerated); } Compiler.BuildMsi(project); Compiler.BuildWxs(project); } static void Compiler_WixSourceGenerated(XDocument document) { foreach (XElement comp in document.Root.AllElements("Component")) { comp.Add(new XAttribute("Win64", "yes")); } } }
using System; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; using WixSharp; class Script { enum Target { i686, x86_64, } static public string ReadVersion(string path) { System.IO.StreamReader file = new System.IO.StreamReader(path); Regex regex = new Regex("^\\s*version\\s*=\\s*\"(\\S+)\""); string line; while ((line = file.ReadLine()) != null) { Match match = regex.Match(line); if (match.Success) { return match.Groups[1].Value; } } return null; } static Target ReadTarget(string path) { String target = System.IO.File.ReadAllText(path); switch (target) { case "x86_64-pc-windows-gnu": return Target.x86_64; case "i686-pc-windows-gnu": return Target.i686; default: throw new Exception("Unknown target: " + target); } } static public void Main(string[] args) { Target target = ReadTarget(@"target\release\target.txt"); String version = ReadVersion(@"Cargo.toml"); Feature featureBuilder = new Feature("Octobuild Builder", true, false); String programFile = (target == Target.x86_64) ? "%ProgramFiles64Folder%" : "%ProgramFilesFolder%"; Project project = new Project("Octobuild", new Dir(programFile + @"\Octobuild", new File(featureBuilder, @"target\release\xgconsole.exe"), new File(featureBuilder, @"LICENSE") ), new EnvironmentVariable(featureBuilder, "PATH", "[INSTALLDIR]") { Permanent = false, Part = EnvVarPart.last, Action = EnvVarAction.set, System = true, } ); project.LicenceFile = @"LICENSE.rtf"; project.GUID = new Guid("b4505233-6377-406b-955b-2547d86a99a7"); project.UI = WUI.WixUI_InstallDir; project.Version = new Version(version); project.OutFileName = @"target\octobuild-" + version + "-" + target; if (target == Target.x86_64) { project.Package.AttributesDefinition = @"Platform=x64;InstallScope=perMachine"; Compiler.WixSourceGenerated += new XDocumentGeneratedDlgt(Compiler_WixSourceGenerated); } Compiler.BuildMsi(project); Compiler.BuildWxs(project); } static void Compiler_WixSourceGenerated(XDocument document) { foreach (XElement comp in document.Root.AllElements("Component")) { comp.Add(new XAttribute("Win64", "yes")); } } }
mit
C#
5f895f120c884f6ad982176cf01d00a91560764c
Remove useless using references
Elgolfin/PokerBot
PokerGame/Dealer.cs
PokerGame/Dealer.cs
using Nicomputer.PokerBot.Cards; namespace Nicomputer.PokerBot.PokerGame { public class Dealer { public Deck52Cards Deck; public Table Table; public Dealer(Table t, Deck52Cards deck) { Deck = deck; Table = t; } public void ShuffleDeck() { Deck.Shuffle(); } /// <summary> /// /// </summary> public void DealHands() { // Dealer... deals // ... First Card DealHandCard(true); // ... Second Card DealHandCard(false); } private void DealHandCard(bool isFirstCard) { var occupiedSeats = Table.GetOccupiedSeats(); foreach (var seat in occupiedSeats) { if (isFirstCard) { seat.Hand = new Hand(); seat.Hand.FirstCard = Deck.Deal(); } else { seat.Hand.SecondCard = Deck.Deal(); } } } private void DealBoardCards(int numCards) { Deck.Burn(); for (var i = 0; i < numCards; i++) { Table.Board.Add(Deck.Deal()); } } public void DealFlop() { DealBoardCards(3); } public void DealTurn() { DealBoardCards(1); } public void DealRiver() { DealBoardCards(1); } } }
using System.Linq; using System.Runtime.InteropServices; using Nicomputer.PokerBot.Cards; namespace Nicomputer.PokerBot.PokerGame { public class Dealer { public Deck52Cards Deck; public Table Table; public Dealer(Table t, Deck52Cards deck) { Deck = deck; Table = t; } public void ShuffleDeck() { Deck.Shuffle(); } /// <summary> /// /// </summary> public void DealHands() { // Dealer... deals // ... First Card DealHandCard(true); // ... Second Card DealHandCard(false); } private void DealHandCard(bool isFirstCard) { var occupiedSeats = Table.GetOccupiedSeats(); foreach (var seat in occupiedSeats) { if (isFirstCard) { seat.Hand = new Hand {}; seat.Hand.FirstCard = Deck.Deal(); } else { seat.Hand.SecondCard = Deck.Deal(); } } } private void DealBoardCards(int numCards) { Deck.Burn(); for (var i = 0; i < numCards; i++) { Table.Board.Add(Deck.Deal()); } } public void DealFlop() { DealBoardCards(3); } public void DealTurn() { DealBoardCards(1); } public void DealRiver() { DealBoardCards(1); } } }
mit
C#
e8de63a38b6b0a23a344474299e34a2124701169
Update UserType.cs
RokuHodo/Twitch-Bot
Enums/UserType.cs
Enums/UserType.cs
namespace TwitchChatBot.Enums { enum UserType { viewer, mod, global_mod, admin, staff } }
namespace TwitchChatBot.Enums { enum UserType { viewer, mod, admin, global_mod, staff } }
apache-2.0
C#
dacf8eec9ccaf524473d71a8ad0853f510395219
remove unecessary fields n comments from testmesh script
tkaretsos/ProceduralBuildings,AlexanderMazaletskiy/ProceduralBuildings
Scripts/TestMesh.cs
Scripts/TestMesh.cs
using UnityEngine; public class TestMesh : MonoBehaviour { [SerializeField] private Material material; private Mesh mesh; private GameObject meshobj; private MeshFilter mf; private MeshRenderer mr; // void Awake () // { // // } // Use this for initialization void Start () { CreateNeoclassical(); } // Update is called once per frame void Update () { } void CreateNeoclassical() { mesh = new Mesh(); meshobj = new GameObject(); mf = meshobj.AddComponent<MeshFilter>(); mr = meshobj.AddComponent<MeshRenderer>(); mr.sharedMaterial = material; Neoclassical neo = new Neoclassical(new Vector3( 4f + Random.Range(0.5f, 1.5f), 0, 1.5f + Random.Range(0.5f, 1.5f)), new Vector3( 4f + Random.Range(0.5f, 1.5f), 0, -1.5f - Random.Range(0.5f, 1.5f)), new Vector3(-4f - Random.Range(0.5f, 1.5f), 0, -1.5f - Random.Range(0.5f, 1.5f)), new Vector3(-4f - Random.Range(0.5f, 1.5f), 0, 1.5f + Random.Range(0.5f, 1.5f))); neo.ConstructFaces(); neo.ConstructFaceComponents(); mesh.Clear(); mesh.vertices = neo.BoundariesArray; mesh.triangles = new int[] { 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7, 4, 5, 6, 4, 6, 7 }; // Assign UVs to shut the editor up -_-' mesh.uv = new Vector2[mesh.vertices.Length]; for (int i = 0; i < mesh.vertices.Length; ++i) mesh.uv[i] = new Vector2(mesh.vertices[i].x, mesh.vertices[i].y); mesh.RecalculateNormals(); mesh.Optimize(); mf.sharedMesh = mesh; } }
using UnityEngine; public class TestMesh : MonoBehaviour { public GameObject empty; public Material material; private Mesh mesh; private GameObject meshobj; private MeshFilter mf; private MeshRenderer mr; // void Awake () // { // // } // Use this for initialization void Start () { CreateNeoclassical(); } // Update is called once per frame void Update () { } void CreateNeoclassical() { mesh = new Mesh(); // meshobj = (GameObject) GameObject.Instantiate(empty, new Vector3(0f, 0f, 0f), Quaternion.identity); meshobj = new GameObject(); mf = meshobj.AddComponent<MeshFilter>(); mr = meshobj.AddComponent<MeshRenderer>(); mr.sharedMaterial = material; Neoclassical neo = new Neoclassical(new Vector3( 4f + Random.Range(0.5f, 1.5f), 0, 1.5f + Random.Range(0.5f, 1.5f)), new Vector3( 4f + Random.Range(0.5f, 1.5f), 0, -1.5f - Random.Range(0.5f, 1.5f)), new Vector3(-4f - Random.Range(0.5f, 1.5f), 0, -1.5f - Random.Range(0.5f, 1.5f)), new Vector3(-4f - Random.Range(0.5f, 1.5f), 0, 1.5f + Random.Range(0.5f, 1.5f))); neo.ConstructFaces(); mesh.Clear(); mesh.vertices = neo.BoundariesArray; mesh.triangles = new int[] { 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7, 4, 5, 6, 4, 6, 7 }; // Assign UVs to shut the editor up -_-' mesh.uv = new Vector2[mesh.vertices.Length]; for (int i = 0; i < mesh.vertices.Length; ++i) mesh.uv[i] = new Vector2(mesh.vertices[i].x, mesh.vertices[i].y); mesh.RecalculateNormals(); mesh.Optimize(); mf.sharedMesh = mesh; } }
mit
C#
eb2f07994fd1f0feb8d98684f255bae58cc4e62d
Fix the assembly version.
izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp
AssemblyInfo.cs
AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("FbxSharp")] [assembly: AssemblyDescription("A pure C# library for loading FBX files")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FbxSharp")] [assembly: AssemblyCopyright("Copyright © izrik 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.4.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("FbxSharp")] [assembly: AssemblyDescription("A pure C# library for loading FBX files")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FbxSharp")] [assembly: AssemblyCopyright("Copyright © izrik 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.3")]
lgpl-2.1
C#
c0ae7cc7582a441dbdf2e89680e561daa44f1886
Fix doc of #82
rsdn/CodeJam
CodeJam.Main/Threading/AwaitableNonDisposable.cs
CodeJam.Main/Threading/AwaitableNonDisposable.cs
// BASEDON: https://github.com/StephenCleary/AsyncEx AwaitableDisposable class. using System; using System.Threading.Tasks; using System.Runtime.CompilerServices; using JetBrains.Annotations; namespace CodeJam.Threading { /// <summary> /// An awaitable wrapper around a task whose result is <see cref="IDisposable"/>. /// The wrapper itself is not <see cref="IDisposable"/>.!-- /// This prevents usage errors like <code>using (lock.AcquireAsync())</code> when the appropriate usage should be <code>using (await lock.AcquireAsync())</code>. /// </summary> /// <typeparam name="T">The type of the result of the underlying task.</typeparam> public struct AwaitableNonDisposable<T> where T : IDisposable { /// <summary> /// The underlying task. /// </summary> [NotNull] private readonly Task<T> _task; /// <summary> /// Initializes a new awaitable wrapper around the specified task. /// </summary> /// <param name="task">The underlying task to wrap. This may not be <c>null</c>.</param> public AwaitableNonDisposable([NotNull] Task<T> task) { Code.NotNull(task, nameof(task)); _task = task; } /// <summary> /// Returns the underlying task. /// </summary> /// <returns>Underlying task.</returns> [NotNull] public Task<T> AsTask() { return _task; } /// <summary> /// Implicit conversion to the underlying task. /// </summary> /// <param name="source">The awaitable wrapper.</param> /// <returns>Underlying task</returns> [NotNull] public static implicit operator Task<T>([NotNull] AwaitableNonDisposable<T> source) { return source.AsTask(); } /// <summary> /// Infrastructure. Returns the task awaiter for the underlying task. /// </summary> /// <returns>Task awaiter for the underlying task.</returns> public TaskAwaiter<T> GetAwaiter() { return _task.GetAwaiter(); } /// <summary> /// Infrastructure. Returns a configured task awaiter for the underlying task. /// </summary> /// <param name="continueOnCapturedContext">Whether to attempt to marshal the continuation back to the captured context.</param> /// <returns>A configured task awaiter for the underlying task.</returns> public ConfiguredTaskAwaitable<T> ConfigureAwait(bool continueOnCapturedContext) { return _task.ConfigureAwait(continueOnCapturedContext); } } }
// BASEDON: https://github.com/StephenCleary/AsyncEx AwaitableDisposable class. using System; using System.Threading.Tasks; using System.Runtime.CompilerServices; using JetBrains.Annotations; namespace CodeJam.Threading { /// <summary> /// An awaitable wrapper around a task whose result is <see cref="IDisposable"/>. /// The wrapper itself is not <see cref="IDisposable"/>.!-- /// This prevents usage errors like <code>using (lock.AcquireAsync())</code> when the appropriate usage should be <code>using (await lock.AcquireAsync())</code>. /// </summary> /// <typeparam name="T">The type of the result of the underlying task.</typeparam> public struct AwaitableNonDisposable<T> where T : IDisposable { /// <summary> /// The underlying task. /// </summary> [NotNull] private readonly Task<T> _task; /// <summary> /// Initializes a new awaitable wrapper around the specified task. /// </summary> /// <param name="task">The underlying task to wrap. This may not be <c>null</c>.</param> public AwaitableNonDisposable([NotNull] Task<T> task) { Code.NotNull(task, nameof(task)); _task = task; } /// <summary> /// Returns the underlying task. /// </summary> public Task<T> AsTask() { return _task; } /// <summary> /// Implicit conversion to the underlying task. /// </summary> /// <param name="source">The awaitable wrapper.</param> public static implicit operator Task<T>([NotNull] AwaitableNonDisposable<T> source) { return source.AsTask(); } /// <summary> /// Infrastructure. Returns the task awaiter for the underlying task. /// </summary> public TaskAwaiter<T> GetAwaiter() { return _task.GetAwaiter(); } /// <summary> /// Infrastructure. Returns a configured task awaiter for the underlying task. /// </summary> /// <param name="continueOnCapturedContext">Whether to attempt to marshal the continuation back to the captured context.</param> public ConfiguredTaskAwaitable<T> ConfigureAwait(bool continueOnCapturedContext) { return _task.ConfigureAwait(continueOnCapturedContext); } } }
mit
C#
f8b085b76964d211c6b2728ef52d868ae88db78e
Add the Geometry property to Responses Result
mklimmasch/google-maps,mklimmasch/google-maps,maximn/google-maps,yonglehou/google-maps,yonglehou/google-maps,maximn/google-maps
GoogleMapsApi/Entities/Places/Response/Result.cs
GoogleMapsApi/Entities/Places/Response/Result.cs
using System.Runtime.Serialization; using GoogleMapsApi.Entities.Common; namespace GoogleMapsApi.Entities.Places.Response { [DataContract] public class Result { /// <summary> /// name contains the human-readable name for the returned result. For establishment results, this is usually the canonicalized business name. /// </summary> [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "rating")] public double Rating { get; set; } [DataMember(Name = "icon")] public string Icon { get; set; } [DataMember(Name = "id")] public string ID { get; set; } [DataMember(Name = "reference")] public string Reference { get; set; } [DataMember(Name = "vicinity")] public string Vicinity { get; set; } [DataMember(Name = "types")] public string[] Types { get; set; } [DataMember( Name = "geometry" )] public Geometry Geometry { get; set; } } }
using System.Runtime.Serialization; using GoogleMapsApi.Entities.Common; namespace GoogleMapsApi.Entities.Places.Response { [DataContract] public class Result { /// <summary> /// name contains the human-readable name for the returned result. For establishment results, this is usually the canonicalized business name. /// </summary> [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "rating")] public double Rating { get; set; } [DataMember(Name = "icon")] public string Icon { get; set; } [DataMember(Name = "id")] public string ID { get; set; } [DataMember(Name = "reference")] public string Reference { get; set; } [DataMember(Name = "vicinity")] public string Vicinity { get; set; } [DataMember(Name = "types")] public string[] Types { get; set; } } }
bsd-2-clause
C#
9621a711aee62b881f2d4b81a8fcc5e81ccba081
Replace copy-paste code with Repeat attribute usage
EVAST9919/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework
osu.Framework.Tests/Visual/Testing/TestSceneTest.cs
osu.Framework.Tests/Visual/Testing/TestSceneTest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Development; using osu.Framework.Testing; namespace osu.Framework.Tests.Visual.Testing { public class TestSceneTest : FrameworkTestScene { private int setupRun; private int setupStepsRun; private int testRunCount; [SetUp] public void SetUp() { setupRun++; } [SetUpSteps] public void SetUpSteps() { setupStepsRun++; } public TestSceneTest() { Schedule(() => { // [SetUp] gets run via TestConstructor() when we are running under nUnit. // note that in TestBrowser's case, this does not invoke SetUp methods, so we skip this increment. // schedule is required to ensure that IsNUnitRunning is initialised. if (DebugUtils.IsNUnitRunning) testRunCount++; }); AddStep("dummy step", () => { }); } [Test, Repeat(2)] public void Test() { AddStep("increment run count", () => testRunCount++); AddAssert("correct setup run count", () => testRunCount == setupRun); AddAssert("correct setup steps run count", () => (DebugUtils.IsNUnitRunning ? testRunCount : 2) == setupStepsRun); } protected override ITestSceneTestRunner CreateRunner() => new TestRunner(); private class TestRunner : TestSceneTestRunner { public override void RunTestBlocking(TestScene test) { base.RunTestBlocking(test); // This will only ever trigger via NUnit Assert.That(test.StepsContainer, Has.Count.GreaterThan(0)); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Development; using osu.Framework.Testing; namespace osu.Framework.Tests.Visual.Testing { public class TestSceneTest : FrameworkTestScene { private int setupRun; private int setupStepsRun; private int testRunCount; [SetUp] public void SetUp() { setupRun++; } [SetUpSteps] public void SetUpSteps() { setupStepsRun++; } public TestSceneTest() { Schedule(() => { // [SetUp] gets run via TestConstructor() when we are running under nUnit. // note that in TestBrowser's case, this does not invoke SetUp methods, so we skip this increment. // schedule is required to ensure that IsNUnitRunning is initialised. if (DebugUtils.IsNUnitRunning) testRunCount++; }); AddStep("dummy step", () => { }); } [Test] public void Test1() { AddStep("increment run count", () => testRunCount++); AddAssert("correct setup run count", () => testRunCount == setupRun); AddAssert("correct setup steps run count", () => (DebugUtils.IsNUnitRunning ? testRunCount : 2) == setupStepsRun); } [Test] public void Test2() { AddStep("increment run count", () => testRunCount++); AddAssert("correct setup run count", () => testRunCount == setupRun); AddAssert("correct setup steps run count", () => (DebugUtils.IsNUnitRunning ? testRunCount : 2) == setupStepsRun); } protected override ITestSceneTestRunner CreateRunner() => new TestRunner(); private class TestRunner : TestSceneTestRunner { public override void RunTestBlocking(TestScene test) { base.RunTestBlocking(test); // This will only ever trigger via NUnit Assert.That(test.StepsContainer, Has.Count.GreaterThan(0)); } } } }
mit
C#
183b48d9fc2080eaec467d6c65650c508ebaa213
Update AssemblyInfo.cs
tiernano/b2uploader
B2Classes/Properties/AssemblyInfo.cs
B2Classes/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("B2Classes")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("B2Classes")] [assembly: AssemblyCopyright("Copyright Tiernan OToole © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fe353639-3b33-44de-9147-45b63818d8a7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("B2Classes")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("B2Classes")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fe353639-3b33-44de-9147-45b63818d8a7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#