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 |
|---|---|---|---|---|---|---|---|---|
3e164ee40d265bb36379973668c8ccfa622660cc
|
make case insensitive on url comparisons
|
Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache
|
NuCache/UrlRewriteMiddlware.cs
|
NuCache/UrlRewriteMiddlware.cs
|
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Owin;
using Serilog;
namespace NuCache
{
public class UrlRewriteMiddlware : OwinMiddleware
{
private static readonly ILogger Log = Serilog.Log.ForContext<UrlRewriteMiddlware>();
public UrlRewriteMiddlware(OwinMiddleware next) : base(next)
{
}
public override Task Invoke(IOwinContext context)
{
var requestPath = context.Request.Path.ToString();
Log.Debug("{path}", requestPath);
if (requestPath.StartsWith("/v3", StringComparison.OrdinalIgnoreCase) == false)
{
return Next.Invoke(context);
}
var client = new HttpClient()
{
BaseAddress = new Uri("http://api.nuget.org")
};
var response = client.GetAsync(requestPath).Result;
context.Response.ContentType = response.Content.Headers.ContentType.MediaType;
using (var sr = new StreamReader(response.Content.ReadAsStreamAsync().Result))
using (var sw = new StreamWriter(context.Response.Body))
{
string line;
while ((line = sr.ReadLine()) != null)
{
sw.WriteLine(line.Replace("https://api.nuget.org/", "http://localhost:55628/"));
}
}
return Task.Delay(0);
}
}
}
|
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Owin;
using Serilog;
namespace NuCache
{
public class UrlRewriteMiddlware : OwinMiddleware
{
private static readonly ILogger Log = Serilog.Log.ForContext<UrlRewriteMiddlware>();
public UrlRewriteMiddlware(OwinMiddleware next) : base(next)
{
}
public override Task Invoke(IOwinContext context)
{
var requestPath = context.Request.Path.ToString();
Log.Debug("{path}", requestPath);
if (requestPath.StartsWith("/v3") == false)
{
return Next.Invoke(context);
}
var client = new HttpClient()
{
BaseAddress = new Uri("http://api.nuget.org")
};
var response = client.GetAsync(requestPath).Result;
context.Response.ContentType = response.Content.Headers.ContentType.MediaType;
using (var sr = new StreamReader(response.Content.ReadAsStreamAsync().Result))
using (var sw = new StreamWriter(context.Response.Body))
{
string line;
while ((line = sr.ReadLine()) != null)
{
sw.WriteLine(line.Replace("https://api.nuget.org/", "http://localhost:55628/"));
}
}
return Task.Delay(0);
}
}
}
|
lgpl-2.1
|
C#
|
faa42e9fc0ef349d6c79c374863f2a73686a8f3c
|
Add DoFeature2
|
seyedk/Staffing
|
Staffing/Staffing/Program.cs
|
Staffing/Staffing/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Staffing
{
class Program
{
static void Main(string[] args)
{
}
static void DoSomthing()
{
Console.WriteLine("I'm doing something now!");
}
static void Feature()
{
Console.WriteLine("Feature 01 has been implemented!");
}
static void ExternalAccess()
{
//added by external user.
Console.Write("Please enter your key:");
var keyedin = Console.ReadLine();
Console.WriteLine("You keyed in: {0}", keyedin);
}
static void DoFeature()
{
Console.WriteLine("Feature is done!");
}
static void DoFeature2()
{
Console.WriteLine("Feature is done!");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Staffing
{
class Program
{
static void Main(string[] args)
{
}
static void DoSomthing()
{
Console.WriteLine("I'm doing something now!");
}
static void Feature()
{
Console.WriteLine("Feature 01 has been implemented!");
}
static void ExternalAccess()
{
//added by external user.
Console.Write("Please enter your key:");
var keyedin = Console.ReadLine();
Console.WriteLine("You keyed in: {0}", keyedin);
}
static void DoFeature()
{
Console.WriteLine("Feature is done!");
}
}
}
|
mit
|
C#
|
6f4ef03682525aa65b7cf8bccdff3c8afddd1486
|
Fix parsing of command line arguments when invoking service from commandline w/o mono-service wrapping us.
|
NoesisLabs/Topshelf.Linux,pruiz/Topshelf.Linux
|
Topshelf.Linux/MonoHelper.cs
|
Topshelf.Linux/MonoHelper.cs
|
#region license
// Copyright 2013 - Pablo Ruiz Garcia <pablo.ruiz at gmail.com>
//
// 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;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Topshelf.Runtime.Linux
{
internal static class MonoHelper
{
[DllImport("libc")]
private static extern uint getuid();
public static bool RunningAsRoot
{
// TODO: Use Mono.Unix instead (it's safer)
get { return getuid() == 0; }
}
public static bool RunningOnMono
{
get
{
Type t = Type.GetType("Mono.Runtime");
if (t != null)
return true;
return false;
}
}
public static bool RunninOnUnix
{
get
{
int p = (int)Environment.OSVersion.Platform;
return ((p == 4) || (p == 6) || (p == 128));
}
}
public static bool RunninOnLinux
{
get
{
int p = (int)Environment.OSVersion.Platform;
return ((p == 4) || (p == 128));
}
}
public static string GetUnparsedCommandLine()
{
var args = new Stack<string>((Environment.GetCommandLineArgs() ?? new string[]{ }).Reverse());
string commandLine = Environment.CommandLine;
string exeName = args.Peek();
if (exeName == null) return commandLine;
// If we are being run under mono-service, strip
// mono-service.exe + arguments from cmdline.
// NOTE: mono-service.exe passes itself as first arg.
if (exeName.EndsWith("mono-service.exe"))
{
commandLine = commandLine.Substring(exeName.Length).TrimStart();
do
{
args.Pop();
} while (args.Count > 0 && args.Peek().StartsWith("-"));
exeName = args.Peek();
}
// Now strip real program's executable name from cmdline.
// Let's try first with a quoted executable..
var qExeName = "\"" + exeName + "\"";
if (commandLine.IndexOf(qExeName) > 0)
{
commandLine = commandLine.Substring(commandLine.IndexOf(qExeName) + qExeName.Length);
}
else
{
commandLine = commandLine.Substring(commandLine.IndexOf(exeName) + exeName.Length);
}
return (commandLine ?? "").Trim();
}
}
}
|
#region license
// Copyright 2013 - Pablo Ruiz Garcia <pablo.ruiz at gmail.com>
//
// 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;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Topshelf.Runtime.Linux
{
internal static class MonoHelper
{
[DllImport("libc")]
private static extern uint getuid();
public static bool RunningAsRoot
{
// TODO: Use Mono.Unix instead (it's safer)
get { return getuid() == 0; }
}
public static bool RunningOnMono
{
get
{
Type t = Type.GetType("Mono.Runtime");
if (t != null)
return true;
return false;
}
}
public static bool RunninOnUnix
{
get
{
int p = (int)Environment.OSVersion.Platform;
return ((p == 4) || (p == 6) || (p == 128));
}
}
public static bool RunninOnLinux
{
get
{
int p = (int)Environment.OSVersion.Platform;
return ((p == 4) || (p == 128));
}
}
public static string GetUnparsedCommandLine()
{
var args = new Stack<string>((Environment.GetCommandLineArgs() ?? new string[]{ }).Reverse());
string commandLine = Environment.CommandLine;
string exeName = args.Peek();
// If we are not being run under mono-service, just return.
// NOTE: mono-service.exe passes itself as first arg.
if (exeName == null || !exeName.EndsWith("mono-service.exe"))
{
return commandLine;
}
// strip mono-service.exe + arguments from cmdline.
commandLine = commandLine.Substring(exeName.Length).TrimStart();
do
{
args.Pop();
} while (args.Count > 0 && args.Peek().StartsWith("-"));
exeName = args.Peek();
// Now strip real program's executable name from cmdline.
// Let's try first with a quoted executable..
var qExeName = "\"" + exeName + "\"";
if (commandLine.IndexOf(qExeName) > 0)
{
commandLine = commandLine.Substring(commandLine.IndexOf(qExeName) + qExeName.Length);
}
else
{
commandLine = commandLine.Substring(commandLine.IndexOf(exeName) + exeName.Length);
}
return (commandLine ?? "").Trim();
}
}
}
|
apache-2.0
|
C#
|
2e329c0eb9a651bbe0523703a128997726d4262f
|
Update LogReplacedAttribute.cs
|
destructurama/attributed
|
src/Destructurama.Attributed/Attributed/LogReplacedAttribute.cs
|
src/Destructurama.Attributed/Attributed/LogReplacedAttribute.cs
|
// Copyright 2015-2020 Destructurama Contributors, Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Text.RegularExpressions;
using Serilog.Core;
using Serilog.Events;
namespace Destructurama.Attributed
{
[AttributeUsage(AttributeTargets.Property)]
public class LogReplacedAttribute : Attribute, IPropertyDestructuringAttribute
{
readonly string _pattern;
readonly string _replacement;
public RegexOptions Options { get; set; }
public LogReplacedAttribute(string pattern, string replacement)
{
_pattern = pattern;
_replacement = replacement;
}
public bool TryCreateLogEventProperty(string name, object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventProperty property)
{
if (value == null)
{
property = new LogEventProperty(name, new ScalarValue(value));
return true;
}
if (value is string s)
{
var replacement = Regex.Replace(s, _pattern, _replacement, Options);
property = new LogEventProperty(name, new ScalarValue(replacement));
return true;
}
property = null;
return false;
}
}
}
|
// Copyright 2015-2020 Destructurama Contributors, Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Text.RegularExpressions;
using Serilog.Core;
using Serilog.Events;
namespace Destructurama.Attributed
{
[AttributeUsage(AttributeTargets.Property)]
public class LogReplacedAttribute : Attribute, IPropertyDestructuringAttribute
{
readonly string _pattern;
readonly string _replacement;
RegexOptions Options { get; set; }
public LogReplacedAttribute(string pattern, string replacement)
{
_pattern = pattern;
_replacement = replacement;
}
public bool TryCreateLogEventProperty(string name, object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventProperty property)
{
if (value == null)
{
property = new LogEventProperty(name, new ScalarValue(value));
return true;
}
if (value is string s)
{
var replacement = Regex.Replace(s, _pattern, _replacement, Options);
property = new LogEventProperty(name, new ScalarValue(replacement));
return true;
}
property = null;
return false;
}
}
}
|
apache-2.0
|
C#
|
9c5d931f25dd81d4d8445f31142506872e5c62d3
|
fix test
|
rflechner/LinqToSalesforce,rflechner/LinqToSalesforce,rflechner/LinqToSalesforce
|
tests/LinqToSalesforce.CsharpTests/TranslationTests.cs
|
tests/LinqToSalesforce.CsharpTests/TranslationTests.cs
|
using System;
using System.Linq;
using Newtonsoft.Json;
using NUnit.Framework;
namespace LinqToSalesforce.CsharpTests
{
[TestFixture]
public class TranslationTests
{
[Test]
public void WhenSelectBirthAsBornDateAndIdCustomerWhereFirstnameIsPopoAndBirthGreatherOrEqualThan02Feb1985OrderByDate_ShouldBe2ComparisonAnd1SelectTokens()
{
var context = new FakeQueryContext();
var customers = context.GetTable<Customer>();
var dateTime = new DateTime(1985, 02, 11);
var query =
from c in customers
where c.Firstname == "popo" && c.Birth >= dateTime
orderby c.Birth descending
select new
{
c.Id,
BornDate = c.Birth
};
var soql = query.ToString();
Assert.AreEqual(@"SELECT Id, BornDate FROM Customer WHERE (Firstname = 'popo') AND (Birth >= 1985-02-11T00:00:00Z) ORDER BY Birth DESC", soql);
}
public class Entity1
{
[EntityField(false)]
public int Id { get; set; }
[EntityField(false)]
public string Name { get; set; }
[EntityField(false)]
[JsonProperty("Cost")]
public string Price { get; set; }
}
[Test]
public void WhenProperyHasJsonPropertyAttributes_PropertyNameShouldBeAttributeValue()
{
var context = new FakeQueryContext();
var entities = context.GetTable<Entity1>();
var query =
from c in entities
where c.Name == "popo"
select c;
var soql = query.ToString();
Assert.AreEqual(@"SELECT Id, Name, Cost FROM Entity1 WHERE Name = 'popo'", soql);
}
}
}
|
using System;
using System.Linq;
using Newtonsoft.Json;
using NUnit.Framework;
namespace LinqToSalesforce.CsharpTests
{
[TestFixture]
public class TranslationTests
{
[Test]
public void WhenSelectBirthAsBornDateAndIdCustomerWhereFirstnameIsPopoAndBirthGreatherOrEqualThan02Feb1985OrderByDate_ShouldBe2ComparisonAnd1SelectTokens()
{
var context = new FakeQueryContext();
var customers = context.GetTable<Customer>();
var dateTime = new DateTime(1985, 02, 11);
var query =
from c in customers
where c.Firstname == "popo" && c.Birth >= dateTime
orderby c.Birth descending
select new
{
c.Id,
BornDate = c.Birth
};
var soql = query.ToString();
Assert.AreEqual(@"SELECT Id, BornDate FROM Customer WHERE (Firstname = 'popo') AND (Birth >= '1985-02-11') ORDER BY Birth DESC", soql);
}
public class Entity1
{
[EntityField(false)]
public int Id { get; set; }
[EntityField(false)]
public string Name { get; set; }
[EntityField(false)]
[JsonProperty("Cost")]
public string Price { get; set; }
}
[Test]
public void WhenProperyHasJsonPropertyAttributes_PropertyNameShouldBeAttributeValue()
{
var context = new FakeQueryContext();
var entities = context.GetTable<Entity1>();
var query =
from c in entities
where c.Name == "popo"
select c;
var soql = query.ToString();
Assert.AreEqual(@"SELECT Id, Name, Cost FROM Entity1 WHERE Name = 'popo'", soql);
}
}
}
|
unlicense
|
C#
|
46daffe36fe4b6f707075c1306d10db202286ef7
|
Update to ConnectedMethod.IsComplete method.
|
jozilla/Uiml.net
|
Uiml/Gummy/Kernel/Services/ApplicationGlue/ConnectedMethod.cs
|
Uiml/Gummy/Kernel/Services/ApplicationGlue/ConnectedMethod.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using Uiml.Gummy.Domain;
namespace Uiml.Gummy.Kernel.Services.ApplicationGlue
{
public class ConnectedMethod
{
private MethodModel m_method;
public MethodModel Method
{
get { return m_method; }
set { m_method = value; }
}
private Dictionary<MethodParameterModel, DomainObject> m_inputs = new Dictionary<MethodParameterModel, DomainObject>();
public Dictionary<MethodParameterModel, DomainObject> Inputs
{
get { return m_inputs; }
}
private DomainObject m_invoke;
public DomainObject Invoke
{
get { return m_invoke; }
set { m_invoke = value; }
}
private DomainObject m_output;
public DomainObject Output
{
get { return m_output; }
set { m_output = value; }
}
public ConnectedMethod(MethodModel method)
{
Method = method;
}
public void AddInput(MethodParameterModel param, DomainObject dom)
{
Inputs.Add(param, dom);
}
public bool IsComplete(out List<MethodParameterModel> missingInputParams, out bool missingOutput, out bool missingInvoke)
{
// initialization
missingInputParams = new List<MethodParameterModel>();
missingOutput = false;
missingInvoke = false;
bool invoke;
bool output;
bool inputs;
invoke = Invoke != null;
if (!invoke)
missingInvoke = true;
inputs = true;
foreach (MethodParameterModel input in Inputs.Keys)
{
if (!Method.Inputs.Contains(input))
{
inputs = false;
missingInputParams.Add(input);
}
}
output = (Method.Outputs.Count > 0) ? Output != null: Output == null;
if (!output)
missingOutput = true;
return output && invoke && inputs;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Uiml.Gummy.Domain;
namespace Uiml.Gummy.Kernel.Services.ApplicationGlue
{
public class ConnectedMethod
{
private MethodModel m_method;
public MethodModel Method
{
get { return m_method; }
set { m_method = value; }
}
private Dictionary<MethodParameterModel, DomainObject> m_inputs = new Dictionary<MethodParameterModel, DomainObject>();
public Dictionary<MethodParameterModel, DomainObject> Inputs
{
get { return m_inputs; }
}
private DomainObject m_invoke;
public DomainObject Invoke
{
get { return m_invoke; }
set { m_invoke = value; }
}
private DomainObject m_output;
public DomainObject Output
{
get { return m_output; }
set { m_output = value; }
}
public ConnectedMethod(MethodModel method)
{
Method = method;
}
public void AddInput(MethodParameterModel param, DomainObject dom)
{
Inputs.Add(param, dom);
}
public bool IsComplete()
{
bool invoke;
bool output;
bool inputs;
invoke = Invoke != null;
inputs = true;
foreach (MethodParameterModel input in Inputs.Keys)
{
if (!Method.Inputs.Contains(input))
inputs = false;
}
output = (Method.Outputs.Count > 0) ? Output != null: Output == null;
return output && invoke && inputs;
}
}
}
|
lgpl-2.1
|
C#
|
fb60fa195281aa4c6d701eb777a4d196e8101c3a
|
Update ModelManager.cs
|
wangyaron/VRProject
|
TestGit/Assets/ModelManager.cs
|
TestGit/Assets/ModelManager.cs
|
using UnityEngine;
using System.Collections;
public class ModelManager : MonoBehaviour
{
private int tag = 3;
private string model_name = "hello";
void Start () {
Debug.Log("git测试");
}
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up, Time.deltaTime * 280);
}
private void PrintMsg()
{
Debug.Log("小郭提交的一个方法");
}
public void SetVisible(bool visible){
gameObject.SetActive(visible);
}
}
|
using UnityEngine;
using System.Collections;
public class ModelManager : MonoBehaviour
{
private int tag = 0;
private string model_name = "hello";
void Start () {
Debug.Log("git测试");
}
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up, Time.deltaTime * 280);
}
private void PrintMsg()
{
Debug.Log("小郭提交的一个方法");
}
public void SetVisible(bool visible){
gameObject.SetActive(visible);
}
}
|
apache-2.0
|
C#
|
c1b92926876ea7454d33fd442fd9dcaf9f556f74
|
Verify model constructors.
|
eatskolnikov/mobile,masterrr/mobile,ZhangLeiCharles/mobile,masterrr/mobile,eatskolnikov/mobile,eatskolnikov/mobile,peeedge/mobile,peeedge/mobile,ZhangLeiCharles/mobile
|
Tests/Data/Models/ModelTest.cs
|
Tests/Data/Models/ModelTest.cs
|
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Toggl.Phoebe.Data.NewModels;
namespace Toggl.Phoebe.Tests.Data.Models
{
public abstract class ModelTest<T> : Test
where T : IModel
{
protected static readonly string[] ExemptProperties = { "Data" };
[Test]
public void VerifyPropertyNames ()
{
const string fieldPrefix = "Property";
var type = typeof(T);
var fields = type.GetFields (BindingFlags.Static | BindingFlags.Public)
.Where (t => t.Name.StartsWith (fieldPrefix, StringComparison.Ordinal))
.ToList ();
Assert.That (fields, Has.Count.AtLeast (1), String.Format ("{0} should define some property names.", type.Name));
// Verify that defined property names have correct value and properties exist
foreach (var field in fields) {
var name = field.Name.Substring (fieldPrefix.Length);
var value = field.GetValue (null);
Assert.AreEqual (name, value, String.Format ("{0}.{1} property value is {2}.", type.Name, field.Name, value));
var prop = type.GetProperty (name, BindingFlags.Public | BindingFlags.Instance);
Assert.NotNull (prop, String.Format ("{0}.{1} property doesn't exist.", type.Name, name));
}
// Verify that all public properties have the property name defined
var fieldNames = fields.Select (f => f.GetValue (null)).ToList ();
var properties = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
foreach (var prop in properties) {
if (!ExemptProperties.Contains (prop.Name)) {
Assert.IsTrue (fieldNames.Contains (prop.Name), String.Format ("{0}.{1}{2} static field is not defined.", type.Name, fieldPrefix, prop.Name));
}
}
}
[Test]
public void VerifyConstructors ()
{
var type = typeof(T);
Assert.IsNotNull (type.GetConstructor (new Type[] { }), "Default constructor not found.");
Assert.IsNotNull (type.GetConstructor (new[] { typeof(Guid) }), "Lazy load constructor not found.");
var dataProp = type.GetProperty ("Data");
Assert.IsNotNull (type.GetConstructor (new[] { dataProp.PropertyType }), "Wrapping constructor not found.");
}
}
}
|
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using Toggl.Phoebe.Data.NewModels;
namespace Toggl.Phoebe.Tests.Data.Models
{
public abstract class ModelTest<T> : Test
where T : IModel
{
protected static readonly string[] ExemptProperties = { "Data" };
[Test]
public void VerifyPropertyNames ()
{
const string fieldPrefix = "Property";
var type = typeof(T);
var fields = type.GetFields (BindingFlags.Static | BindingFlags.Public)
.Where (t => t.Name.StartsWith (fieldPrefix, StringComparison.Ordinal))
.ToList ();
Assert.That (fields, Has.Count.AtLeast (1), String.Format ("{0} should define some property names.", type.Name));
// Verify that defined property names have correct value and properties exist
foreach (var field in fields) {
var name = field.Name.Substring (fieldPrefix.Length);
var value = field.GetValue (null);
Assert.AreEqual (name, value, String.Format ("{0}.{1} property value is {2}.", type.Name, field.Name, value));
var prop = type.GetProperty (name, BindingFlags.Public | BindingFlags.Instance);
Assert.NotNull (prop, String.Format ("{0}.{1} property doesn't exist.", type.Name, name));
}
// Verify that all public properties have the property name defined
var fieldNames = fields.Select (f => f.GetValue (null)).ToList ();
var properties = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
foreach (var prop in properties) {
if (!ExemptProperties.Contains (prop.Name)) {
Assert.IsTrue (fieldNames.Contains (prop.Name), String.Format ("{0}.{1}{2} static field is not defined.", type.Name, fieldPrefix, prop.Name));
}
}
}
}
}
|
bsd-3-clause
|
C#
|
f6456b511339cf1a411e78661655335b0d833a54
|
Update ContextController.cs
|
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
|
services/api/Tweek.ApiService.NetCore/Controllers/ContextController.cs
|
services/api/Tweek.ApiService.NetCore/Controllers/ContextController.cs
|
using System;
using Engine.DataTypes;
using Engine.Drivers.Context;
using FSharpUtils.Newtonsoft;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Tweek.ApiService.NetCore.Security;
namespace Tweek.ApiService.NetCore.Controllers
{
[Route("api/v1/context")]
public class ContextController : Controller
{
private readonly IContextDriver _contextDriver;
private readonly CheckWriteContextAccess _checkAccess;
public ContextController(IContextDriver contextDriver, JsonSerializer serializer, CheckWriteContextAccess checkAccess)
{
_contextDriver = contextDriver;
_checkAccess =checkAccess;
}
[HttpPost("{identityType}/{*identityId}")]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.Forbidden)]
public async Task<ActionResult> AppendContext([FromRoute] string identityType, [FromRoute] string identityId, [FromBody] Dictionary<string, JsonValue> data)
{
if (!_checkAccess(User, new Identity(identityType, identityId))) return Forbid();
var identity = new Identity(identityType, identityId);
await _contextDriver.AppendContext(identity, data);
return Ok();
}
[HttpDelete("{identityType}/{identityId}/{*prop}")]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.Forbidden)]
public async Task<ActionResult> DeleteFromContext([FromRoute] string identityType, [FromRoute] string identityId, [FromRoute] string prop)
{
if (!_checkAccess(User, new Identity(identityType, identityId))) return Forbid();
var identity = new Identity(identityType, identityId);
await _contextDriver.RemoveFromContext(identity, prop);
return Ok();
}
[HttpGet("{identityType}/{identityId}")]
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<ActionResult> GetContext([FromRoute] string identityType, [FromRoute] string identityId)
{
if (!User.IsTweekIdentity()) return Forbid();
var identity = new Identity(identityType, identityId);
var contextData = await _contextDriver.GetContext(identity);
return Json(contextData);
}
}
}
|
using System;
using Engine.DataTypes;
using Engine.Drivers.Context;
using FSharpUtils.Newtonsoft;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Tweek.ApiService.NetCore.Security;
namespace Tweek.ApiService.NetCore.Controllers
{
[Route("api/v1/context")]
public class ContextController : Controller
{
private readonly IContextDriver _contextDriver;
private readonly CheckWriteContextAccess _checkAccess;
public ContextController(IContextDriver contextDriver, JsonSerializer serializer, CheckWriteContextAccess checkAccess)
{
_contextDriver = contextDriver;
_checkAccess =checkAccess;
}
[HttpPost("{identityType}/{*identityId}")]
[Consumes("application/json")]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.Forbidden)]
public async Task<ActionResult> AppendContext([FromRoute] string identityType, [FromRoute] string identityId, [FromBody] Dictionary<string, JsonValue> data)
{
if (!_checkAccess(User, new Identity(identityType, identityId))) return Forbid();
var identity = new Identity(identityType, identityId);
await _contextDriver.AppendContext(identity, data);
return Ok();
}
[HttpDelete("{identityType}/{identityId}/{*prop}")]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.OK)]
[ProducesResponseType(typeof(void), (int)HttpStatusCode.Forbidden)]
public async Task<ActionResult> DeleteFromContext([FromRoute] string identityType, [FromRoute] string identityId, [FromRoute] string prop)
{
if (!_checkAccess(User, new Identity(identityType, identityId))) return Forbid();
var identity = new Identity(identityType, identityId);
await _contextDriver.RemoveFromContext(identity, prop);
return Ok();
}
[HttpGet("{identityType}/{identityId}")]
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<ActionResult> GetContext([FromRoute] string identityType, [FromRoute] string identityId)
{
if (!User.IsTweekIdentity()) return Forbid();
var identity = new Identity(identityType, identityId);
var contextData = await _contextDriver.GetContext(identity);
return Json(contextData);
}
}
}
|
mit
|
C#
|
101e6466d6872efe2704651ead12fe3cb93d1bd6
|
Include faction info in the RedeemVoucher event
|
jgoode/EDDiscovery,jgoode/EDDiscovery,mwerle/EDDiscovery,mwerle/EDDiscovery,jthorpe4/EDDiscovery
|
EDDiscovery/EliteDangerous/JournalEvents/JournalRedeemVoucher.cs
|
EDDiscovery/EliteDangerous/JournalEvents/JournalRedeemVoucher.cs
|
/*
* Copyright © 2016 EDDiscovery development team
*
* 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.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
using Newtonsoft.Json.Linq;
using System.Linq;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
// When Written: when claiming payment for combat bounties and bonds
//Parameters:
//• Type
//• Amount: (Net amount received, after any broker fee)
//• Faction: name of faction
//• BrokerPercenentage
[JournalEntryType(JournalTypeEnum.RedeemVoucher)]
public class JournalRedeemVoucher : JournalEntry, ILedgerJournalEntry
{
public JournalRedeemVoucher(JObject evt) : base(evt, JournalTypeEnum.RedeemVoucher)
{
Type = JSONHelper.GetStringDef(evt["Type"]);
Amount = JSONHelper.GetLong(evt["Amount"]);
Faction = JSONHelper.GetStringDef(evt["Faction"]);
BrokerPercentage = JSONHelper.GetDouble(evt["BrokerPercentage"]);
}
public string Type { get; set; }
public long Amount { get; set; }
public string Faction { get; set; }
public double BrokerPercentage { get; set; }
public static System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.bounty; } }
public void Ledger(EDDiscovery2.DB.MaterialCommoditiesLedger mcl, DB.SQLiteConnectionUser conn)
{
mcl.AddEvent(Id, EventTimeUTC, EventTypeID, Type + " Broker " + BrokerPercentage.ToString("0.0") + "%", Amount);
}
}
}
|
/*
* Copyright © 2016 EDDiscovery development team
*
* 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.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
using Newtonsoft.Json.Linq;
using System.Linq;
namespace EDDiscovery.EliteDangerous.JournalEvents
{
// When Written: when claiming payment for combat bounties and bonds
//Parameters:
//• Type
//• Amount: (Net amount received, after any broker fee)
//• BrokerPercenentage
[JournalEntryType(JournalTypeEnum.RedeemVoucher)]
public class JournalRedeemVoucher : JournalEntry, ILedgerJournalEntry
{
public JournalRedeemVoucher(JObject evt) : base(evt, JournalTypeEnum.RedeemVoucher)
{
Type = JSONHelper.GetStringDef(evt["Type"]);
Amount = JSONHelper.GetLong(evt["Amount"]);
BrokerPercentage = JSONHelper.GetDouble(evt["BrokerPercentage"]);
}
public string Type { get; set; }
public long Amount { get; set; }
public double BrokerPercentage { get; set; }
public static System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.bounty; } }
public void Ledger(EDDiscovery2.DB.MaterialCommoditiesLedger mcl, DB.SQLiteConnectionUser conn)
{
mcl.AddEvent(Id, EventTimeUTC, EventTypeID, Type + " Broker " + BrokerPercentage.ToString("0.0") + "%", Amount);
}
}
}
|
apache-2.0
|
C#
|
5d48da15ec7217c55559c86b53aa861b81409ac2
|
Fix bug in Array converter
|
Jericho/CakeMail.RestClient
|
CakeMail.RestClient/Utilities/CakeMailArrayConverter.cs
|
CakeMail.RestClient/Utilities/CakeMailArrayConverter.cs
|
using Newtonsoft.Json;
using System;
namespace CakeMail.RestClient.Utilities
{
/// <summary>
/// The Json for an array returned by CakeMail looks like this:
/// {
/// name_of_array_property: [ { ... item 1 ...} { ... item 2... } ]
/// }
/// The goal of this JsonConverter is to ignore the "array property" and to return an array of items.
///
/// Also, an empty array looks like this:
/// {
/// []
/// }
/// This JsonConverter returns an empty array in this scenario
/// </summary>
public class CakeMailArrayConverter : JsonConverter
{
private string _arrayPropertyName;
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public CakeMailArrayConverter(string arrayPropertyName)
{
_arrayPropertyName = arrayPropertyName;
}
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// The token type will be 'StartObject' when the items returned by CakeMail are in a "array property".
// In the case of an empty array, the token type will be 'StartArray' since CakeMail omits the "array property".
if (reader.TokenType == JsonToken.StartObject)
{
// Read the next token, presumably the property containing the items
reader.Read();
// Make sure the token we just read is the expected property
if (reader.TokenType != JsonToken.PropertyName) throw new JsonSerializationException(string.Format("Expected a property containing an array of items. Instead found a {0}", reader.TokenType));
if (!reader.Value.Equals(_arrayPropertyName)) throw new JsonSerializationException(string.Format("Expected a property called {0}. Instead found {1}", _arrayPropertyName, reader.Value));
// Read the next token, presumably the array of items
reader.Read();
}
// Make sure the property contains an array of items
if (reader.TokenType == JsonToken.StartArray)
{
var itemsSerializer = new JsonSerializer();
return itemsSerializer.Deserialize(reader, objectType);
}
// The Json does not seem to contain a CakeMail array
throw new JsonSerializationException("Json does not seem to contain CakeMail array");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
|
using Newtonsoft.Json;
using System;
namespace CakeMail.RestClient.Utilities
{
/// <summary>
/// The Json for an array returned by CakeMail looks like this:
/// {
/// name_of_array_property: [ { ... item 1 ...} { ... item 2... } ]
/// }
/// The goal of this JsonConverter is to ignore the "array property" and to return an array of items.
///
/// Also, an empty array looks like this:
/// {
/// []
/// }
/// This JsonConverter returns an empty array in this scenario
/// </summary>
public class CakeMailArrayConverter : JsonConverter
{
private string _arrayPropertyName;
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public CakeMailArrayConverter(string arrayPropertyName)
{
_arrayPropertyName = arrayPropertyName;
}
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// The token type will be 'StartObject' when the items returned by CakeMail are in a "array property".
// In the case of an empty array, the token type will be 'StartArray' since CakeMail omits the "array property".
if (reader.TokenType == JsonToken.StartObject)
{
// Read the next token, presumably the property containing the items
reader.Read();
// Make sure the token we just read is the expected property
if (reader.TokenType != JsonToken.PropertyName) throw new JsonSerializationException(string.Format("Expected a property containing an array of items. Instead found a {0}", reader.TokenType));
if (!reader.Value.Equals(_arrayPropertyName)) throw new JsonSerializationException(string.Format("Expected a property called {0}. Instead found {1}", _arrayPropertyName, reader.Value));
// Read the next token, presumably the numerical value
reader.Read();
// Parse the numerical value
var itemSerializer = new JsonSerializer();
return itemSerializer.Deserialize(reader, objectType);
}
// Make sure the property contains an array of items
if (reader.TokenType == JsonToken.StartArray)
{
var itemsSerializer = new JsonSerializer();
return itemsSerializer.Deserialize(reader, objectType);
}
// The Json does not seem to contain a CakeMail array
throw new JsonSerializationException("Json does not seem to contain CakeMail array");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
e06a1c7a4b12e6b5bcde0f339854979cd7afce1e
|
adjust assembly version for first release
|
lehmamic/undo-manager
|
trunc/src/UndoManager/Properties/AssemblyInfo.cs
|
trunc/src/UndoManager/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("UndoManager")]
[assembly: AssemblyDescription("An easy to use Undo API for .NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Diskordia")]
[assembly: AssemblyProduct("UndoManager")]
[assembly: AssemblyCopyright("Copyright © Diskordia 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a221d2b9-6334-4c16-831f-f372f0d362f5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.*")]
[assembly: AssemblyFileVersion("0.1")]
|
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("UndoManager")]
[assembly: AssemblyDescription("An easy to use Undo API for .NET.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Diskordia")]
[assembly: AssemblyProduct("UndoManager")]
[assembly: AssemblyCopyright("Copyright © Diskordia 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a221d2b9-6334-4c16-831f-f372f0d362f5")]
// 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.*")]
[assembly: AssemblyFileVersion("1.0")]
|
mit
|
C#
|
0bfd7579362d55a258163c70ba1a8640b1e11eff
|
Make OsuTextBox use BasicTextBox
|
ppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,ppy/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,peppy/osu,johnneijzen/osu,peppy/osu-new
|
osu.Game/Graphics/UserInterface/OsuTextBox.cs
|
osu.Game/Graphics/UserInterface/OsuTextBox.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.Sprites;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class OsuTextBox : BasicTextBox
{
protected override float LeftRightPadding => 10;
protected override SpriteText CreatePlaceholder() => new OsuSpriteText
{
Font = OsuFont.GetFont(italics: true),
Colour = new Color4(180, 180, 180, 255),
Margin = new MarginPadding { Left = 2 },
};
public OsuTextBox()
{
Height = 40;
TextContainer.Height = 0.5f;
CornerRadius = 5;
LengthLimit = 1000;
Current.DisabledChanged += disabled => { Alpha = disabled ? 0.3f : 1; };
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
BackgroundUnfocused = Color4.Black.Opacity(0.5f);
BackgroundFocused = OsuColour.Gray(0.3f).Opacity(0.8f);
BackgroundCommit = BorderColour = colour.Yellow;
}
protected override Color4 SelectionColour => new Color4(249, 90, 255, 255);
protected override void OnFocus(FocusEvent e)
{
BorderThickness = 3;
base.OnFocus(e);
}
protected override void OnFocusLost(FocusLostEvent e)
{
BorderThickness = 0;
base.OnFocusLost(e);
}
protected override Drawable GetDrawableCharacter(char c) => new OsuSpriteText { Text = c.ToString(), Font = OsuFont.GetFont(size: CalculatedTextSize) };
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics.Sprites;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Input.Events;
namespace osu.Game.Graphics.UserInterface
{
public class OsuTextBox : TextBox
{
protected override float LeftRightPadding => 10;
protected override SpriteText CreatePlaceholder() => new OsuSpriteText
{
Font = OsuFont.GetFont(italics: true),
Colour = new Color4(180, 180, 180, 255),
Margin = new MarginPadding { Left = 2 },
};
public OsuTextBox()
{
Height = 40;
TextContainer.Height = 0.5f;
CornerRadius = 5;
LengthLimit = 1000;
Current.DisabledChanged += disabled => { Alpha = disabled ? 0.3f : 1; };
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
BackgroundUnfocused = Color4.Black.Opacity(0.5f);
BackgroundFocused = OsuColour.Gray(0.3f).Opacity(0.8f);
BackgroundCommit = BorderColour = colour.Yellow;
}
protected override void OnFocus(FocusEvent e)
{
BorderThickness = 3;
base.OnFocus(e);
}
protected override void OnFocusLost(FocusLostEvent e)
{
BorderThickness = 0;
base.OnFocusLost(e);
}
protected override Drawable GetDrawableCharacter(char c) => new OsuSpriteText { Text = c.ToString(), Font = OsuFont.GetFont(size: CalculatedTextSize) };
}
}
|
mit
|
C#
|
58feba72a30824e7d5624dbf20bf6a0e2acc0666
|
Fix scheduled events not running on previous drawables
|
ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,johnneijzen/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,ZLima12/osu,2yangk23/osu,peppy/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,peppy/osu-new,smoogipoo/osu
|
osu.Game/Skinning/SkinReloadableDrawable.cs
|
osu.Game/Skinning/SkinReloadableDrawable.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 osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A drawable which has a callback when the skin changes.
/// </summary>
public abstract class SkinReloadableDrawable : CompositeDrawable
{
private readonly Func<ISkinSource, bool> allowFallback;
private ISkinSource skin;
/// <summary>
/// Whether fallback to default skin should be allowed if the custom skin is missing this resource.
/// </summary>
private bool allowDefaultFallback => allowFallback == null || allowFallback.Invoke(skin);
/// <summary>
/// Create a new <see cref="SkinReloadableDrawable"/>
/// </summary>
/// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param>
protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null)
{
this.allowFallback = allowFallback;
}
[BackgroundDependencyLoader]
private void load(ISkinSource source)
{
skin = source;
skin.SourceChanged += onChange;
}
private void onChange() =>
// schedule required to avoid calls after disposed.
// note that this has the side-effect of components only performance a skin change when they are alive.
Scheduler.AddOnce(() => SkinChanged(skin, allowDefaultFallback));
protected override void LoadAsyncComplete()
{
base.LoadAsyncComplete();
SkinChanged(skin, allowDefaultFallback);
}
/// <summary>
/// Called when a change is made to the skin.
/// </summary>
/// <param name="skin">The new skin.</param>
/// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param>
protected virtual void SkinChanged(ISkinSource skin, bool allowFallback)
{
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (skin != null)
skin.SourceChanged -= onChange;
}
}
}
|
// 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 osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Skinning
{
/// <summary>
/// A drawable which has a callback when the skin changes.
/// </summary>
public abstract class SkinReloadableDrawable : CompositeDrawable
{
private readonly Func<ISkinSource, bool> allowFallback;
private ISkinSource skin;
/// <summary>
/// Whether fallback to default skin should be allowed if the custom skin is missing this resource.
/// </summary>
private bool allowDefaultFallback => allowFallback == null || allowFallback.Invoke(skin);
/// <summary>
/// Create a new <see cref="SkinReloadableDrawable"/>
/// </summary>
/// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param>
protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null)
{
this.allowFallback = allowFallback;
}
[BackgroundDependencyLoader]
private void load(ISkinSource source)
{
skin = source;
skin.SourceChanged += onChange;
}
private void onChange() =>
// schedule required to avoid calls after disposed.
Schedule(() => SkinChanged(skin, allowDefaultFallback));
protected override void LoadAsyncComplete()
{
base.LoadAsyncComplete();
SkinChanged(skin, allowDefaultFallback);
}
/// <summary>
/// Called when a change is made to the skin.
/// </summary>
/// <param name="skin">The new skin.</param>
/// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param>
protected virtual void SkinChanged(ISkinSource skin, bool allowFallback)
{
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (skin != null)
skin.SourceChanged -= onChange;
}
}
}
|
mit
|
C#
|
67044093265452be16aa2eae09612097c9af07e1
|
Add more information to reported exceptions
|
ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab
|
source/Server/Integration/Azure/ApplicationInsightsMonitor.cs
|
source/Server/Integration/Azure/ApplicationInsightsMonitor.cs
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Metrics;
using MirrorSharp.Advanced;
using SharpLab.Server.MirrorSharp;
using SharpLab.Server.Monitoring;
namespace SharpLab.Server.Integration.Azure {
public class ApplicationInsightsMonitor : IMonitor {
private static readonly ConcurrentDictionary<MonitorMetric, MetricIdentifier> _metricIdentifiers = new();
private readonly TelemetryClient _client;
private readonly string _webAppName;
public ApplicationInsightsMonitor(TelemetryClient client, string webAppName) {
_client = Argument.NotNull(nameof(client), client);
_webAppName = Argument.NotNullOrEmpty(nameof(webAppName), webAppName);
}
public void Metric(MonitorMetric metric, double value) {
var identifier = _metricIdentifiers.GetOrAdd(metric, static m => new(m.Namespace, m.Name));
_client.GetMetric(identifier).TrackValue(value);
}
public void Exception(Exception exception, IWorkSession? session, IDictionary<string, string>? extras = null) {
var telemetry = new ExceptionTelemetry(exception) {
Properties = {
{ "Code", session?.GetText() },
{ "Language", session?.LanguageName },
{ "Target", session?.GetTargetName() },
}
};
AddDefaultDetails(telemetry, session, extras);
_client.TrackException(telemetry);
}
private void AddDefaultDetails<TTelemetry>(TTelemetry telemetry, IWorkSession? session, IDictionary<string, string>? extras)
where TTelemetry: ITelemetry, ISupportProperties
{
telemetry.Context.Session.Id = session?.GetSessionId();
telemetry.Properties.Add("Web App", _webAppName);
if (extras == null)
return;
foreach (var pair in extras) {
telemetry.Properties.Add(pair.Key, pair.Value);
}
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Metrics;
using MirrorSharp.Advanced;
using SharpLab.Server.MirrorSharp;
using SharpLab.Server.Monitoring;
namespace SharpLab.Server.Integration.Azure {
public class ApplicationInsightsMonitor : IMonitor {
private static readonly ConcurrentDictionary<MonitorMetric, MetricIdentifier> _metricIdentifiers = new();
private readonly TelemetryClient _client;
private readonly string _webAppName;
public ApplicationInsightsMonitor(TelemetryClient client, string webAppName) {
_client = Argument.NotNull(nameof(client), client);
_webAppName = Argument.NotNullOrEmpty(nameof(webAppName), webAppName);
}
public void Metric(MonitorMetric metric, double value) {
var identifier = _metricIdentifiers.GetOrAdd(metric, static m => new(m.Namespace, m.Name));
_client.GetMetric(identifier).TrackValue(value);
}
public void Exception(Exception exception, IWorkSession? session, IDictionary<string, string>? extras = null) {
var telemetry = new ExceptionTelemetry(exception) {
Properties = {
{ "Code", session?.GetText() }
}
};
AddDefaultDetails(telemetry, session, extras);
_client.TrackException(telemetry);
}
private void AddDefaultDetails<TTelemetry>(TTelemetry telemetry, IWorkSession? session, IDictionary<string, string>? extras)
where TTelemetry: ITelemetry, ISupportProperties
{
telemetry.Context.Session.Id = session?.GetSessionId();
telemetry.Properties.Add("Web App", _webAppName);
if (extras == null)
return;
foreach (var pair in extras) {
telemetry.Properties.Add(pair.Key, pair.Value);
}
}
}
}
|
bsd-2-clause
|
C#
|
19e9304f216107052c7b193eeddaeffabe9d9659
|
update version
|
prodot/ReCommended-Extension
|
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
|
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
|
using System.Reflection;
using ReCommendedExtension;
// 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(ZoneMarker.ExtensionName)]
[assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("prodot GmbH")]
[assembly: AssemblyProduct(ZoneMarker.ExtensionId)]
[assembly: AssemblyCopyright("© 2012-2022 prodot GmbH")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("5.7.3.0")]
[assembly: AssemblyFileVersion("5.7.3")]
|
using System.Reflection;
using ReCommendedExtension;
// 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(ZoneMarker.ExtensionName)]
[assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("prodot GmbH")]
[assembly: AssemblyProduct(ZoneMarker.ExtensionId)]
[assembly: AssemblyCopyright("© 2012-2022 prodot GmbH")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("5.7.2.0")]
[assembly: AssemblyFileVersion("5.7.2")]
|
apache-2.0
|
C#
|
4b28045371170657ed77a9ce00a4c73b521da02c
|
fix demo test
|
amiralles/contest,amiralles/contest
|
src/Contest.Demo/Demo.cs
|
src/Contest.Demo/Demo.cs
|
namespace Contest.Demo {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _ = System.Action<Contest.Core.Runner>;
// ReSharper disable UnusedMember.Local
class Contest101 {
_ this_is_a_passing_test = assert =>
assert.Equal(4, 2 + 2);
_ this_is_a_failing_test = assert =>
assert.Equal(5, 2 + 2);
_ this_is_a__should_throw__passing_test = test =>
test.ShouldThrow<NullReferenceException>(() => {
object target = null;
var dummy = target.ToString();
});
_ this_is_a__should_throw__failing_test = test =>
test.ShouldThrow<NullReferenceException>(() => {
//It doesn't throws; So it fails.
});
}
class Contest201 {
_ before_each = test => {
User.Create("pipe");
User.Create("vilmis");
User.Create("amiralles");
};
_ after_each = test =>
User.Reset();
_ find_existing_user_returns_user = assert =>
assert.IsNotNull(User.Find("pipe"));
_ find_non_existing_user_returns_null = assert =>
assert.IsNull(User.Find("not exists"));
_ create_user_adds_new_user = assert => {
User.Create("foo");
assert.Equal(4, User.Count());
};
}
class Contest301 {
// setup
_ before_echo = test =>
test.Bag["msg"] = "Hello World!";
//cleanup
_ after_echo = test =>
test.Bag["msg"] = null;
//actual test
_ echo = test =>
test.Equal("Hello World!", Utils.Echo(test.Bag["msg"]));
}
class Utils {
public static Func<object, object> Echo = msg => msg;
}
public class User {
static readonly List<string> _users = new List<string>();
public static Action Reset = () => _users.Clear();
public static Action<string> Create = name => _users.Add(name);
public static Func<int> Count = () => _users.Count;
public static Func<string, object> Find = name =>
_users.FirstOrDefault(u => u == name);
}
}
|
namespace Contest.Demo {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _ = System.Action<Contest.Core.Runner>;
class Contest101 {
_ this_is_a_passing_test = assert =>
assert.Equal(4, 2 + 2);
_ this_is_a_failing_test = assert =>
assert.Equal(5, 2 + 2);
_ this_is_a__should_throw__passing_test = test =>
test.ShouldThrow<NullReferenceException>(() => {
object target = null;
var dummy = target.ToString();
});
_ this_is_a__should_throw__failing_test = test =>
test.ShouldThrow<NullReferenceException>(() => {
//It doesn't throws; So it fails.
});
}
class Contest201 {
_ before_each = test => {
User.Create("pipe");
User.Create("vilmis");
User.Create("amiralles");
};
_ after_each = test =>
User.Reset();
_ find_existing_user_returns_user = assert =>
assert.IsNotNull(User.Find("pipe"));
_ find_non_existing_user_returns_null = assert =>
assert.IsNull(User.Find("not exists"));
_ create_user_adds_new_user = assert => {
User.Create("foo");
assert.Equal(4, User.Count());
};
}
class Contest301 {
_ before_foo = test => {
//Specific setup for foo case.
};
_ after_foo = test => {
//Specific teardown for foo case.
};
_ foo = assert => {
assert.Equal("foo", "foo");
};
}
public class User {
static readonly List<string> _users = new List<string>();
public static Action Reset = () => _users.Clear();
public static Action<string> Create = name => _users.Add(name);
public static Func<int> Count = () => _users.Count;
public static Func<string, object> Find = name =>
_users.FirstOrDefault(u => u == name);
}
}
|
mit
|
C#
|
1bac3dcb52abe127caecc2e3fb867d0e7e86e071
|
Remove unnecessary using
|
agens-no/PolyglotUnity
|
Assets/Polyglot/Scripts/SaveLanguagePreference.cs
|
Assets/Polyglot/Scripts/SaveLanguagePreference.cs
|
#if UNITY_5
using JetBrains.Annotations;
#endif
using UnityEngine;
namespace Polyglot
{
public class SaveLanguagePreference : MonoBehaviour, ILocalize
{
[SerializeField]
private string preferenceKey = "Polyglot.SelectedLanguage";
#if UNITY_5
[UsedImplicitly]
#endif
public void Start()
{
Localization.Instance.SelectedLanguage = (Language) PlayerPrefs.GetInt(preferenceKey);
Localization.Instance.AddOnLocalizeEvent(this);
}
public void OnLocalize()
{
PlayerPrefs.SetInt(preferenceKey, (int) Localization.Instance.SelectedLanguage);
}
}
}
|
#if UNITY_5
using JetBrains.Annotations;
#endif
using UnityEngine;
using System.Collections;
namespace Polyglot
{
public class SaveLanguagePreference : MonoBehaviour, ILocalize
{
[SerializeField]
private string preferenceKey = "Polyglot.SelectedLanguage";
#if UNITY_5
[UsedImplicitly]
#endif
public void Start()
{
Localization.Instance.SelectedLanguage = (Language) PlayerPrefs.GetInt(preferenceKey);
Localization.Instance.AddOnLocalizeEvent(this);
}
public void OnLocalize()
{
PlayerPrefs.SetInt(preferenceKey, (int) Localization.Instance.SelectedLanguage);
}
}
}
|
mit
|
C#
|
0020196e4818f9ef60f1511204dc95d72b9919b1
|
Comment List Extension method.
|
KevinJump/uSync,KevinJump/uSync,KevinJump/uSync
|
uSync8.Core/Extensions/ListExtensions.cs
|
uSync8.Core/Extensions/ListExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace uSync8.Core.Extensions
{
public static class ListExtensions
{
/// <summary>
/// Add item to list if the item is not null
/// </summary>
public static void AddNotNull<TObject>(this List<TObject> list, TObject item)
{
if (item == null) return;
list.Add(item);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace uSync8.Core.Extensions
{
public static class ListExtensions
{
public static void AddNotNull<TObject>(this List<TObject> list, TObject item)
{
if (item == null) return;
list.Add(item);
}
}
}
|
mpl-2.0
|
C#
|
cf21f1d8080a418e128232926fff21a8866367f1
|
Update server side API for single multiple answer question
|
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
|
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
|
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
|
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
|
using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRepository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var questions = _dbContext.SingleMultipleAnswerQuestion.ToList();
return questions;
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOption);
_dbContext.SaveChanges();
}
}
}
|
mit
|
C#
|
2f18e5ca18ad73bbd1b804d0b9b48f5a92d3a3e9
|
test for xml converter
|
Happi-cat/Untech.SharePoint
|
Untech.SharePoint.Common.Test/Converters/Custom/XmlFieldConverterTest.cs
|
Untech.SharePoint.Common.Test/Converters/Custom/XmlFieldConverterTest.cs
|
using System.Runtime.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Untech.SharePoint.Common.Converters;
using Untech.SharePoint.Common.Converters.Custom;
namespace Untech.SharePoint.Common.Test.Converters.Custom
{
[TestClass]
public class XmlFieldConverterTest : BaseConverterTest
{
[TestMethod]
public void CanConvertTestObject()
{
Given<TestObject>()
.CanConvertFromSp(null, null)
.CanConvertFromSp("", null)
.CanConvertFromSp("<Test />", new TestObject())
.CanConvertFromSp("<Test><Inner><Id>2</Id></Inner></Test>", new TestObject {Inner = new InnerObject {Id = 2}})
.CanConvertFromSp("<Test ><Field>value</Field></Test>", new TestObject {Field = "value"})
.CanConvertToSp(null, null)
.CanConvertToSp(new TestObject(),
"<Test xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" />")
.CanConvertToSp(new TestObject {Field = "test"},
"<Test xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Field>test</Field></Test>");
}
protected override IFieldConverter GetConverter()
{
return new XmlFieldConverter();
}
[DataContract(Name = "Test", Namespace = "")]
public class TestObject
{
[DataMember(Name = "Field", EmitDefaultValue = false)]
public string Field { get; set; }
[DataMember(Name = "Inner", EmitDefaultValue = false)]
public InnerObject Inner{ get; set; }
public override bool Equals(object obj)
{
if (obj == null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetHashCode() == GetHashCode();
}
public override int GetHashCode()
{
var innerHash = Inner != null ? Inner.Id.GetHashCode() : 0;
return (Field != null ? Field.GetHashCode() : 0) ^ innerHash;
}
}
[DataContract(Name = "Inner", Namespace = "")]
public class InnerObject
{
[DataMember(Name = "Id")]
public int Id { get; set; }
}
}
}
|
using System.Runtime.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Untech.SharePoint.Common.Converters;
using Untech.SharePoint.Common.Converters.Custom;
namespace Untech.SharePoint.Common.Test.Converters.Custom
{
[TestClass]
public class XmlFieldConverterTest : BaseConverterTest
{
[TestMethod]
public void CanConvertTestObject()
{
Given<TestObject>()
.CanConvertFromSp(null, null)
.CanConvertFromSp("", null)
.CanConvertFromSp("<Test xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" />", new TestObject())
.CanConvertFromSp("<Test xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Field>value</Field></Test>", new TestObject { Field = "value" })
.CanConvertToSp(null, null)
.CanConvertToSp(new TestObject(), "<Test xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" />")
.CanConvertToSp(new TestObject { Field = "test" }, "<Test xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><Field>test</Field></Test>");
}
protected override IFieldConverter GetConverter()
{
return new XmlFieldConverter();
}
[DataContract(Name = "Test", Namespace = "")]
public class TestObject
{
[DataMember(Name = "Field", EmitDefaultValue = false)]
public string Field { get; set; }
public override bool Equals(object obj)
{
if (obj == null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetHashCode() == GetHashCode();
}
public override int GetHashCode()
{
return Field != null ? Field.GetHashCode() : 0;
}
}
}
}
|
mit
|
C#
|
87891f8ba59b800c73115116b2dea1ff37c484bd
|
Fix grammar
|
martincostello/project-euler
|
src/ProjectEuler/Puzzle.cs
|
src/ProjectEuler/Puzzle.cs
|
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler
{
using System;
using System.Collections.Generic;
/// <summary>
/// The base class for puzzles.
/// </summary>
internal abstract class Puzzle : IPuzzle
{
/// <inheritdoc />
public abstract string Question { get; }
/// <inheritdoc />
public object Answer { get; protected set; }
/// <summary>
/// Gets the minimum number of arguments required to solve the puzzle.
/// </summary>
protected abstract int MinimumArguments { get; }
/// <inheritdoc />
public virtual int Solve(string[] args)
{
if (!EnsureArguments(args, MinimumArguments))
{
Console.Error.WriteLine(
"At least {0:N0} argument{1} {2} required.",
MinimumArguments,
MinimumArguments == 1 ? string.Empty : "s",
MinimumArguments == 1 ? "is" : "are");
return -1;
}
return SolveCore(args);
}
/// <summary>
/// Ensures that the specified number of arguments are present.
/// </summary>
/// <param name="args">The input arguments to the puzzle.</param>
/// <param name="minimumLength">The minimum number of arguments required.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="args"/> is at least
/// <paramref name="minimumLength"/> in length; otherwise <see langword="false"/>.
/// </returns>
protected static bool EnsureArguments(ICollection<string> args, int minimumLength)
{
return args.Count >= minimumLength;
}
/// <summary>
/// Solves the puzzle given the specified arguments.
/// </summary>
/// <param name="args">The input arguments to the puzzle.</param>
/// <returns>The exit code the application should return.</returns>
protected abstract int SolveCore(string[] args);
}
}
|
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler
{
using System;
using System.Collections.Generic;
/// <summary>
/// The base class for puzzles.
/// </summary>
internal abstract class Puzzle : IPuzzle
{
/// <inheritdoc />
public abstract string Question { get; }
/// <inheritdoc />
public object Answer { get; protected set; }
/// <summary>
/// Gets the minimum number of arguments required to solve the puzzle.
/// </summary>
protected abstract int MinimumArguments { get; }
/// <inheritdoc />
public virtual int Solve(string[] args)
{
if (!EnsureArguments(args, MinimumArguments))
{
Console.Error.WriteLine(
"At least {0:N0} argument{1} are required.",
MinimumArguments,
MinimumArguments == 1 ? string.Empty : "s");
return -1;
}
return SolveCore(args);
}
/// <summary>
/// Ensures that the specified number of arguments are present.
/// </summary>
/// <param name="args">The input arguments to the puzzle.</param>
/// <param name="minimumLength">The minimum number of arguments required.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="args"/> is at least
/// <paramref name="minimumLength"/> in length; otherwise <see langword="false"/>.
/// </returns>
protected static bool EnsureArguments(ICollection<string> args, int minimumLength)
{
return args.Count >= minimumLength;
}
/// <summary>
/// Solves the puzzle given the specified arguments.
/// </summary>
/// <param name="args">The input arguments to the puzzle.</param>
/// <returns>The exit code the application should return.</returns>
protected abstract int SolveCore(string[] args);
}
}
|
apache-2.0
|
C#
|
90062b534228582c42cceaec18aacb0b7459046a
|
tidy up some more
|
Syntronian/cbabb,Syntronian/cbabb
|
source/CBA/Views/Home/Index.cshtml
|
source/CBA/Views/Home/Index.cshtml
|
@{
ViewBag.Title = "CBA Travel Companion";
}
@section scripts
{
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css">
@*<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.min.js"></script>*@
}
<header class="bar bar-nav">
<h1 class="title"><img src="@Url.Content("~/assets/img/cba-logo.png")"/></h1>
</header>
<nav class="bar bar-tab">
<a class="tab-item" href="@Url.Action("Index")">
<span class="icon icon-home"></span>
<span class="tab-label">Home</span>
</a>
<a class="tab-item" href="#">
<i class="fa fa-heart fa-nav"></i><br/>
<span class="tab-label" style="display: block; font-size: 11px;">Share</span>
</a>
<a class="tab-item" href="#">
<span class="icon icon-gear"></span>
<span class="tab-label">Settings</span>
</a>
</nav>
<div class="content">
<p class="content-padded" style="text-align: center;">Travel companion</p>
@{ Html.BeginForm("Index", "Home", FormMethod.Get, new { style = "margin-top: 25%;", @class = "content-padded" }); }
@*<input type="search" name="q" placeholder=" Search" style="font-family:Arial, FontAwesome">
<button class="btn btn-primary btn-block"><span class="icon icon-check"></span></button>*@
<div class="input-group" style="margin-top: 20px;">
<input type="text" name="q" placeholder=" Search" style="font-family:Arial, FontAwesome; border: none;" required>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary"><span class="icon icon-check"></span></button>
</span>
</div>
@{ Html.EndForm(); }
</div>
|
@{
ViewBag.Title = "CBA Travel Companion";
}
@section scripts
{
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.min.js"></script>
}
<header class="bar bar-nav">
<h1 class="title"><img src="@Url.Content("~/assets/img/cba-logo.png")"/></h1>
</header>
<nav class="bar bar-tab">
<a class="tab-item" href="@Url.Action("Index")">
<span class="icon icon-home"></span>
<span class="tab-label">Home</span>
</a>
<a class="tab-item" href="#">
<i class="fa fa-heart fa-nav"></i><br/>
<span class="tab-label" style="display: block; font-size: 11px;">Share</span>
</a>
<a class="tab-item" href="#">
<span class="icon icon-gear"></span>
<span class="tab-label">Settings</span>
</a>
</nav>
<div class="content">
<p class="content-padded" style="text-align: center;">Travel companion</p>
@{ Html.BeginForm("Index", "Home", FormMethod.Get, new { style = "margin-top: 25%;", @class = "content-padded" }); }
@*<input type="search" name="q" placeholder=" Search" style="font-family:Arial, FontAwesome">
<button class="btn btn-primary btn-block"><span class="icon icon-check"></span></button>*@
<div class="input-group" style="margin-top: 20px;">
<input type="search" name="q" placeholder=" Search" style="font-family:Arial, FontAwesome" autofocus required>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary"><span class="icon icon-check"></span></button>
</span>
</div>
@{ Html.EndForm(); }
</div>
|
mit
|
C#
|
bea5d1d6ae1caa51b38369bf89c4c5430704b795
|
修复单元测试升级CO2NET之后的代码
|
JeffreySu/WxOpen,JeffreySu/WxOpen
|
src/Senparc.Weixin.WxOpen.Tests/Containers/SessionContainerTests.cs
|
src/Senparc.Weixin.WxOpen.Tests/Containers/SessionContainerTests.cs
|
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.Weixin.WxOpen.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Senparc.Weixin.MP.Test.CommonAPIs;
namespace Senparc.Weixin.WxOpen.Containers.Tests
{
[TestClass()]
public class SessionContainerTests:CommonApiTest
{
[TestMethod()]
public void UpdateSessionTest()
{
var openId = "openid";
var sessionKey = "sessionKey";
var unionId = "unionId";
var bag = SessionContainer.UpdateSession(null, openId, sessionKey, unionId);
Console.WriteLine("bag.Key:{0}",bag.Key);
Console.WriteLine("bag.ExpireTime:{0}",bag.ExpireTime);
var key = bag.Key;
Thread.Sleep(1000);
var bag2 = SessionContainer.GetSession(key);
Assert.IsNotNull(bag2);
Console.WriteLine("bag2.ExpireTime:{0}", bag2.ExpireTime);
}
}
}
|
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2018 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.Weixin.WxOpen.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Senparc.Weixin.MP.Test.CommonAPIs;
namespace Senparc.Weixin.WxOpen.Containers.Tests
{
[TestClass()]
public class SessionContainerTests:CommonApiTest
{
[TestMethod()]
public void UpdateSessionTest()
{
var openId = "openid";
var sessionKey = "sessionKey";
var bag = SessionContainer.UpdateSession(null, openId, sessionKey);
Console.WriteLine("bag.Key:{0}",bag.Key);
Console.WriteLine("bag.ExpireTime:{0}",bag.ExpireTime);
var key = bag.Key;
Thread.Sleep(1000);
var bag2 = SessionContainer.GetSession(key);
Assert.IsNotNull(bag2);
Console.WriteLine("bag2.ExpireTime:{0}", bag2.ExpireTime);
}
}
}
|
apache-2.0
|
C#
|
83a4fb6f37f0fe725e52771e1d762cd407a56e2c
|
Remove empty lines
|
ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu
|
osu.Game.Rulesets.Osu/Mods/OsuModApproachCircle.cs
|
osu.Game.Rulesets.Osu/Mods/OsuModApproachCircle.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 osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModApproachCircle : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Approach Circle";
public override string Acronym => "AC";
public override string Description => "Never trust the approach circles...";
public override double ScoreMultiplier => 1;
public override IconUsage? Icon { get; } = FontAwesome.Regular.Circle;
[SettingSource("Easing", "Change the easing type of the approach circles.", 0)]
public Bindable<Easing> BindableEasing { get; } = new Bindable<Easing>();
[SettingSource("Scale the size", "Change the factor of the approach circle scale.", 1)]
public BindableFloat Scale { get; } = new BindableFloat
{
Precision = 0.1f,
MinValue = 2,
MaxValue = 10,
Default = 4,
Value = 4
};
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable =>
{
drawable.ApplyCustomUpdateState += (drawableHitObj, state) =>
{
if (!(drawableHitObj is DrawableOsuHitObject drawableOsuHitObj) || !(drawableHitObj is DrawableHitCircle hitCircle)) return;
var obj = drawableOsuHitObj.HitObject;
hitCircle.BeginAbsoluteSequence(obj.StartTime - obj.TimePreempt, true);
hitCircle.ApproachCircle.ScaleTo(Scale.Value);
hitCircle.ApproachCircle.FadeIn(Math.Min(obj.TimeFadeIn, obj.TimePreempt));
hitCircle.ApproachCircle.ScaleTo(1f, obj.TimePreempt, BindableEasing.Value);
hitCircle.ApproachCircle.Expire(true);
};
});
}
}
}
|
// 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 osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Configuration;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModApproachCircle : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Approach Circle";
public override string Acronym => "AC";
public override string Description => "Never trust the approach circles...";
public override double ScoreMultiplier => 1;
public override IconUsage? Icon { get; } = FontAwesome.Regular.Circle;
[SettingSource("Easing", "Change the easing type of the approach circles.", 0)]
public Bindable<Easing> BindableEasing { get; } = new Bindable<Easing>();
[SettingSource("Scale the size", "Change the factor of the approach circle scale.", 1)]
public BindableFloat Scale { get; } = new BindableFloat
{
Precision = 0.1f,
MinValue = 2,
MaxValue = 10,
Default = 4,
Value = 4
};
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable =>
{
drawable.ApplyCustomUpdateState += (drawableHitObj, state) =>
{
if (!(drawableHitObj is DrawableOsuHitObject drawableOsuHitObj) || !(drawableHitObj is DrawableHitCircle hitCircle)) return;
var obj = drawableOsuHitObj.HitObject;
hitCircle.BeginAbsoluteSequence(obj.StartTime - obj.TimePreempt, true);
hitCircle.ApproachCircle.ScaleTo(Scale.Value);
hitCircle.ApproachCircle.FadeIn(Math.Min(obj.TimeFadeIn, obj.TimePreempt));
hitCircle.ApproachCircle.ScaleTo(1f, obj.TimePreempt, BindableEasing.Value);
hitCircle.ApproachCircle.Expire(true);
};
});
}
}
}
|
mit
|
C#
|
eae23784662e89b9d1bdc4d5b0710afe77d41303
|
Add WIP to search filters
|
peppy/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu
|
osu.Game/Overlays/BeatmapListing/SearchCategory.cs
|
osu.Game/Overlays/BeatmapListing/SearchCategory.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.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.BeatmapListing
{
public enum SearchCategory
{
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusAny))]
Any,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusLeaderboard))]
[Description("Has Leaderboard")]
Leaderboard,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusRanked))]
Ranked,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusQualified))]
Qualified,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusLoved))]
Loved,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusFavourites))]
Favourites,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusPending))]
[Description("Pending & WIP")]
Pending,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusWip))]
Wip,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusGraveyard))]
Graveyard,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusMine))]
[Description("My Maps")]
Mine,
}
}
|
// 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.ComponentModel;
using osu.Framework.Localisation;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Overlays.BeatmapListing
{
public enum SearchCategory
{
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusAny))]
Any,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusLeaderboard))]
[Description("Has Leaderboard")]
Leaderboard,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusRanked))]
Ranked,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusQualified))]
Qualified,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusLoved))]
Loved,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusFavourites))]
Favourites,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusPending))]
[Description("Pending & WIP")]
Pending,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusGraveyard))]
Graveyard,
[LocalisableDescription(typeof(BeatmapsStrings), nameof(BeatmapsStrings.StatusMine))]
[Description("My Maps")]
Mine,
}
}
|
mit
|
C#
|
87f404c23b9938a81a6604c96344aaef34711f38
|
Move logging lambda to its own method
|
LassieME/Discord.Net,RogueException/Discord.Net,AntiTcb/Discord.Net,Confruggy/Discord.Net
|
docs/guides/samples/logging.cs
|
docs/guides/samples/logging.cs
|
using Discord;
using Discord.Rest;
public class Program
{
private DiscordSocketClient _client;
static void Main(string[] args) => new Program().Start().GetAwaiter().GetResult();
public async Task Start()
{
_client = new DiscordSocketClient(new DiscordSocketConfig() {
LogLevel = LogSeverity.Info
});
_client.Log += Log;
await _client.LoginAsync(TokenType.Bot, "bot token");
await _client.ConnectAsync();
await Task.Delay(-1);
}
private Task Log(LogMessage message)
{
Console.WriteLine(message.ToString());
return Task.CompletedTask;
}
}
|
using Discord;
using Discord.Rest;
public class Program
{
private DiscordSocketClient _client;
static void Main(string[] args) => new Program().Start().GetAwaiter().GetResult();
public async Task Start()
{
_client = new DiscordSocketClient(new DiscordSocketConfig() {
LogLevel = LogSeverity.Info
});
_client.Log += (message) =>
{
Console.WriteLine($"{message.ToString()}");
return Task.CompletedTask;
};
await _client.LoginAsync(TokenType.Bot, "bot token");
await _client.ConnectAsync();
await Task.Delay(-1);
}
}
|
mit
|
C#
|
ba3d6e77c27a1cac091762d78e765944faa24d0a
|
Refactor SaveOptions
|
igitur/ClosedXML,ClosedXML/ClosedXML
|
ClosedXML/Excel/SaveOptions.cs
|
ClosedXML/Excel/SaveOptions.cs
|
// Keep this file CodeMaid organised and cleaned
using System;
namespace ClosedXML.Excel
{
public class SaveOptions
{
public SaveOptions()
{
#if DEBUG
this.ValidatePackage = true;
#else
this.ValidatePackage = false;
#endif
}
public Boolean EvaluateFormulasBeforeSaving { get; set; } = false;
public Boolean GenerateCalculationChain { get; set; } = true;
public Boolean ValidatePackage { get; set; }
}
}
|
using System;
namespace ClosedXML.Excel
{
public sealed class SaveOptions
{
public SaveOptions()
{
#if DEBUG
this.ValidatePackage = true;
#else
this.ValidatePackage = false;
#endif
this.EvaluateFormulasBeforeSaving = false;
this.GenerateCalculationChain = true;
}
public Boolean ValidatePackage;
public Boolean EvaluateFormulasBeforeSaving;
public Boolean GenerateCalculationChain;
}
}
|
mit
|
C#
|
07d28d9dda070285cfbbcb7dce804d4d3f029beb
|
fix typo in Foldable documentation
|
StanJav/language-ext,louthy/language-ext,StefanBertels/language-ext
|
LanguageExt.Core/TypeClasses/Foldable/Foldable.cs
|
LanguageExt.Core/TypeClasses/Foldable/Foldable.cs
|
using System;
using System.Diagnostics.Contracts;
using LanguageExt.Attributes;
namespace LanguageExt.TypeClasses
{
[Typeclass]
public interface Foldable<FA, A> : Foldable<Unit, FA, A>
{
}
[Typeclass]
public interface Foldable<Env, FA, A> : Typeclass
{
/// <summary>
/// In the case of lists, 'Fold', when applied to a binary
/// operator, a starting value(typically the left-identity of the operator),
/// and a list, reduces the list using the binary operator, from left to
/// right.
///
/// Note that, since the head of the resulting expression is produced by
/// an application of the operator to the first element of the list,
/// 'Fold' can produce a terminating expression from an infinite list.
/// </summary>
/// <typeparam name="S">Aggregate state type</typeparam>
/// <param name="state">Initial state</param>
/// <param name="f">Folder function, applied for each item in fa</param>
/// <returns>The aggregate state</returns>
[Pure]
Func<Env, S> Fold<S>(FA fa, S state, Func<S, A, S> f);
/// <summary>
/// In the case of lists, 'FoldBack', when applied to a binary
/// operator, a starting value(typically the left-identity of the operator),
/// and a list, reduces the list using the binary operator, from right to
/// left.
///
/// Note that to produce the outermost application of the operator the
/// entire input list must be traversed.
/// </summary>
/// <typeparam name="S">Aggregate state type</typeparam>
/// <param name="state">Initial state</param>
/// <param name="f">Folder function, applied for each item in fa</param>
/// <returns>The aggregate state</returns>
[Pure]
Func<Env, S> FoldBack<S>(FA fa, S state, Func<S, A, S> f);
/// <summary>
/// Number of items in the foldable
/// </summary>
/// <returns>Total number of items </returns>
[Pure]
Func<Env, int> Count(FA fa);
}
}
|
using System;
using System.Diagnostics.Contracts;
using LanguageExt.Attributes;
namespace LanguageExt.TypeClasses
{
[Typeclass]
public interface Foldable<FA, A> : Foldable<Unit, FA, A>
{
}
[Typeclass]
public interface Foldable<Env, FA, A> : Typeclass
{
/// <summary>
/// In the case of lists, 'Fold', when applied to a binary
/// operator, a starting value(typically the left-identity of the operator),
/// and a list, reduces the list using the binary operator, from left to
/// right.
///
/// Note that, since the head of the resulting expression is produced by
/// an application of the operator to the first element of the list,
/// 'Fold' can produce a terminating expression from an infinite list.
/// </summary>
/// <typeparam name="S">Aggregate state type</typeparam>
/// <param name="state">Initial state</param>
/// <param name="f">Folder function, applied for each item in fa</param>
/// <returns>The aggregate state</returns>
[Pure]
Func<Env, S> Fold<S>(FA fa, S state, Func<S, A, S> f);
/// <summary>
/// In the case of lists, 'FoldBack', when applied to a binary
/// operator, a starting value(typically the left-identity of the operator),
/// and a list, reduces the list using the binary operator, from left to
/// right.
///
/// Note that to produce the outermost application of the operator the
/// entire input list must be traversed.
/// </summary>
/// <typeparam name="S">Aggregate state type</typeparam>
/// <param name="state">Initial state</param>
/// <param name="f">Folder function, applied for each item in fa</param>
/// <returns>The aggregate state</returns>
[Pure]
Func<Env, S> FoldBack<S>(FA fa, S state, Func<S, A, S> f);
/// <summary>
/// Number of items in the foldable
/// </summary>
/// <returns>Total number of items </returns>
[Pure]
Func<Env, int> Count(FA fa);
}
}
|
mit
|
C#
|
d61d8bfa40cc0a823795844d78adec2e260326e3
|
Remove erroneous "$" symbol from "bling string."
|
brendanjbaker/Bakery
|
src/Bakery/Configuration/Properties/PropertyNotFoundException.cs
|
src/Bakery/Configuration/Properties/PropertyNotFoundException.cs
|
namespace Bakery.Configuration.Properties
{
using System;
public class PropertyNotFoundException
: Exception
{
private readonly String propertyName;
public PropertyNotFoundException(String propertyName)
{
this.propertyName = propertyName;
}
public override String Message
{
get
{
return $"Property \"{propertyName}\" not found.";
}
}
}
}
|
namespace Bakery.Configuration.Properties
{
using System;
public class PropertyNotFoundException
: Exception
{
private readonly String propertyName;
public PropertyNotFoundException(String propertyName)
{
this.propertyName = propertyName;
}
public override String Message
{
get
{
return $"Property \"${propertyName}\" not found.";
}
}
}
}
|
mit
|
C#
|
98126f71d90585991deb860bf60ec584472f24ba
|
use extension method to cleanup cookie path
|
18098924759/IdentityServer3,EternalXw/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,charoco/IdentityServer3,jackswei/IdentityServer3,angelapper/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,codeice/IdentityServer3,delloncba/IdentityServer3,18098924759/IdentityServer3,olohmann/IdentityServer3,delloncba/IdentityServer3,delRyan/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,paulofoliveira/IdentityServer3,delRyan/IdentityServer3,Agrando/IdentityServer3,Agrando/IdentityServer3,jackswei/IdentityServer3,roflkins/IdentityServer3,SonOfSam/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,openbizgit/IdentityServer3,buddhike/IdentityServer3,kouweizhong/IdentityServer3,paulofoliveira/IdentityServer3,yanjustino/IdentityServer3,18098924759/IdentityServer3,wondertrap/IdentityServer3,uoko-J-Go/IdentityServer,roflkins/IdentityServer3,paulofoliveira/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,buddhike/IdentityServer3,jonathankarsh/IdentityServer3,tonyeung/IdentityServer3,jonathankarsh/IdentityServer3,mvalipour/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,huoxudong125/Thinktecture.IdentityServer.v3,IdentityServer/IdentityServer3,codeice/IdentityServer3,iamkoch/IdentityServer3,yanjustino/IdentityServer3,charoco/IdentityServer3,wondertrap/IdentityServer3,bestwpw/IdentityServer3,angelapper/IdentityServer3,chicoribas/IdentityServer3,tuyndv/IdentityServer3,faithword/IdentityServer3,openbizgit/IdentityServer3,bodell/IdentityServer3,kouweizhong/IdentityServer3,uoko-J-Go/IdentityServer,openbizgit/IdentityServer3,buddhike/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,angelapper/IdentityServer3,roflkins/IdentityServer3,Agrando/IdentityServer3,tbitowner/IdentityServer3,faithword/IdentityServer3,faithword/IdentityServer3,EternalXw/IdentityServer3,charoco/IdentityServer3,uoko-J-Go/IdentityServer,olohmann/IdentityServer3,bestwpw/IdentityServer3,olohmann/IdentityServer3,yanjustino/IdentityServer3,EternalXw/IdentityServer3,jonathankarsh/IdentityServer3,delRyan/IdentityServer3,bodell/IdentityServer3,mvalipour/IdentityServer3,kouweizhong/IdentityServer3,SonOfSam/IdentityServer3,jackswei/IdentityServer3,codeice/IdentityServer3,tbitowner/IdentityServer3,ryanvgates/IdentityServer3,IdentityServer/IdentityServer3,chicoribas/IdentityServer3,tuyndv/IdentityServer3,ryanvgates/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,tonyeung/IdentityServer3,IdentityServer/IdentityServer3,iamkoch/IdentityServer3,tonyeung/IdentityServer3,iamkoch/IdentityServer3,ryanvgates/IdentityServer3,tbitowner/IdentityServer3,mvalipour/IdentityServer3,SonOfSam/IdentityServer3,bestwpw/IdentityServer3,bodell/IdentityServer3,chicoribas/IdentityServer3,delloncba/IdentityServer3,wondertrap/IdentityServer3,tuyndv/IdentityServer3
|
source/Core/Configuration/Hosting/SessionCookie.cs
|
source/Core/Configuration/Hosting/SessionCookie.cs
|
/*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Microsoft.Owin;
using System;
using System.ComponentModel;
using Thinktecture.IdentityModel;
using Thinktecture.IdentityServer.Core.Extensions;
#pragma warning disable 1591
namespace Thinktecture.IdentityServer.Core.Configuration.Hosting
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class SessionCookie
{
readonly IOwinContext context;
readonly IdentityServerOptions identityServerOptions;
protected internal SessionCookie(IOwinContext ctx, IdentityServerOptions options)
{
this.context = ctx;
this.identityServerOptions = options;
}
public virtual void IssueSessionId()
{
context.Response.Cookies.Append(
GetCookieName(), CryptoRandom.CreateUniqueId(),
CreateCookieOptions());
}
private Microsoft.Owin.CookieOptions CreateCookieOptions()
{
var path = context.Request.Environment.GetIdentityServerBasePath().CleanUrlPath();
var options = new Microsoft.Owin.CookieOptions
{
HttpOnly = false,
Secure = context.Request.IsSecure,
Path = path
};
return options;
}
private string GetCookieName()
{
return identityServerOptions.AuthenticationOptions.CookieOptions.GetSessionCookieName();
}
public virtual string GetSessionId()
{
return context.Request.Cookies[GetCookieName()];
}
public virtual void ClearSessionId()
{
var options = CreateCookieOptions();
options.Expires = DateTimeHelper.UtcNow.AddYears(-1);
var name = GetCookieName();
context.Response.Cookies.Append(name, ".", options);
}
}
}
|
/*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Microsoft.Owin;
using System;
using System.ComponentModel;
using Thinktecture.IdentityModel;
using Thinktecture.IdentityServer.Core.Extensions;
#pragma warning disable 1591
namespace Thinktecture.IdentityServer.Core.Configuration.Hosting
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class SessionCookie
{
readonly IOwinContext context;
readonly IdentityServerOptions identityServerOptions;
protected internal SessionCookie(IOwinContext ctx, IdentityServerOptions options)
{
this.context = ctx;
this.identityServerOptions = options;
}
public virtual void IssueSessionId()
{
context.Response.Cookies.Append(
GetCookieName(), CryptoRandom.CreateUniqueId(),
CreateCookieOptions());
}
private Microsoft.Owin.CookieOptions CreateCookieOptions()
{
var path = context.Request.Environment.GetIdentityServerBasePath();
if (path.EndsWith("/")) path = path.Substring(0, path.Length - 1);
if (String.IsNullOrWhiteSpace(path)) path = "/";
var options = new Microsoft.Owin.CookieOptions
{
HttpOnly = false,
Secure = context.Request.IsSecure,
Path = path
};
return options;
}
private string GetCookieName()
{
return identityServerOptions.AuthenticationOptions.CookieOptions.GetSessionCookieName();
}
public virtual string GetSessionId()
{
return context.Request.Cookies[GetCookieName()];
}
public virtual void ClearSessionId()
{
var options = CreateCookieOptions();
options.Expires = DateTimeHelper.UtcNow.AddYears(-1);
var name = GetCookieName();
context.Response.Cookies.Append(name, ".", options);
}
}
}
|
apache-2.0
|
C#
|
a3f18af8714361e51d055e8cf33312e0fe90aa4d
|
Remove unused progressSection calculation
|
jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl,mmoening/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl
|
PartPreviewWindow/View3D/SliceProgressReporter.cs
|
PartPreviewWindow/View3D/SliceProgressReporter.cs
|
/*
Copyright (c) 2017, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Diagnostics;
using MatterHackers.GCodeVisualizer;
using MatterHackers.Agg;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class SliceProgressReporter : IProgress<ProgressStatus>
{
private double currentValue = 0;
private double destValue = 10;
private IProgress<ProgressStatus> parentProgress;
private PrinterConfig printer;
private Stopwatch timer = Stopwatch.StartNew();
public SliceProgressReporter(IProgress<ProgressStatus> progressStatus, PrinterConfig printer)
{
this.parentProgress = progressStatus;
this.printer = printer;
}
public void Report(ProgressStatus progressStatus)
{
string value = progressStatus.Status;
if (GCodeFile.GetFirstNumberAfter("", value, ref currentValue)
&& GCodeFile.GetFirstNumberAfter("/", value, ref destValue))
{
if (destValue == 0)
{
destValue = 1;
}
timer.Restart();
progressStatus.Status = progressStatus.Status.TrimEnd('.');
progressStatus.Progress0To1 = currentValue / destValue;
}
else
{
printer.Connection.TerminalLog.WriteLine(value);
}
parentProgress.Report(progressStatus);
}
}
}
|
/*
Copyright (c) 2017, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Diagnostics;
using MatterHackers.GCodeVisualizer;
using MatterHackers.Agg;
namespace MatterHackers.MatterControl.PartPreviewWindow
{
public class SliceProgressReporter : IProgress<ProgressStatus>
{
private double currentValue = 0;
private double destValue = 10;
private IProgress<ProgressStatus> parentProgress;
private PrinterConfig printer;
private Stopwatch timer = Stopwatch.StartNew();
private string progressSection = "";
public SliceProgressReporter(IProgress<ProgressStatus> progressStatus, PrinterConfig printer)
{
this.parentProgress = progressStatus;
this.printer = printer;
}
public void Report(ProgressStatus progressStatus)
{
string value = progressStatus.Status;
if (GCodeFile.GetFirstNumberAfter("", value, ref currentValue)
&& GCodeFile.GetFirstNumberAfter("/", value, ref destValue))
{
if (destValue == 0)
{
destValue = 1;
}
int pos = value.IndexOf(currentValue.ToString());
if (pos != -1)
{
progressSection = value.Substring(0, pos);
}
else
{
progressSection = value;
}
timer.Restart();
progressStatus.Status = progressStatus.Status.TrimEnd('.');
progressStatus.Progress0To1 = currentValue / destValue;
}
else
{
printer.Connection.TerminalLog.WriteLine(value);
}
parentProgress.Report(progressStatus);
}
}
}
|
bsd-2-clause
|
C#
|
faf12a94d064a301c226b321eb201df04df0836c
|
Fix directory
|
KrzysztofCwalina/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,benaadams/corefxlab,tarekgh/corefxlab,whoisj/corefxlab,benaadams/corefxlab,adamsitnik/corefxlab,ahsonkhan/corefxlab,ericstj/corefxlab,ericstj/corefxlab,ericstj/corefxlab,KrzysztofCwalina/corefxlab,stephentoub/corefxlab,tarekgh/corefxlab,adamsitnik/corefxlab,dotnet/corefxlab,ericstj/corefxlab,ahsonkhan/corefxlab,joshfree/corefxlab,dotnet/corefxlab,ericstj/corefxlab,stephentoub/corefxlab,joshfree/corefxlab,whoisj/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,ericstj/corefxlab
|
src/System.IO.FileSystem.Watcher.Polling/System/IO/FileChange.cs
|
src/System.IO.FileSystem.Watcher.Polling/System/IO/FileChange.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.Diagnostics;
namespace System.IO.FileSystem
{
public struct FileChange
{
string _directory;
string _path;
ChangeType _chageType;
internal FileChange(string directory, string path, ChangeType type)
{
Debug.Assert(path != null);
_directory = directory;
_path = path;
_chageType = type;
}
public string Name
{
get
{
return _path;
}
}
public ChangeType ChangeType
{
get
{
return _chageType;
}
}
public string Directory
{
get
{
return _directory;
}
}
public string Path
{
get
{
return Directory + '\\' + Name;
}
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
namespace System.IO.FileSystem
{
public struct FileChange
{
string _directory;
string _path;
ChangeType _chageType;
internal FileChange(string directory, string path, ChangeType type)
{
Debug.Assert(path != null);
_directory = directory;
_path = path;
_chageType = type;
}
public string Name
{
get
{
return _path;
}
}
public ChangeType ChangeType
{
get
{
return _chageType;
}
}
public string Directory
{
get
{
return _directory.Substring(4, _directory.Length - 6);
}
}
public string Path
{
get
{
return Directory + '\\' + Name;
}
}
}
}
|
mit
|
C#
|
92ccdd61b9a2dbaa32c922812542ef9061892e85
|
Update version
|
webprofusion/Certify,Prerequisite/Certify,Marcus-L/Certify,ndouthit/Certify
|
src/Certify.Core/Properties/AssemblyInfo.cs
|
src/Certify.Core/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following set of attributes.
// Change these attribute values to modify the information associated with an assembly.
[assembly: AssemblyTitle("Certify The Web - SSL Certificate Manager")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Certify The Web")]
[assembly: AssemblyCopyright("Copyright © Webprofusion Pty Ltd 2015 - 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible to COM components. If you
// need to access a type in this assembly from COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("87baa9ca-e0c9-4d3e-8971-55a30134c942")]
// Version information for an assembly consists of the following four values:
//
// Major Version Minor Version Build Number Revision
//
// You can specify all the values or you can default the Build and Revision Numbers by using the '*'
// as shown below: [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.23.*")]
[assembly: AssemblyFileVersion("2.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("Certify The Web - SSL Certificate Manager")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Certify The Web")]
[assembly: AssemblyCopyright("Copyright © Webprofusion Pty Ltd 2015 - 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible to COM components. If you
// need to access a type in this assembly from COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("87baa9ca-e0c9-4d3e-8971-55a30134c942")]
// Version information for an assembly consists of the following four values:
//
// Major Version Minor Version Build Number Revision
//
// You can specify all the values or you can default the Build and Revision Numbers by using the '*'
// as shown below: [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.22.*")]
[assembly: AssemblyFileVersion("2.0.0")]
|
mit
|
C#
|
7fa0e75288a7124a55728feecb140ef02140b133
|
Change default Search URL Prefix
|
danielchalmers/DesktopWidgets
|
DesktopWidgets/Widgets/Search/Settings.cs
|
DesktopWidgets/Widgets/Search/Settings.cs
|
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.Search
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Style.Width = 150;
Style.FramePadding = new Thickness(0);
}
[Category("General")]
[DisplayName("URL Prefix")]
public string BaseUrl { get; set; } = "https://www.google.com/search?q=";
[Category("General")]
[DisplayName("URL Suffix")]
public string URLSuffix { get; set; }
}
}
|
using System.ComponentModel;
using System.Windows;
using DesktopWidgets.WidgetBase.Settings;
namespace DesktopWidgets.Widgets.Search
{
public class Settings : WidgetSettingsBase
{
public Settings()
{
Style.Width = 150;
Style.FramePadding = new Thickness(0);
}
[Category("General")]
[DisplayName("URL Prefix")]
public string BaseUrl { get; set; } = "http://";
[Category("General")]
[DisplayName("URL Suffix")]
public string URLSuffix { get; set; }
}
}
|
apache-2.0
|
C#
|
f9f53041b9da87946b63230b362691ff30b2bc36
|
Fix encoding issue while the query string parameters contains Chinese characters
|
exceptionless/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless
|
src/Exceptionless.Core/Extensions/UriExtensions.cs
|
src/Exceptionless.Core/Extensions/UriExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace Exceptionless.Core.Extensions {
public static class UriExtensions {
public static string ToQueryString(this NameValueCollection collection) {
return collection.AsKeyValuePairs().ToQueryString();
}
public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) {
return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={System.Web.HttpUtility.UrlEncode(pair.Value)}", "&");
}
/// <summary>
/// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence.
/// </summary>
private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) {
return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key)));
}
public static string GetBaseUrl(this Uri uri) {
return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace Exceptionless.Core.Extensions {
public static class UriExtensions {
public static string ToQueryString(this NameValueCollection collection) {
return collection.AsKeyValuePairs().ToQueryString();
}
public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) {
return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={pair.Value}", "&");
}
/// <summary>
/// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence.
/// </summary>
private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) {
return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key)));
}
public static string GetBaseUrl(this Uri uri) {
return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath;
}
}
}
|
apache-2.0
|
C#
|
5b41465266ca6aaef58c8be5b9b659e4a40671f2
|
remove unneeded reflection schema stuff (for now)
|
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
|
src/FilterLists.Data/Schema/JsonSchemaGenerator.cs
|
src/FilterLists.Data/Schema/JsonSchemaGenerator.cs
|
using System;
using System.IO;
using FilterLists.Data.Models.Implementations;
using Newtonsoft.Json.Schema.Generation;
namespace FilterLists.Data.Schema
{
public static class JsonSchemaGenerator
{
public static void WriteSchemaToFiles()
{
WriteSchemaToFile(typeof(List));
}
private static void WriteSchemaToFile(Type type)
{
File.WriteAllText(
Path.GetFullPath(Path.Combine(AppContext.BaseDirectory + @"\", @"..\..\..\..\..\data\")) + type.Name +
"Schema.json", new JSchemaGenerator().Generate(type).ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using FilterLists.Data.Models.Implementations;
using Newtonsoft.Json.Schema.Generation;
namespace FilterLists.Data.Schema
{
public static class JsonSchemaGenerator
{
public static void WriteSchemaToFiles()
{
foreach (var type in GetTypesInNamespace(Assembly.GetExecutingAssembly(),
"FilterLists.Data.Models.Implementations"))
{
if (type != typeof(List)) continue; //TEMP: only document List schema for now
WriteSchemaToFile(type);
}
}
private static void WriteSchemaToFile(Type type)
{
File.WriteAllText(
Path.GetFullPath(Path.Combine(AppContext.BaseDirectory + @"\", @"..\..\..\..\..\data\")) +
type.Name + "Schema.json", new JSchemaGenerator().Generate(type).ToString());
}
private static IEnumerable<Type> GetTypesInNamespace(Assembly assembly, string @namespace)
{
return assembly.GetTypes().Where(t => string.Equals(t.Namespace, @namespace, StringComparison.Ordinal));
}
}
}
|
mit
|
C#
|
12131d92390a208b7f6189269a21f17774c97d17
|
Make TestUserProfile service more derivation friendly
|
jbijlsma/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,chrisowhite/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,jbijlsma/IdentityServer4,chrisowhite/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4
|
src/IdentityServer4/Test/TestUserProfileService.cs
|
src/IdentityServer4/Test/TestUserProfileService.cs
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServer4.Test
{
public class TestUserProfileService : IProfileService
{
protected readonly ILogger Logger;
protected readonly TestUserStore Users;
public TestUserProfileService(TestUserStore users, ILogger<TestUserProfileService> logger)
{
Users = users;
Logger = logger;
}
public virtual Task GetProfileDataAsync(ProfileDataRequestContext context)
{
Logger.LogDebug("Get profile called for subject {subject} from client {client} with claim types {claimTypes} via {caller}",
context.Subject.GetSubjectId(),
context.Client.ClientName ?? context.Client.ClientId,
context.RequestedClaimTypes,
context.Caller);
if (context.RequestedClaimTypes.Any())
{
var user = Users.FindBySubjectId(context.Subject.GetSubjectId());
context.AddFilteredClaims(user.Claims);
}
return Task.FromResult(0);
}
public virtual Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true;
return Task.FromResult(0);
}
}
}
|
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
namespace IdentityServer4.Test
{
public class TestUserProfileService : IProfileService
{
private readonly ILogger<TestUserProfileService> _logger;
private readonly TestUserStore _users;
public TestUserProfileService(TestUserStore users, ILogger<TestUserProfileService> logger)
{
_users = users;
_logger = logger;
}
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
_logger.LogDebug("Get profile called for subject {subject} from client {client} with claim types{claimTypes} via {caller}",
context.Subject.GetSubjectId(),
context.Client.ClientName ?? context.Client.ClientId,
context.RequestedClaimTypes,
context.Caller);
if (context.RequestedClaimTypes.Any())
{
var user = _users.FindBySubjectId(context.Subject.GetSubjectId());
context.AddFilteredClaims(user.Claims);
}
return Task.FromResult(0);
}
public Task IsActiveAsync(IsActiveContext context)
{
context.IsActive = true;
return Task.FromResult(0);
}
}
}
|
apache-2.0
|
C#
|
14361cb59bf4170866a711dcfa5f7edecbdf972e
|
fix name
|
mzrimsek/resume-site-api
|
Integration.EntityFramework/Models/Job.cs
|
Integration.EntityFramework/Models/Job.cs
|
using System;
using System.ComponentModel.DataAnnotations;
namespace Integration.EntityFramework.Models
{
public class Job
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string City { get; set; }
[Required]
public string State { get; set; }
[Required]
public string Title { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate;
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace Integration.EntityFramework.Models
{
public class JobDatabaseModel
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string City { get; set; }
[Required]
public string State { get; set; }
[Required]
public string Title { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate;
}
}
|
mit
|
C#
|
00b784618caa58b2efe38b9d54cf8fc57bbc93da
|
hide Register link from navigation #102
|
FanrayMedia/Fanray,FanrayMedia/Fanray,FanrayMedia/Fanray
|
src/Fan.Web/Views/Shared/_LoginPartial.cshtml
|
src/Fan.Web/Views/Shared/_LoginPartial.cshtml
|
@using Microsoft.AspNetCore.Identity
@using Fan.Models
@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @((await UserManager.FindByNameAsync(User.Identity.Name)).DisplayName)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
@*<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>*@
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
|
@using Microsoft.AspNetCore.Identity
@using Fan.Models
@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @((await UserManager.FindByNameAsync(User.Identity.Name)).DisplayName)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
|
apache-2.0
|
C#
|
d62349c945e99df935d5970f882ba1bd81e1d613
|
Fix bug in IQuery interface
|
csf-dev/CSF.Security
|
CSF/Data/IQuery.cs
|
CSF/Data/IQuery.cs
|
//
// IQuery.cs
//
// Author:
// Craig Fowler <craig@craigfowler.me.uk>
//
// Copyright (c) 2016 Craig Fowler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
namespace CSF.Data
{
/// <summary>
/// Interface for a query component that is capable of returning a queryable data source.
/// </summary>
public interface IQuery
{
/// <summary>
/// Creates an instance of the given object-type, based upon a theory that it exists in the underlying data-source.
/// </summary>
/// <remarks>
/// <para>
/// This method will always return a non-null object instance, even if the underlying object does not exist in the
/// data source. If a 'thoery object' is created for an object which does not actually exist, then an exception
/// could be thrown if that theory object is used.
/// </para>
/// </remarks>
/// <param name="identityValue">The identity value for the object to retrieve.</param>
/// <typeparam name="TQueried">The type of object to retrieve.</typeparam>
TQueried Theorise<TQueried>(object identityValue) where TQueried : class;
/// <summary>
/// Gets a single instance from the underlying data source, identified by an identity value.
/// </summary>
/// <remarks>
/// <para>
/// This method will either get an object instance, or it will return <c>null</c> (if no instance is found).
/// </para>
/// </remarks>
/// <param name="identityValue">The identity value for the object to retrieve.</param>
/// <typeparam name="TQueried">The type of object to retrieve.</typeparam>
TQueried Get<TQueried>(object identityValue) where TQueried : class;
/// <summary>
/// Gets a new queryable data-source.
/// </summary>
/// <typeparam name="TQueried">The type of queried-for object.</typeparam>
IQueryable<TQueried> Query<TQueried>() where TQueried : class;
}
}
|
//
// IQuery.cs
//
// Author:
// Craig Fowler <craig@craigfowler.me.uk>
//
// Copyright (c) 2016 Craig Fowler
//
// 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;
namespace CSF.Data
{
/// <summary>
/// Interface for a query component that is capable of returning a queryable data source.
/// </summary>
public interface IQuery
{
/// <summary>
/// Creates an instance of the given object-type, based upon a theory that it exists in the underlying data-source.
/// </summary>
/// <remarks>
/// <para>
/// This method will always return a non-null object instance, even if the underlying object does not exist in the
/// data source. If a 'thoery object' is created for an object which does not actually exist, then an exception
/// could be thrown if that theory object is used.
/// </para>
/// </remarks>
/// <param name="identityValue">The identity value for the object to retrieve.</param>
/// <typeparam name="TQueried">The type of object to retrieve.</typeparam>
TQueried Theorise<TQueried>(object identityValue) where TQueried : class;
/// <summary>
/// Gets a single instance from the underlying data source, identified by an identity value.
/// </summary>
/// <remarks>
/// <para>
/// This method will either get an object instance, or it will return <c>null</c> (if no instance is found).
/// </para>
/// </remarks>
/// <param name="identityValue">The identity value for the object to retrieve.</param>
/// <typeparam name="TQueried">The type of object to retrieve.</typeparam>
TQueried Get<TQueried>(object identityValue) where TQueried : class;
/// <summary>
/// Gets a new queryable data-source.
/// </summary>
/// <typeparam name="TQueried">The type of queried-for object.</typeparam>
TQueried Query<TQueried>() where TQueried : class;
}
}
|
mit
|
C#
|
e2e3423966dd80c9dbb9aa326bbb2aae7bef9a95
|
fix hoe breaking objects on untilled dirt
|
Pathoschild/StardewMods
|
TractorMod/Framework/Attachments/HoeAttachment.cs
|
TractorMod/Framework/Attachments/HoeAttachment.cs
|
using Microsoft.Xna.Framework;
using StardewValley;
using StardewValley.TerrainFeatures;
using StardewValley.Tools;
using SFarmer = StardewValley.Farmer;
using SObject = StardewValley.Object;
namespace Pathoschild.Stardew.TractorMod.Framework.Attachments
{
/// <summary>An attachment for the hoe.</summary>
internal class HoeAttachment : BaseAttachment
{
/*********
** Public methods
*********/
/// <summary>Get whether the tool is currently enabled.</summary>
/// <param name="player">The current player.</param>
/// <param name="tool">The tool selected by the player (if any).</param>
/// <param name="item">The item selected by the player (if any).</param>
/// <param name="location">The current location.</param>
public override bool IsEnabled(SFarmer player, Tool tool, Item item, GameLocation location)
{
return tool is Hoe;
}
/// <summary>Apply the tool to the given tile.</summary>
/// <param name="tile">The tile to modify.</param>
/// <param name="tileObj">The object on the tile.</param>
/// <param name="tileFeature">The feature on the tile.</param>
/// <param name="player">The current player.</param>
/// <param name="tool">The tool selected by the player (if any).</param>
/// <param name="item">The item selected by the player (if any).</param>
/// <param name="location">The current location.</param>
public override bool Apply(Vector2 tile, SObject tileObj, TerrainFeature tileFeature, SFarmer player, Tool tool, Item item, GameLocation location)
{
// till plain dirt
if (tileFeature == null && tileObj == null)
return this.UseToolOnTile(tool, tile);
return false;
}
}
}
|
using Microsoft.Xna.Framework;
using StardewValley;
using StardewValley.TerrainFeatures;
using StardewValley.Tools;
using SFarmer = StardewValley.Farmer;
using SObject = StardewValley.Object;
namespace Pathoschild.Stardew.TractorMod.Framework.Attachments
{
/// <summary>An attachment for the hoe.</summary>
internal class HoeAttachment : BaseAttachment
{
/*********
** Public methods
*********/
/// <summary>Get whether the tool is currently enabled.</summary>
/// <param name="player">The current player.</param>
/// <param name="tool">The tool selected by the player (if any).</param>
/// <param name="item">The item selected by the player (if any).</param>
/// <param name="location">The current location.</param>
public override bool IsEnabled(SFarmer player, Tool tool, Item item, GameLocation location)
{
return tool is Hoe;
}
/// <summary>Apply the tool to the given tile.</summary>
/// <param name="tile">The tile to modify.</param>
/// <param name="tileObj">The object on the tile.</param>
/// <param name="tileFeature">The feature on the tile.</param>
/// <param name="player">The current player.</param>
/// <param name="tool">The tool selected by the player (if any).</param>
/// <param name="item">The item selected by the player (if any).</param>
/// <param name="location">The current location.</param>
public override bool Apply(Vector2 tile, SObject tileObj, TerrainFeature tileFeature, SFarmer player, Tool tool, Item item, GameLocation location)
{
return this.UseToolOnTile(tool, tile);
}
}
}
|
mit
|
C#
|
1a26658ba4d3ab18ce3661bb4f1ec4b8405d825d
|
Add description for mania special style
|
NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu
|
osu.Game.Rulesets.Mania/Edit/Setup/ManiaSetupSection.cs
|
osu.Game.Rulesets.Mania/Edit/Setup/ManiaSetupSection.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterfaceV2;
using osu.Game.Screens.Edit.Setup;
namespace osu.Game.Rulesets.Mania.Edit.Setup
{
public class ManiaSetupSection : RulesetSetupSection
{
private LabelledSwitchButton specialStyle;
public ManiaSetupSection()
: base(new ManiaRuleset().RulesetInfo)
{
}
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
specialStyle = new LabelledSwitchButton
{
Label = "Use special (N+1) style",
Description = "Changes one column to act as a classic \"scratch\" or \"special\" column, which can be moved around by the user's skin (to the left/right/centre). Generally used in 5k (4+1) or 8key (7+1) configurations.",
Current = { Value = Beatmap.BeatmapInfo.SpecialStyle }
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
specialStyle.Current.BindValueChanged(_ => updateBeatmap());
}
private void updateBeatmap()
{
Beatmap.BeatmapInfo.SpecialStyle = specialStyle.Current.Value;
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterfaceV2;
using osu.Game.Screens.Edit.Setup;
namespace osu.Game.Rulesets.Mania.Edit.Setup
{
public class ManiaSetupSection : RulesetSetupSection
{
private LabelledSwitchButton specialStyle;
public ManiaSetupSection()
: base(new ManiaRuleset().RulesetInfo)
{
}
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
specialStyle = new LabelledSwitchButton
{
Label = "Use special (N+1) style",
Current = { Value = Beatmap.BeatmapInfo.SpecialStyle }
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
specialStyle.Current.BindValueChanged(_ => updateBeatmap());
}
private void updateBeatmap()
{
Beatmap.BeatmapInfo.SpecialStyle = specialStyle.Current.Value;
}
}
}
|
mit
|
C#
|
f647ba703fef8a0af85dedc12c60ce936f56fa7c
|
Clean up formatting
|
ballance/QuickTest
|
QuickTest/CompressionTester.cs
|
QuickTest/CompressionTester.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
public class CompressionTester
{
public static int bufferSize = 32768;
public string Compress(string uncompressedString)
{
var inputData = Encoding.UTF8.GetBytes(uncompressedString);
using (var output = new MemoryStream())
{
using (var compression = new GZipStream(output, CompressionMode.Compress, false))
{
compression.Write(inputData, 0, inputData.Length);
}
return Convert.ToBase64String(output.ToArray());
}
}
public string Decompress(string compressedString)
{
byte[] gzBuffer = Convert.FromBase64String(compressedString);
using (var inStream = new MemoryStream(gzBuffer))
{
using (var outStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(inStream, CompressionMode.Decompress))
{
var buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = gzipStream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
}
}
return Encoding.UTF8.GetString(outStream.ToArray());
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
public class CompressionTester
{
public static int bufferSize = 32768;
public string Compress(string uncompressedString)
{
var inputData = Encoding.UTF8.GetBytes(uncompressedString);
using (var output = new MemoryStream())
{
using (var compression = new GZipStream(output, CompressionMode.Compress, false))
{
compression.Write(inputData, 0, inputData.Length);
}
return Convert.ToBase64String(output.ToArray());
}
}
public string Decompress(string compressedString)
{
byte[] gzBuffer = Convert.FromBase64String(compressedString);
using (var inStream = new MemoryStream(gzBuffer))
{
using (var outStream = new MemoryStream())
{
using (var gzipStream = new GZipStream(inStream, CompressionMode.Decompress))
{
var buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = gzipStream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
}
}
return Encoding.UTF8.GetString(outStream.ToArray());
}
}
}
}
}
|
mit
|
C#
|
0925586c22d4961e18f0352c5e12fc4905cc952a
|
Implement messenger
|
sakapon/Samples-2017
|
Network/UdpSample/UdpMessenger/Program.cs
|
Network/UdpSample/UdpMessenger/Program.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace UdpMessenger
{
class Program
{
static void Main(string[] args)
{
try
{
var localPort = int.Parse(GetInput("Local Port: ", "8100"));
var remoteHost = GetInput("Remote Host: ", "localhost");
var remotePort = int.Parse(GetInput("Remote Port: ", "8101"));
using (var client = new TextUdpClient(localPort, remoteHost, remotePort))
{
client.TextReceived += s => Console.WriteLine($"Received: {s}");
Console.WriteLine();
Console.WriteLine("Input message.");
Console.WriteLine("Input [x] to exit.");
foreach (var message in GetInputs())
{
client.SendText(message);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static string GetInput(string message = "", string defaultValue = "")
{
Console.Write(message);
var input = Console.ReadLine();
return string.IsNullOrWhiteSpace(input) ? defaultValue : input;
}
static IEnumerable<string> GetInputs(string message = "", string defaultValue = "")
{
while (true)
{
var input = GetInput(message, defaultValue);
if (string.Equals(input, "x", StringComparison.InvariantCultureIgnoreCase)) yield break;
yield return input;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UdpMessenger
{
class Program
{
static void Main(string[] args)
{
}
}
}
|
mit
|
C#
|
788c94f11e451706df6b6685e781c1fb8812b8c6
|
Update AssemblyRedirects.cs
|
mgoertz-msft/roslyn,bkoelman/roslyn,physhi/roslyn,mattscheffer/roslyn,MichalStrehovsky/roslyn,stephentoub/roslyn,jeffanders/roslyn,leppie/roslyn,brettfo/roslyn,AmadeusW/roslyn,KevinH-MS/roslyn,physhi/roslyn,stephentoub/roslyn,tmeschter/roslyn,KevinH-MS/roslyn,aelij/roslyn,AArnott/roslyn,weltkante/roslyn,yeaicc/roslyn,amcasey/roslyn,xasx/roslyn,paulvanbrenk/roslyn,TyOverby/roslyn,CyrusNajmabadi/roslyn,jkotas/roslyn,weltkante/roslyn,michalhosala/roslyn,swaroop-sridhar/roslyn,AArnott/roslyn,CaptainHayashi/roslyn,Pvlerick/roslyn,MatthieuMEZIL/roslyn,brettfo/roslyn,jaredpar/roslyn,jamesqo/roslyn,diryboy/roslyn,jcouv/roslyn,davkean/roslyn,bkoelman/roslyn,diryboy/roslyn,jamesqo/roslyn,lorcanmooney/roslyn,gafter/roslyn,xoofx/roslyn,AnthonyDGreen/roslyn,drognanar/roslyn,mmitche/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,dpoeschl/roslyn,Hosch250/roslyn,KiloBravoLima/roslyn,ljw1004/roslyn,AmadeusW/roslyn,leppie/roslyn,tmat/roslyn,MattWindsor91/roslyn,mgoertz-msft/roslyn,Giftednewt/roslyn,physhi/roslyn,reaction1989/roslyn,mavasani/roslyn,cston/roslyn,brettfo/roslyn,gafter/roslyn,khyperia/roslyn,khyperia/roslyn,nguerrera/roslyn,abock/roslyn,tvand7093/roslyn,pdelvo/roslyn,panopticoncentral/roslyn,natidea/roslyn,natidea/roslyn,bartdesmet/roslyn,bbarry/roslyn,balajikris/roslyn,OmarTawfik/roslyn,zooba/roslyn,ericfe-ms/roslyn,DustinCampbell/roslyn,natidea/roslyn,eriawan/roslyn,jaredpar/roslyn,mattscheffer/roslyn,Pvlerick/roslyn,KevinRansom/roslyn,ericfe-ms/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,jhendrixMSFT/roslyn,Giftednewt/roslyn,AlekseyTs/roslyn,lorcanmooney/roslyn,KevinRansom/roslyn,pdelvo/roslyn,stephentoub/roslyn,zooba/roslyn,vslsnap/roslyn,balajikris/roslyn,AArnott/roslyn,aelij/roslyn,wvdd007/roslyn,OmarTawfik/roslyn,amcasey/roslyn,Shiney/roslyn,gafter/roslyn,swaroop-sridhar/roslyn,KirillOsenkov/roslyn,budcribar/roslyn,robinsedlaczek/roslyn,davkean/roslyn,Shiney/roslyn,MichalStrehovsky/roslyn,DustinCampbell/roslyn,reaction1989/roslyn,heejaechang/roslyn,bbarry/roslyn,ErikSchierboom/roslyn,jaredpar/roslyn,heejaechang/roslyn,davkean/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,Giftednewt/roslyn,nguerrera/roslyn,balajikris/roslyn,kelltrick/roslyn,aelij/roslyn,sharwell/roslyn,jmarolf/roslyn,dotnet/roslyn,AnthonyDGreen/roslyn,panopticoncentral/roslyn,srivatsn/roslyn,MatthieuMEZIL/roslyn,agocke/roslyn,eriawan/roslyn,orthoxerox/roslyn,swaroop-sridhar/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,TyOverby/roslyn,genlu/roslyn,wvdd007/roslyn,abock/roslyn,genlu/roslyn,TyOverby/roslyn,leppie/roslyn,akrisiun/roslyn,xoofx/roslyn,dotnet/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mmitche/roslyn,mavasani/roslyn,dpoeschl/roslyn,akrisiun/roslyn,yeaicc/roslyn,panopticoncentral/roslyn,MichalStrehovsky/roslyn,KiloBravoLima/roslyn,a-ctor/roslyn,reaction1989/roslyn,VSadov/roslyn,VSadov/roslyn,tmat/roslyn,tannergooding/roslyn,MatthieuMEZIL/roslyn,CyrusNajmabadi/roslyn,srivatsn/roslyn,bartdesmet/roslyn,paulvanbrenk/roslyn,a-ctor/roslyn,AlekseyTs/roslyn,Hosch250/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,michalhosala/roslyn,MattWindsor91/roslyn,shyamnamboodiripad/roslyn,michalhosala/roslyn,AnthonyDGreen/roslyn,mattwar/roslyn,dotnet/roslyn,Hosch250/roslyn,heejaechang/roslyn,tannergooding/roslyn,vslsnap/roslyn,jhendrixMSFT/roslyn,agocke/roslyn,KevinH-MS/roslyn,OmarTawfik/roslyn,kelltrick/roslyn,jmarolf/roslyn,xasx/roslyn,AmadeusW/roslyn,jkotas/roslyn,tmeschter/roslyn,lorcanmooney/roslyn,jcouv/roslyn,VSadov/roslyn,sharwell/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,xoofx/roslyn,Shiney/roslyn,budcribar/roslyn,jcouv/roslyn,dpoeschl/roslyn,robinsedlaczek/roslyn,zooba/roslyn,MattWindsor91/roslyn,jhendrixMSFT/roslyn,yeaicc/roslyn,orthoxerox/roslyn,mattwar/roslyn,bkoelman/roslyn,weltkante/roslyn,ericfe-ms/roslyn,shyamnamboodiripad/roslyn,paulvanbrenk/roslyn,cston/roslyn,genlu/roslyn,tmeschter/roslyn,mattwar/roslyn,mmitche/roslyn,robinsedlaczek/roslyn,tannergooding/roslyn,vslsnap/roslyn,KiloBravoLima/roslyn,Pvlerick/roslyn,amcasey/roslyn,khyperia/roslyn,nguerrera/roslyn,ljw1004/roslyn,drognanar/roslyn,mgoertz-msft/roslyn,CaptainHayashi/roslyn,ErikSchierboom/roslyn,agocke/roslyn,pdelvo/roslyn,budcribar/roslyn,mattscheffer/roslyn,jamesqo/roslyn,jmarolf/roslyn,tvand7093/roslyn,srivatsn/roslyn,ErikSchierboom/roslyn,ljw1004/roslyn,jkotas/roslyn,kelltrick/roslyn,tvand7093/roslyn,xasx/roslyn,drognanar/roslyn,jeffanders/roslyn,MattWindsor91/roslyn,AlekseyTs/roslyn,cston/roslyn,CaptainHayashi/roslyn,DustinCampbell/roslyn,KirillOsenkov/roslyn,bbarry/roslyn,jeffanders/roslyn,akrisiun/roslyn,a-ctor/roslyn,mavasani/roslyn,tmat/roslyn,orthoxerox/roslyn,KirillOsenkov/roslyn,abock/roslyn,diryboy/roslyn
|
src/VisualStudio/Setup/AssemblyRedirects.cs
|
src/VisualStudio/Setup/AssemblyRedirects.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell;
using Roslyn.VisualStudio.Setup;
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.EditorFeatures.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.Features.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.Workspaces.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.EditorFeatures.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.EditorFeatures.Text.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Features.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.Features.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Workspaces.Desktop.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Workspaces.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.Implementation.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.VisualBasic.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.CSharp.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.SolutionExplorer.dll")]
[assembly: ProvideBindingRedirection(
AssemblyName = "System.Reflection.Metadata",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "1.2.0.0",
NewVersion = "1.3.0.0",
PublicKeyToken = "b03f5f7f11d50a3a",
GenerateCodeBase = true)]
[assembly: ProvideBindingRedirection(
AssemblyName = "System.Collections.Immutable",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "1.2.0.0",
NewVersion = "1.2.0.0",
PublicKeyToken = "b03f5f7f11d50a3a",
GenerateCodeBase = true)]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Esent.Interop.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Microsoft.CodeAnalysis.Elfie.dll")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.DiaSymReader",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "1.0.7.0",
NewVersion = "1.0.8.0",
PublicKeyToken = "31bf3856ad364e35",
GenerateCodeBase = true)]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.Convention.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.Hosting.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.TypedParts.dll")]
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell;
using Roslyn.VisualStudio.Setup;
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.EditorFeatures.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.Features.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.CSharp.Workspaces.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.EditorFeatures.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.EditorFeatures.Text.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Features.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.Features.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Workspaces.Desktop.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.CodeAnalysis.Workspaces.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.Implementation.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.VisualBasic.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.CSharp.dll")]
[assembly: ProvideRoslynBindingRedirection("Microsoft.VisualStudio.LanguageServices.SolutionExplorer.dll")]
[assembly: ProvideBindingRedirection(
AssemblyName = "System.Reflection.Metadata",
OldVersionLowerBound = "1.0.0.0",
OldVersionUpperBound = "1.2.0.0",
NewVersion = "1.2.0.0",
PublicKeyToken = "b03f5f7f11d50a3a",
GenerateCodeBase = true)]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Esent.Interop.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Microsoft.CodeAnalysis.Elfie.dll")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.DiaSymReader",
OldVersionLowerBound = "1.0.0.0",
OldVersionUpperBound = "1.0.7.0",
NewVersion = "1.0.7.0",
PublicKeyToken = "31bf3856ad364e35",
GenerateCodeBase = true)]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.Convention.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.Hosting.dll")]
[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.TypedParts.dll")]
|
mit
|
C#
|
fec14977533f862213401bd915683bd44e416208
|
handle the 404 error - for angular routes
|
krzyhook/aspnet-core-angular2-starter,krzyhook/aspnet-core-angular2-starter,krzyhook/aspnet-core-angular2-starter,krzyhook/aspnet-core-angular2-starter
|
src/aspnet-core-angular2-starter/Startup.cs
|
src/aspnet-core-angular2-starter/Startup.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AspNetCoreAngular2Starter
{
public class Startup
{
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// support the Routing of Angular2. If the Browser calls a URL which doesn't exists on the server, it could be a Angular route. Especially if the URL doesn't contain a file extension.
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404
&& !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AspNetCoreAngular2Starter
{
public class Startup
{
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
}
}
|
mit
|
C#
|
071c98f12d6c93ebba0f33835df910ac05ce751c
|
Change version to 1.8
|
Seddryck/NBi,Seddryck/NBi
|
AssemblyInfo.cs
|
AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
// 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: AssemblyCompany("NBi Team - Cédric L. Charlier")]
[assembly: AssemblyProduct("NBi")]
[assembly: AssemblyCopyright("Copyright © Cédric L. Charlier 2012-2014")]
[assembly: AssemblyDescription("NBi is a testing framework (add-on to NUnit) for Microsoft Business Intelligence platform and Data Access. The main goal of this framework is to let users create tests with a declarative approach based on an Xml syntax. By the means of NBi, you don't need to develop C# code to specify your tests! Either, you don't need Visual Studio to compile your test suite. Just create an Xml file and let the framework interpret it and play your tests. The framework is designed as an add-on of NUnit but with the possibility to port it easily to other testing frameworks.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//Reference the testing class to ensure access to internal members
[assembly: InternalsVisibleTo("NBi.Testing")]
// 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.8.0.*")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
// 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: AssemblyCompany("NBi Team - Cédric L. Charlier")]
[assembly: AssemblyProduct("NBi")]
[assembly: AssemblyCopyright("Copyright © Cédric L. Charlier 2012-2014")]
[assembly: AssemblyDescription("NBi is a testing framework (add-on to NUnit) for Microsoft Business Intelligence platform and Data Access. The main goal of this framework is to let users create tests with a declarative approach based on an Xml syntax. By the means of NBi, you don't need to develop C# code to specify your tests! Either, you don't need Visual Studio to compile your test suite. Just create an Xml file and let the framework interpret it and play your tests. The framework is designed as an add-on of NUnit but with the possibility to port it easily to other testing frameworks.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//Reference the testing class to ensure access to internal members
[assembly: InternalsVisibleTo("NBi.Testing")]
// 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.7.0.*")]
|
apache-2.0
|
C#
|
2203465c2f43187d1be43a1c61d554ea67f94ede
|
Refactor away property setter usages to allow Color to be immutable.
|
dotless/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,dotless/dotless
|
src/dotless.Core/Plugins/ColorSpinPlugin.cs
|
src/dotless.Core/Plugins/ColorSpinPlugin.cs
|
namespace dotless.Core.Plugins
{
using Parser.Infrastructure.Nodes;
using Parser.Tree;
using Utils;
using System.ComponentModel;
[Description("Automatically spins all colors in a less file"), DisplayName("ColorSpin")]
public class ColorSpinPlugin : VisitorPlugin
{
public double Spin { get; set; }
public ColorSpinPlugin(double spin)
{
Spin = spin;
}
public override VisitorPluginType AppliesTo
{
get { return VisitorPluginType.AfterEvaluation; }
}
public override Node Execute(Node node, out bool visitDeeper)
{
visitDeeper = true;
var color = node as Color;
if (color == null) return node;
var hslColor = HslColor.FromRgbColor(color);
hslColor.Hue += Spin/360.0d;
var newColor = hslColor.ToRgbColor();
return newColor.ReducedFrom<Color>(color);
}
}
}
|
namespace dotless.Core.Plugins
{
using System;
using Parser.Infrastructure.Nodes;
using Parser.Tree;
using Utils;
using System.ComponentModel;
[Description("Automatically spins all colors in a less file"), DisplayName("ColorSpin")]
public class ColorSpinPlugin : VisitorPlugin
{
public double Spin { get; set; }
public ColorSpinPlugin(double spin)
{
Spin = spin;
}
public override VisitorPluginType AppliesTo
{
get { return VisitorPluginType.AfterEvaluation; }
}
public override Node Execute(Node node, out bool visitDeeper)
{
visitDeeper = true;
if(node is Color)
{
var color = node as Color;
var hslColor = HslColor.FromRgbColor(color);
hslColor.Hue += Spin/360.0d;
var newColor = hslColor.ToRgbColor();
//node = new Color(newColor.R, newColor.G, newColor.B);
color.R = newColor.R;
color.G = newColor.G;
color.B = newColor.B;
}
return node;
}
}
}
|
apache-2.0
|
C#
|
75f04f6f93b31431fc396cd299738f2907a99dc2
|
Add [HideInInspector] to isCustomProfile
|
killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
|
Assets/MixedRealityToolkit/Definitions/BaseMixedRealityProfile.cs
|
Assets/MixedRealityToolkit/Definitions/BaseMixedRealityProfile.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit
{
public abstract class BaseMixedRealityProfile : ScriptableObject
{
[SerializeField]
[HideInInspector]
private bool isCustomProfile = true;
internal bool IsCustomProfile => isCustomProfile;
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit
{
public abstract class BaseMixedRealityProfile : ScriptableObject
{
[SerializeField]
private bool isCustomProfile = true;
internal bool IsCustomProfile => isCustomProfile;
}
}
|
mit
|
C#
|
c7e8221b15578596ff16881555155286bd790118
|
Update dll version for storage
|
naveedaz/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,atpham256/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,atpham256/azure-powershell,atpham256/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,atpham256/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell
|
src/Storage/Commands.Storage/Properties/AssemblyInfo.cs
|
src/Storage/Commands.Storage/Properties/AssemblyInfo.cs
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
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("Microsoft Azure Powershell")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
// 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("a102cbe8-8a50-43b1-821d-72b42b9831a4")]
// 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("3.0.1")]
[assembly: AssemblyFileVersion("3.0.1")]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test")]
#endif
[assembly: CLSCompliant(false)]
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
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("Microsoft Azure Powershell")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
// 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("a102cbe8-8a50-43b1-821d-72b42b9831a4")]
// 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("3.0.0")]
[assembly: AssemblyFileVersion("3.0.0")]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test")]
#endif
[assembly: CLSCompliant(false)]
|
apache-2.0
|
C#
|
62c28f41feed8818c31de6c69a79b1b419f60a1d
|
Fix event lookup
|
l8s/Eto,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto
|
Source/Eto/EventLookup.cs
|
Source/Eto/EventLookup.cs
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace Eto
{
static class EventLookup
{
static readonly Dictionary<Type, List<EventDeclaration>> registeredEvents = new Dictionary<Type, List<EventDeclaration>>();
static readonly Assembly etoAssembly = typeof(EventLookup).Assembly;
static readonly Dictionary<Type, string[]> externalEvents = new Dictionary<Type, string[]>();
struct EventDeclaration
{
public readonly string Identifier;
public readonly string MethodName;
public readonly Type Type;
public EventDeclaration(Type type, string methodName, string identifier)
{
Type = type;
MethodName = methodName;
Identifier = identifier;
}
}
public static void Register(Type type, string methodName, string identifier)
{
var declarations = GetDeclarations(type);
declarations.Add(new EventDeclaration(type, methodName, identifier));
}
public static void HookupEvents(InstanceWidget widget)
{
var type = widget.GetType();
if (type.Assembly == etoAssembly)
return;
widget.HandleEvents(GetEvents(type));
}
static string[] GetEvents(Type type)
{
string[] events;
if (!externalEvents.TryGetValue(type, out events))
{
events = FindTypeEvents(type).ToArray();
externalEvents.Add(type, events);
}
return events;
}
static IEnumerable<string> FindTypeEvents(Type type)
{
var externalTypes = new List<Type>();
var current = type;
while (current != null)
{
if (current.Assembly == etoAssembly)
{
List<EventDeclaration> declarations;
if (registeredEvents.TryGetValue(current, out declarations))
{
foreach (var item in declarations)
{
foreach (var externalType in externalTypes)
{
var method = externalType.GetMethod(item.MethodName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (method != null)
{
var baseMethod = method.GetBaseDefinition();
if (baseMethod != null && baseMethod.DeclaringType == item.Type)
yield return item.Identifier;
}
}
}
}
}
else
externalTypes.Add(current);
current = current.BaseType;
}
}
static List<EventDeclaration> GetDeclarations(Type type)
{
List<EventDeclaration> declarations;
if (!registeredEvents.TryGetValue(type, out declarations))
{
declarations = new List<EventDeclaration>();
registeredEvents.Add(type, declarations);
}
return declarations;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace Eto
{
static class EventLookup
{
static readonly Dictionary<Type, List<EventDeclaration>> registeredEvents = new Dictionary<Type, List<EventDeclaration>>();
static readonly Assembly etoAssembly = typeof(EventLookup).Assembly;
static readonly Dictionary<Type, string[]> externalEvents = new Dictionary<Type, string[]>();
struct EventDeclaration
{
public readonly string Identifier;
public readonly string MethodName;
public readonly Type Type;
public EventDeclaration(Type type, string methodName, string identifier)
{
Type = type;
MethodName = methodName;
Identifier = identifier;
}
}
public static void Register(Type type, string methodName, string identifier)
{
var declarations = GetDeclarations(type);
declarations.Add(new EventDeclaration(type, identifier, methodName));
}
public static void HookupEvents(InstanceWidget widget)
{
var type = widget.GetType();
if (type.Assembly == etoAssembly)
return;
widget.HandleEvents(GetEvents(type));
}
static string[] GetEvents(Type type)
{
string[] events;
if (!externalEvents.TryGetValue(type, out events))
{
events = FindTypeEvents(type).ToArray();
externalEvents.Add(type, events);
}
return events;
}
static IEnumerable<string> FindTypeEvents(Type type)
{
var externalTypes = new List<Type>();
var current = type;
while (current != null)
{
if (current.Assembly == etoAssembly)
{
List<EventDeclaration> declarations;
if (registeredEvents.TryGetValue(current, out declarations))
{
foreach (var item in declarations)
{
foreach (var externalType in externalTypes)
{
var method = externalType.GetMethod(item.MethodName, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (method != null)
{
var baseMethod = method.GetBaseDefinition();
if (baseMethod != null && baseMethod.DeclaringType == item.Type)
yield return item.Identifier;
}
}
}
}
}
else
externalTypes.Add(current);
current = current.BaseType;
}
}
static List<EventDeclaration> GetDeclarations(Type type)
{
List<EventDeclaration> declarations;
if (!registeredEvents.TryGetValue(type, out declarations))
{
declarations = new List<EventDeclaration>();
registeredEvents.Add(type, declarations);
}
return declarations;
}
}
}
|
bsd-3-clause
|
C#
|
b26b9ae3630710c1a02c361f05dd7003176d7cea
|
Update Tests/AssemblyLocation.cs
|
SimonCropp/CaptureSnippets
|
Tests/AssemblyLocation.cs
|
Tests/AssemblyLocation.cs
|
using System.IO;
public static class AssemblyLocation
{
static AssemblyLocation()
{
var assembly = typeof(AssemblyLocation).Assembly;
var path = assembly.CodeBase
.Replace("file:///", "")
.Replace("file://", "")
.Replace(@"file:\\\", "")
.Replace(@"file:\\", "");
CurrentDirectory = Path.GetDirectoryName(path);
}
public static string CurrentDirectory;
}
|
using System.IO;
public static class AssemblyLocation
{
static AssemblyLocation()
{
var assembly = typeof(AssemblyLocation).Assembly;
var path = assembly.CodeBase
.Replace("file:///", "")
.Replace("file://", "")
.Replace(@"file:\\\", "")
.Replace(@"file:\\", "");
CurrentDirectory = Path.GetDirectoryName(path);
}
public static string CurrentDirectory;
}
|
mit
|
C#
|
b4f191cd47e2111278f624233a9e46b7cfae6bbd
|
Add Func`3 doc
|
AMDL/CommonMark.NET,AMDL/CommonMark.NET
|
CommonMark/Func.cs
|
CommonMark/Func.cs
|
using System;
namespace CommonMark
{
#if v2_0
/// <summary>An alternative to <c>System.Func</c> which is not present in .NET 2.0.</summary>
public delegate TResult Func<in T, out TResult>(T arg);
/// <summary>An alternative to <c>System.Func</c> which is not present in .NET 2.0.</summary>
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
/// <summary>An alternative to <c>System.Action</c> which is not present in .NET 2.0.</summary>
public delegate void Action<in T1, in T2, in T3>(T1 arg1, T2 arg2, T3 arg3);
#endif
}
|
using System;
namespace CommonMark
{
#if v2_0
/// <summary>An alternative to <c>System.Func</c> which is not present in .NET 2.0.</summary>
public delegate TResult Func<in T, out TResult>(T arg);
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
/// <summary>An alternative to <c>System.Action</c> which is not present in .NET 2.0.</summary>
public delegate void Action<in T1, in T2, in T3>(T1 arg1, T2 arg2, T3 arg3);
#endif
}
|
bsd-3-clause
|
C#
|
5a5037b4cf609b2e25935021411d8895a675fbe6
|
use var
|
pardeike/Harmony
|
HarmonyTests/IL/Instructions.cs
|
HarmonyTests/IL/Instructions.cs
|
using Harmony;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection.Emit;
namespace HarmonyTests.IL
{
[TestClass]
public class Instructions
{
[TestMethod]
public void TestMalformedStringOperand()
{
var expectedOperand = "this should not fail {4}";
var inst = new CodeInstruction(OpCodes.Ldstr, expectedOperand);
Assert.AreEqual($"ldstr \"{expectedOperand}\"", inst.ToString());
}
}
}
|
using Harmony;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection.Emit;
namespace HarmonyTests.IL
{
[TestClass]
public class Instructions
{
[TestMethod]
public void TestMalformedStringOperand()
{
string expectedOperand = "this should not fail {4}";
var inst = new CodeInstruction(OpCodes.Ldstr, expectedOperand);
Assert.AreEqual($"ldstr \"{expectedOperand}\"", inst.ToString());
}
}
}
|
mit
|
C#
|
090808d3c1de878382bea5ed7e27304e67721e49
|
Refactor UnblindedSignature class
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi/Crypto/UnblindedSignature.cs
|
WalletWasabi/Crypto/UnblindedSignature.cs
|
using System;
using NBitcoin.DataEncoders;
using NBitcoin.Secp256k1;
namespace WalletWasabi.Crypto
{
#nullable enable
public class UnblindedSignature
{
internal UnblindedSignature(in Scalar c, in Scalar s)
{
C = c;
S = s;
}
internal Scalar C { get; }
internal Scalar S { get; }
public static bool TryParse(ReadOnlySpan<byte> in64, out UnblindedSignature? unblindedSignature)
{
unblindedSignature = null;
if (in64.Length != 64)
{
return false;
}
var c = new Scalar(in64.Slice(0, 32), out int overflow);
if (c.IsZero || overflow != 0)
{
return false;
}
var s = new Scalar(in64.Slice(32, 32), out overflow);
if (s.IsZero || overflow != 0)
{
return false;
}
unblindedSignature = new UnblindedSignature(c, s);
return true;
}
public static UnblindedSignature Parse(ReadOnlySpan<byte> in64)
{
if (TryParse(in64, out var unblindedSignature) && unblindedSignature is UnblindedSignature)
{
return unblindedSignature;
}
throw new FormatException("Invalid unblinded signature");
}
public static UnblindedSignature Parse(string str)
{
if (TryParse(str, out var unblindedSignature) && unblindedSignature is UnblindedSignature)
{
return unblindedSignature;
}
throw new FormatException("Invalid unblinded signature");
}
public static bool TryParse(string str, out UnblindedSignature? unblindedSignature)
{
unblindedSignature = null;
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (!HexEncoder.IsWellFormed(str))
{
return false;
}
return TryParse(Encoders.Hex.DecodeData(str), out unblindedSignature);
}
public byte[] ToBytes()
{
var result = new byte[64];
ToBytes(result.AsSpan());
return result;
}
public void ToBytes(Span<byte> out64)
{
if (out64.Length != 64)
{
throw new ArgumentException(paramName: nameof(out64), message: "out64 must be 64 bytes");
}
C.WriteToSpan(out64.Slice(0, 32));
S.WriteToSpan(out64.Slice(32, 32));
}
public override string ToString()
{
Span<byte> tmp = stackalloc byte[64];
ToBytes(tmp);
return Encoders.Hex.EncodeData(tmp);
}
}
}
|
using System;
using NBitcoin.DataEncoders;
using NBitcoin.Secp256k1;
namespace WalletWasabi.Crypto
{
#nullable enable
public class UnblindedSignature
{
internal Scalar C { get; }
internal Scalar S { get; }
internal UnblindedSignature(in Scalar c, in Scalar s)
{
C = c;
S = s;
}
public static bool TryParse(ReadOnlySpan<byte> in64, out UnblindedSignature? unblindedSignature)
{
int overflow;
unblindedSignature = null;
if (in64.Length != 64)
return false;
var c = new Scalar(in64.Slice(0, 32), out overflow);
if (c.IsZero || overflow != 0)
return false;
var s = new Scalar(in64.Slice(32, 32), out overflow);
if (s.IsZero || overflow != 0)
return false;
unblindedSignature = new UnblindedSignature(c, s);
return true;
}
public static UnblindedSignature Parse(ReadOnlySpan<byte> in64)
{
if (TryParse(in64, out var unblindedSignature) && unblindedSignature is UnblindedSignature)
return unblindedSignature;
throw new FormatException("Invalid unblinded signature");
}
public static UnblindedSignature Parse(string str)
{
if (TryParse(str, out var unblindedSignature) && unblindedSignature is UnblindedSignature)
return unblindedSignature;
throw new FormatException("Invalid unblinded signature");
}
public static bool TryParse(string str, out UnblindedSignature? unblindedSignature)
{
unblindedSignature = null;
if (str == null)
throw new ArgumentNullException(nameof(str));
if (!HexEncoder.IsWellFormed(str))
return false;
return TryParse(Encoders.Hex.DecodeData(str), out unblindedSignature);
}
public byte[] ToBytes()
{
var result = new byte[64];
ToBytes(result.AsSpan());
return result;
}
public void ToBytes(Span<byte> out64)
{
if (out64.Length != 64)
throw new ArgumentException(paramName: nameof(out64), message: "out64 must be 64 bytes");
C.WriteToSpan(out64.Slice(0, 32));
S.WriteToSpan(out64.Slice(32, 32));
}
public override string ToString()
{
Span<byte> tmp = stackalloc byte[64];
ToBytes(tmp);
return Encoders.Hex.EncodeData(tmp);
}
}
}
|
mit
|
C#
|
5b3ee1de430b3fd5781fec356b1b73fef4245f6a
|
Update RemovingWorksheetsUsingSheetName.cs
|
aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET
|
Examples/CSharp/Worksheets/Management/RemovingWorksheetsUsingSheetName.cs
|
Examples/CSharp/Worksheets/Management/RemovingWorksheetsUsingSheetName.cs
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Management
{
public class RemovingWorksheetsUsingSheetName
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Removing a worksheet using its sheet name
workbook.Worksheets.RemoveAt("Sheet1");
//Save workbook
workbook.Save(dataDir + "output.out.xls");
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Management
{
public class RemovingWorksheetsUsingSheetName
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Removing a worksheet using its sheet name
workbook.Worksheets.RemoveAt("Sheet1");
//Save workbook
workbook.Save(dataDir + "output.out.xls");
}
}
}
|
mit
|
C#
|
de22589499de4462c1bd194bc927a92e7fa8504a
|
Add UNITY_EDITOR_LINUX check in Packsize
|
rlabrecque/Steamworks.NET,rlabrecque/Steamworks.NET,rlabrecque/Steamworks.NET,rlabrecque/Steamworks.NET
|
com.rlabrecque.steamworks.net/Runtime/Packsize.cs
|
com.rlabrecque.steamworks.net/Runtime/Packsize.cs
|
// This file is provided under The MIT License as part of Steamworks.NET.
// Copyright (c) 2013-2022 Riley Labrecque
// Please see the included LICENSE.txt for additional information.
// This file is automatically generated.
// Changes to this file will be reverted when you update Steamworks.NET
#if !(UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_WIN || STEAMWORKS_LIN_OSX)
#define DISABLESTEAMWORKS
#endif
#if !DISABLESTEAMWORKS
// If we're running in the Unity Editor we need the editors platform.
#if UNITY_EDITOR_WIN
#define VALVE_CALLBACK_PACK_LARGE
#elif UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX
#define VALVE_CALLBACK_PACK_SMALL
// Otherwise we want the target platform.
#elif UNITY_STANDALONE_WIN || STEAMWORKS_WIN
#define VALVE_CALLBACK_PACK_LARGE
#elif UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_LIN_OSX
#define VALVE_CALLBACK_PACK_SMALL
// We do not want to throw a warning when we're building in Unity but for an unsupported platform. So we'll silently let this slip by.
// It would be nice if Unity itself would define 'UNITY' or something like that...
#elif UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_2017_1_OR_NEWER
#define VALVE_CALLBACK_PACK_SMALL
// But we do want to be explicit on the Standalone build for XNA/Monogame.
#else
#define VALVE_CALLBACK_PACK_LARGE
#warning You need to define STEAMWORKS_WIN, or STEAMWORKS_LIN_OSX. Refer to the readme for more details.
#endif
using System.Runtime.InteropServices;
using IntPtr = System.IntPtr;
namespace Steamworks {
public static class Packsize {
#if VALVE_CALLBACK_PACK_LARGE
public const int value = 8;
#elif VALVE_CALLBACK_PACK_SMALL
public const int value = 4;
#endif
public static bool Test() {
int sentinelSize = Marshal.SizeOf(typeof(ValvePackingSentinel_t));
int subscribedFilesSize = Marshal.SizeOf(typeof(RemoteStorageEnumerateUserSubscribedFilesResult_t));
#if VALVE_CALLBACK_PACK_LARGE
if (sentinelSize != 32 || subscribedFilesSize != (1 + 1 + 1 + 50 + 100) * 4 + 4)
return false;
#elif VALVE_CALLBACK_PACK_SMALL
if (sentinelSize != 24 || subscribedFilesSize != (1 + 1 + 1 + 50 + 100) * 4)
return false;
#endif
return true;
}
[StructLayout(LayoutKind.Sequential, Pack = Packsize.value)]
struct ValvePackingSentinel_t {
uint m_u32;
ulong m_u64;
ushort m_u16;
double m_d;
};
}
}
#endif // !DISABLESTEAMWORKS
|
// This file is provided under The MIT License as part of Steamworks.NET.
// Copyright (c) 2013-2022 Riley Labrecque
// Please see the included LICENSE.txt for additional information.
// This file is automatically generated.
// Changes to this file will be reverted when you update Steamworks.NET
#if !(UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_WIN || STEAMWORKS_LIN_OSX)
#define DISABLESTEAMWORKS
#endif
#if !DISABLESTEAMWORKS
// If we're running in the Unity Editor we need the editors platform.
#if UNITY_EDITOR_WIN
#define VALVE_CALLBACK_PACK_LARGE
#elif UNITY_EDITOR_OSX
#define VALVE_CALLBACK_PACK_SMALL
// Otherwise we want the target platform.
#elif UNITY_STANDALONE_WIN || STEAMWORKS_WIN
#define VALVE_CALLBACK_PACK_LARGE
#elif UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_LIN_OSX
#define VALVE_CALLBACK_PACK_SMALL
// We do not want to throw a warning when we're building in Unity but for an unsupported platform. So we'll silently let this slip by.
// It would be nice if Unity itself would define 'UNITY' or something like that...
#elif UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_2017_1_OR_NEWER
#define VALVE_CALLBACK_PACK_SMALL
// But we do want to be explicit on the Standalone build for XNA/Monogame.
#else
#define VALVE_CALLBACK_PACK_LARGE
#warning You need to define STEAMWORKS_WIN, or STEAMWORKS_LIN_OSX. Refer to the readme for more details.
#endif
using System.Runtime.InteropServices;
using IntPtr = System.IntPtr;
namespace Steamworks {
public static class Packsize {
#if VALVE_CALLBACK_PACK_LARGE
public const int value = 8;
#elif VALVE_CALLBACK_PACK_SMALL
public const int value = 4;
#endif
public static bool Test() {
int sentinelSize = Marshal.SizeOf(typeof(ValvePackingSentinel_t));
int subscribedFilesSize = Marshal.SizeOf(typeof(RemoteStorageEnumerateUserSubscribedFilesResult_t));
#if VALVE_CALLBACK_PACK_LARGE
if (sentinelSize != 32 || subscribedFilesSize != (1 + 1 + 1 + 50 + 100) * 4 + 4)
return false;
#elif VALVE_CALLBACK_PACK_SMALL
if (sentinelSize != 24 || subscribedFilesSize != (1 + 1 + 1 + 50 + 100) * 4)
return false;
#endif
return true;
}
[StructLayout(LayoutKind.Sequential, Pack = Packsize.value)]
struct ValvePackingSentinel_t {
uint m_u32;
ulong m_u64;
ushort m_u16;
double m_d;
};
}
}
#endif // !DISABLESTEAMWORKS
|
mit
|
C#
|
85a4b2188881aaea531757bbb19f2684aa7bff40
|
Add support of Patch Creator 1.0.0.9
|
dsolovay/Sitecore-Instance-Manager,Sitecore/Sitecore-Instance-Manager,sergeyshushlyapin/Sitecore-Instance-Manager,Brad-Christie/Sitecore-Instance-Manager
|
src/SIM.Tool.Windows/MainWindowComponents/CreateSupportPatchButton.cs
|
src/SIM.Tool.Windows/MainWindowComponents/CreateSupportPatchButton.cs
|
namespace SIM.Tool.Windows.MainWindowComponents
{
using System;
using System.IO;
using System.Windows;
using Sitecore.Diagnostics.Base;
using Sitecore.Diagnostics.Base.Annotations;
using SIM.Core;
using SIM.Instances;
using SIM.Tool.Base;
using SIM.Tool.Base.Plugins;
[UsedImplicitly]
public class CreateSupportPatchButton : IMainWindowButton
{
#region Public methods
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
if (instance == null)
{
WindowHelper.ShowMessage("Choose an instance first");
return;
}
var product = instance.Product;
Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first.");
var version = product.Version + "." + product.Update;
var args = new[]
{
version,
instance.Name,
instance.WebRootPath
};
var dir = Environment.ExpandEnvironmentVariables("%APPDATA%\\Sitecore\\CreatePatch");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllLines(Path.Combine(dir, "args.txt"), args);
CoreApp.RunApp("iexplore", $"http://dl.sitecore.net/updater/pc/CreatePatch.application");
NuGetHelper.UpdateSettings();
NuGetHelper.GeneratePackages(new FileInfo(product.PackagePath));
foreach (var module in instance.Modules)
{
NuGetHelper.GeneratePackages(new FileInfo(module.PackagePath));
}
}
#endregion
}
}
|
namespace SIM.Tool.Windows.MainWindowComponents
{
using System.IO;
using System.Windows;
using Sitecore.Diagnostics.Base;
using Sitecore.Diagnostics.Base.Annotations;
using SIM.Core;
using SIM.Instances;
using SIM.Tool.Base;
using SIM.Tool.Base.Plugins;
[UsedImplicitly]
public class CreateSupportPatchButton : IMainWindowButton
{
#region Public methods
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
if (instance == null)
{
WindowHelper.ShowMessage("Choose an instance first");
return;
}
var product = instance.Product;
Assert.IsNotNull(product, $"The {instance.ProductFullName} distributive is not available in local repository. You need to get it first.");
var version = product.Version + "." + product.Update;
CoreApp.RunApp("iexplore", $"http://dl.sitecore.net/updater/pc/CreatePatch.application?p1={version}&p2={instance.Name}&p3={instance.WebRootPath}");
NuGetHelper.UpdateSettings();
NuGetHelper.GeneratePackages(new FileInfo(product.PackagePath));
foreach (var module in instance.Modules)
{
NuGetHelper.GeneratePackages(new FileInfo(module.PackagePath));
}
}
#endregion
}
}
|
mit
|
C#
|
69c41b953ec2fda7b6393e9bc30f7ac78e283615
|
Fix typo in EntityPostion handler
|
SharpUmbrella/RustInterceptor
|
RustInterceptor/Data/Entity.cs
|
RustInterceptor/Data/Entity.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Rust_Interceptor.Data {
public class Entity {
/* BaseNetworkable */
public uint UID { get { return protobuf.baseNetworkable.uid; } }
public uint Group { get { return protobuf.baseNetworkable.group; } }
public uint PrefabID { get { return protobuf.baseNetworkable.prefabID; } }
/* BaseEntity */
internal uint num = 0;
public uint Number { get { return num; } }
internal ProtoBuf.Entity protobuf;
public ProtoBuf.Entity Protobuf { get { return protobuf; } }
public Vector3 Position { get { return protobuf.baseEntity.pos; } }
public Vector3 Rotation { get { return protobuf.baseEntity.rot; } }
public int Entity_Flags { get { return protobuf.baseEntity.flags; } }
public ulong SkinID { get { return protobuf.baseEntity.skinid; } }
internal BasePlayer player;
public BasePlayer Player { get { return player; } }
public bool IsPlayer { get { return protobuf.basePlayer != null; } }
/* List of all received entities */
internal static Dictionary<uint, Entity> entities = new Dictionary<uint, Entity>();
public static List<Entity> Entities { get { return entities.Values.ToList(); } }
/* List of all received players */
internal static List<Entity> players = new List<Entity>();
public static List<Entity> Players { get { return players; } }
/* Local Player is sent first, so it should be first */
public static Entity LocalPlayer { get { return Players.First(); } }
public static bool CheckEntity(uint id) {
return entities.ContainsKey(id);
}
public static void UpdatePosition(Packet p) {
/* EntityPosition packets may contain multiple positions */
while (p.unread >= 28L) {
/* Entity UID */
var id = p.UInt32();
CheckEntity(id);
/* Read 2 Vector3 in form of 3 floats each, Position and Rotation */
entities[id].protobuf.baseEntity.pos.Set(p.Float(), p.Float(), p.Float());
entities[id].protobuf.baseEntity.rot.Set(p.Float(), p.Float(), p.Float());
}
}
public static uint CreateOrUpdate(Packet p) {
/* Entity Number/Order, for internal use */
var num = p.UInt32();
ProtoBuf.Entity proto = global::ProtoBuf.Entity.Deserialize(p);
/* All Networkables have Unique Identifiers */
var id = proto.baseNetworkable.uid;
if (CheckEntity(id))
entities[id].protobuf = proto;
else {
entities[id] = new Entity(proto);
entities[id].num = num;
}
return id;
}
public Entity(ProtoBuf.Entity proto) {
protobuf = proto;
player = new BasePlayer(proto.basePlayer);
if (IsPlayer) players.Add(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Rust_Interceptor.Data {
public class Entity {
/* BaseNetworkable */
public uint UID { get { return protobuf.baseNetworkable.uid; } }
public uint Group { get { return protobuf.baseNetworkable.group; } }
public uint PrefabID { get { return protobuf.baseNetworkable.prefabID; } }
/* BaseEntity */
internal uint num = 0;
public uint Number { get { return num; } }
internal ProtoBuf.Entity protobuf;
public ProtoBuf.Entity Protobuf { get { return protobuf; } }
public Vector3 Position { get { return protobuf.baseEntity.pos; } }
public Vector3 Rotation { get { return protobuf.baseEntity.rot; } }
public int Entity_Flags { get { return protobuf.baseEntity.flags; } }
public ulong SkinID { get { return protobuf.baseEntity.skinid; } }
internal BasePlayer player;
public BasePlayer Player { get { return player; } }
public bool IsPlayer { get { return protobuf.basePlayer != null; } }
/* List of all received entities */
internal static Dictionary<uint, Entity> entities = new Dictionary<uint, Entity>();
public static List<Entity> Entities { get { return entities.Values.ToList(); } }
/* List of all received players */
internal static List<Entity> players = new List<Entity>();
public static List<Entity> Players { get { return players; } }
/* Local Player is sent first, so it should be first */
public static Entity LocalPlayer { get { return Players.First(); } }
public static bool CheckEntity(uint id) {
return entities.ContainsKey(id);
}
public static void UpdatePosition(Packet p) {
while (p.unread > 28L) {
var id = p.UInt32();
CheckEntity(id);
/* Read 2 Vector3f in form of 3 floats each, Position and Rotation */
entities[id].protobuf.baseEntity.pos.Set(p.Float(), p.Float(), p.Float());
entities[id].protobuf.baseEntity.rot.Set(p.Float(), p.Float(), p.Float());
}
}
public static uint CreateOrUpdate(Packet p) {
/* Entity Number, for internal use */
var num = p.UInt32();
ProtoBuf.Entity proto = global::ProtoBuf.Entity.Deserialize(p);
/* All Networkables have Unique Identifiers */
var id = proto.baseNetworkable.uid;
if (CheckEntity(id))
entities[id].protobuf = proto;
else {
entities[id] = new Entity(proto);
entities[id].num = num;
}
return id;
}
public Entity(ProtoBuf.Entity proto) {
protobuf = proto;
player = new BasePlayer(proto.basePlayer);
if (IsPlayer) players.Add(this);
}
}
}
|
mit
|
C#
|
2b01faf218e99d31e40e481865cdc0aeb11c7a30
|
Disable running on codecov
|
vCipher/Cake.Hg
|
setup.cake
|
setup.cake
|
#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease
Environment.SetVariableNames();
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "Cake.Hg",
repositoryOwner: "cake-contrib",
repositoryName: "Cake.Hg",
appVeyorAccountName: "cakecontrib",
solutionFilePath: "./src/Cake.Hg.sln",
shouldRunCodecov: false,
wyamSourceFiles: "../../src/**/{!bin,!obj,!packages,!*Tests,}/**/*.cs");
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context,
dupFinderExcludePattern: new string[] {
BuildParameters.RootDirectoryPath + "/src/Cake.HgTests/**/*.cs",
BuildParameters.RootDirectoryPath + "/src/Cake.Hg/**/*.AssemblyInfo.cs"
});
Build.Run();
|
#load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease
Environment.SetVariableNames();
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "Cake.Hg",
repositoryOwner: "cake-contrib",
repositoryName: "Cake.Hg",
appVeyorAccountName: "cakecontrib",
solutionFilePath: "./src/Cake.Hg.sln",
wyamSourceFiles: "../../src/**/{!bin,!obj,!packages,!*Tests,}/**/*.cs");
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context,
dupFinderExcludePattern: new string[] {
BuildParameters.RootDirectoryPath + "/src/Cake.HgTests/**/*.cs",
BuildParameters.RootDirectoryPath + "/src/Cake.Hg/**/*.AssemblyInfo.cs"
});
Build.Run();
|
mit
|
C#
|
86da1a96f6d0303b4f2666bd05fbc6d3caf0a13a
|
bump version
|
Fody/Freezable
|
CommonAssemblyInfo.cs
|
CommonAssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Freezable")]
[assembly: AssemblyProduct("Freezable")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Freezable")]
[assembly: AssemblyProduct("Freezable")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
|
mit
|
C#
|
17ad6648d1e837a7a85f57792a9185377b37bd52
|
Fix new test failing on headless runs
|
ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu
|
osu.Game.Tests/Visual/SongSelect/TestSceneDifficultyRangeFilterControl.cs
|
osu.Game.Tests/Visual/SongSelect/TestSceneDifficultyRangeFilterControl.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.
#nullable disable
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Screens.Select;
using osuTK;
namespace osu.Game.Tests.Visual.SongSelect
{
public class TestSceneDifficultyRangeFilterControl : OsuTestScene
{
[Test]
public void TestBasic()
{
AddStep("create control", () =>
{
Child = new DifficultyRangeFilterControl
{
Width = 200,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(3),
};
});
}
}
}
|
// 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.
#nullable disable
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Screens.Select;
using osuTK;
namespace osu.Game.Tests.Visual.SongSelect
{
public class TestSceneDifficultyRangeFilterControl : OsuTestScene
{
[Test]
public void TestBasic()
{
Child = new DifficultyRangeFilterControl
{
Width = 200,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(3),
};
}
}
}
|
mit
|
C#
|
f2c3577463323f7def4c5356fc18cc5fd3e27172
|
Update vuokaavio 3
|
JuusoLo/Programming-basics
|
Conditional-Statements/conditional-statement/loop_example_2/Program.cs
|
Conditional-Statements/conditional-statement/loop_example_2/Program.cs
|
using System;
namespace loop_example_2
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("Ohjelma laskee. Anna luku, mistä summa lasketaan:");
string userInput = Console.ReadLine();
int number = int.Parse(userInput);
//int.TryParse(userInput, out int number);
int i = 0;
int sum = 0;
while (i < number)
{
i = i + 1;
sum = sum + i;
}
Console.WriteLine($"Lukujen summa: {sum}");
Console.ReadKey();
}
}
}
|
using System;
namespace loop_example_2
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("Ohjelma laskee. Anna luku, jonka mistä summa lasketaan:");
string userInput = Console.ReadLine();
int number = int.Parse(userInput);
//int.TryParse(userInput, out int number);
int i = 0;
int sum = 0;
while (i < number)
{
i = i + 1;
sum = sum + i;
}
Console.WriteLine($"Lukujen summa: {sum}");
Console.ReadKey();
}
}
}
|
mit
|
C#
|
a5f866d95ce0a6e97c8620b22266b5bf3f470173
|
Test updates
|
smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,ppy/osu
|
osu.Game.Tests/Visual/Editing/TestSceneTimelineHitObjectBlueprint.cs
|
osu.Game.Tests/Visual/Editing/TestSceneTimelineHitObjectBlueprint.cs
|
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Screens.Edit.Compose.Components.Timeline;
using osuTK;
using osuTK.Input;
using static osu.Game.Screens.Edit.Compose.Components.Timeline.TimelineHitObjectBlueprint;
namespace osu.Game.Tests.Visual.Editing
{
public class TestSceneTimelineHitObjectBlueprint : TimelineTestScene
{
private Spinner spinner;
public TestSceneTimelineHitObjectBlueprint()
{
spinner = new Spinner
{
Position = new Vector2(256, 256),
StartTime = -1000,
EndTime = 2000
};
spinner.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty { CircleSize = 2 });
}
public override Drawable CreateTestComponent() => new TimelineHitObjectBlueprint(spinner);
[Test]
public void TestDisallowZeroLengthSpinners()
{
DragBar dragBar = this.ChildrenOfType<DragBar>().First();
Circle circle = this.ChildrenOfType<Circle>().First();
InputManager.MoveMouseTo(dragBar.ScreenSpaceDrawQuad.TopRight);
AddStep("drag dragbar to hit object", () =>
{
InputManager.PressButton(MouseButton.Left);
InputManager.MoveMouseTo(circle.ScreenSpaceDrawQuad.TopLeft);
InputManager.ReleaseButton(MouseButton.Left);
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Screens.Edit.Compose.Components.Timeline;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
public class TestSceneTimelineHitObjectBlueprint : TimelineTestScene
{
private Spinner spinner;
private TimelineHitObjectBlueprint blueprint;
public TestSceneTimelineHitObjectBlueprint()
{
var spinner = new Spinner
{
Position = new Vector2(256, 256),
StartTime = -1000,
EndTime = 2000
};
spinner.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty { CircleSize = 2 });
Add(new Container
{
RelativeSizeAxes = Axes.Both,
Size = new Vector2(0.5f),
Child = _ = new DrawableSpinner(spinner)
});
}
protected override void LoadComplete()
{
base.LoadComplete();
Clock.Seek(10000);
}
public override Drawable CreateTestComponent() => blueprint = new TimelineHitObjectBlueprint(spinner);
[Test]
public void TestDisallowZeroLengthSpinners()
{
}
}
}
|
mit
|
C#
|
477e45365d09f11ff6df8ffccef15618f6d9e91f
|
Allow only Tor endpoints (#673)
|
NicolasDorier/NBitcoin,MetacoSA/NBitcoin,MetacoSA/NBitcoin
|
NBitcoin/Protocol/Connectors/DefaultEndpointConnector.cs
|
NBitcoin/Protocol/Connectors/DefaultEndpointConnector.cs
|
#if !NOSOCKET
using NBitcoin.Protocol.Behaviors;
using NBitcoin.Socks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NBitcoin.Protocol.Connectors
{
public class DefaultEndpointConnector : IEnpointConnector
{
/// <summary>
/// If it must connect to TOR only (default: false)
/// </summary>
public bool AllowOnlyTorEndpoints { get; set; } = false;
public DefaultEndpointConnector()
{
}
public DefaultEndpointConnector(bool allowOnlyTorEndpoints)
{
AllowOnlyTorEndpoints = allowOnlyTorEndpoints;
}
public IEnpointConnector Clone()
{
return new DefaultEndpointConnector(AllowOnlyTorEndpoints);
}
public async Task ConnectSocket(Socket socket, EndPoint endpoint, NodeConnectionParameters nodeConnectionParameters, CancellationToken cancellationToken)
{
var isTor = endpoint.IsTor();
if(AllowOnlyTorEndpoints && !isTor)
throw new InvalidOperationException($"The Endpoint connector is configured to allow only Tor endpoints and the '{endpoint}' enpoint is not one");
var socksSettings = nodeConnectionParameters.TemplateBehaviors.Find<SocksSettingsBehavior>();
bool socks = isTor || socksSettings?.OnlyForOnionHosts is false;
if (socks && socksSettings?.SocksEndpoint == null)
throw new InvalidOperationException("SocksSettingsBehavior.SocksEndpoint is not set but the connection is expecting using socks proxy");
var socketEndpoint = socks ? socksSettings.SocksEndpoint : endpoint;
if (socketEndpoint is IPEndPoint mappedv4 && mappedv4.Address.IsIPv4MappedToIPv6Ex())
socketEndpoint = new IPEndPoint(mappedv4.Address.MapToIPv4Ex(), mappedv4.Port);
#if NETCORE
await socket.ConnectAsync(socketEndpoint).WithCancellation(cancellationToken).ConfigureAwait(false);
#else
await socket.ConnectAsync(socketEndpoint, cancellationToken).ConfigureAwait(false);
#endif
if (!socks)
return;
await SocksHelper.Handshake(socket, endpoint, cancellationToken);
}
}
}
#endif
|
#if !NOSOCKET
using NBitcoin.Protocol.Behaviors;
using NBitcoin.Socks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NBitcoin.Protocol.Connectors
{
public class DefaultEndpointConnector : IEnpointConnector
{
public DefaultEndpointConnector()
{
}
public IEnpointConnector Clone()
{
return new DefaultEndpointConnector();
}
public async Task ConnectSocket(Socket socket, EndPoint endpoint, NodeConnectionParameters nodeConnectionParameters, CancellationToken cancellationToken)
{
var socksSettings = nodeConnectionParameters.TemplateBehaviors.Find<SocksSettingsBehavior>();
bool socks = endpoint.IsTor() || socksSettings?.OnlyForOnionHosts is false;
if (socks && socksSettings?.SocksEndpoint == null)
throw new InvalidOperationException("SocksSettingsBehavior.SocksEndpoint is not set but the connection is expecting using socks proxy");
var socketEndpoint = socks ? socksSettings.SocksEndpoint : endpoint;
if (socketEndpoint is IPEndPoint mappedv4 && mappedv4.Address.IsIPv4MappedToIPv6Ex())
socketEndpoint = new IPEndPoint(mappedv4.Address.MapToIPv4Ex(), mappedv4.Port);
#if NETCORE
await socket.ConnectAsync(socketEndpoint).WithCancellation(cancellationToken).ConfigureAwait(false);
#else
await socket.ConnectAsync(socketEndpoint, cancellationToken).ConfigureAwait(false);
#endif
if (!socks)
return;
await SocksHelper.Handshake(socket, endpoint, cancellationToken);
}
}
}
#endif
|
mit
|
C#
|
6c6b13db945fbd350fdcf82062bde5017bd5c073
|
Use Index initializers
|
ms-iot/UniversalMediaEngine
|
samples/speechSynthesisSample/speechSynthesisSample/MainPage.xaml.cs
|
samples/speechSynthesisSample/speechSynthesisSample/MainPage.xaml.cs
|
using Microsoft.Maker.Media.UniversalMediaEngine;
using System;
using System.Diagnostics;
using Windows.Media.SpeechSynthesis;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace speechSynthesisSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private MediaEngine mediaEngine= new MediaEngine();
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");
mediaEngine.PlayStream(stream);
}
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
var result = await mediaEngine.InitializeAsync();
if (MediaEngineInitializationResult.Success != result)
{
Debug.WriteLine("Failed to start MediaEngine");
}
}
}
}
|
using Microsoft.Maker.Media.UniversalMediaEngine;
using System;
using System.Diagnostics;
using Windows.Media.SpeechSynthesis;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace speechSynthesisSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private MediaEngine mediaEngine;
public MainPage()
{
this.InitializeComponent();
this.mediaEngine = new MediaEngine();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");
mediaEngine.PlayStream(stream);
}
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
var result = await mediaEngine.InitializeAsync();
if (MediaEngineInitializationResult.Success != result)
{
Debug.WriteLine("Failed to start MediaEngine");
}
}
}
}
|
mit
|
C#
|
786f2ecbe5d3528595438f2154b2c3e719c0fc48
|
Remove trait from commontraits.cs
|
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation
|
UnityProject/Assets/Scripts/Items/Traits/CommonTraits.cs
|
UnityProject/Assets/Scripts/Items/Traits/CommonTraits.cs
|
using UnityEngine;
/// <summary>
/// Singleton, provides common ItemTraits with special purposes (such as components
/// used on many prefabs which automatically cause an object to have particular traits) so they can be easily used
/// in components without needing to be assigned in editor.
/// </summary>
[CreateAssetMenu(fileName = "CommonTraitsSingleton", menuName = "Singleton/Traits/CommonTraits")]
public class CommonTraits : SingletonScriptableObject<CommonTraits>
{
public ItemTrait ReagentContainer;
public ItemTrait CanisterFillable;
public ItemTrait Gun;
public ItemTrait Food;
public ItemTrait Mask;
public ItemTrait Wirecutter;
public ItemTrait Wrench;
public ItemTrait Emag;
public ItemTrait Crowbar;
public ItemTrait Screwdriver;
public ItemTrait NoSlip;
public ItemTrait Slippery;
public ItemTrait Multitool;
public ItemTrait SpillOnThrow;
public ItemTrait CanFillMop;
public ItemTrait Cultivator;
public ItemTrait Trowel;
public ItemTrait Bucket;
public ItemTrait MetalSheet;
public ItemTrait GlassSheet;
public ItemTrait PlasteelSheet;
public ItemTrait Cable;
public ItemTrait Welder;
public ItemTrait Shovel;
public ItemTrait Knife;
}
|
using UnityEngine;
/// <summary>
/// Singleton, provides common ItemTraits with special purposes (such as components
/// used on many prefabs which automatically cause an object to have particular traits) so they can be easily used
/// in components without needing to be assigned in editor.
/// </summary>
[CreateAssetMenu(fileName = "CommonTraitsSingleton", menuName = "Singleton/Traits/CommonTraits")]
public class CommonTraits : SingletonScriptableObject<CommonTraits>
{
public ItemTrait ReagentContainer;
public ItemTrait CanisterFillable;
public ItemTrait Gun;
public ItemTrait Food;
public ItemTrait Mask;
public ItemTrait Wirecutter;
public ItemTrait Wrench;
public ItemTrait Emag;
public ItemTrait Crowbar;
public ItemTrait Screwdriver;
public ItemTrait NoSlip;
public ItemTrait Slippery;
public ItemTrait Multitool;
public ItemTrait SpillOnThrow;
public ItemTrait CanFillMop;
public ItemTrait Cultivator;
public ItemTrait Trowel;
public ItemTrait Bucket;
public ItemTrait MetalSheet;
public ItemTrait GlassSheet;
public ItemTrait PlasteelSheet;
public ItemTrait Cable;
public ItemTrait Welder;
public ItemTrait Shovel;
public ItemTrait Knife;
public ItemTrait AtmosAnalyser;
}
|
agpl-3.0
|
C#
|
f023251170fd98f683433993165643b9bae6884e
|
Update QuoteRepository.cs
|
ShadowNoire/NadekoBot,miraai/NadekoBot,shikhir-arora/NadekoBot,Youngsie1997/NadekoBot,PravEF/EFNadekoBot,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,powered-by-moe/MikuBot,ScarletKuro/NadekoBot,Midnight-Myth/Mitternacht-NEW,WoodenGlaze/NadekoBot,Nielk1/NadekoBot,halitalf/NadekoMods,Taknok/NadekoBot,Blacnova/NadekoBot,gfrewqpoiu/NadekoBot
|
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
|
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
|
using NadekoBot.Services.Database.Models;
using NadekoBot.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
return _set.Where(q => q.Text.ContainsNoCase(text, StringComparison.OrdinalIgnoreCase) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
|
using NadekoBot.Services.Database.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace NadekoBot.Services.Database.Repositories.Impl
{
public class QuoteRepository : Repository<Quote>, IQuoteRepository
{
public QuoteRepository(DbContext context) : base(context)
{
}
public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) =>
_set.Where(q => q.GuildId == guildId && q.Keyword == keyword);
public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) =>
_set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList();
public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword)
{
var rng = new NadekoRandom();
return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync();
}
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text)
{
var rngk = new NadekoRandom();
return _set.Where(q => q.Text.IndexOf(text, StringComparison.OrdinalIgnoreCase) >=0 && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync();
}
}
}
|
mit
|
C#
|
d475f9827359324174962016176b33be2c3db9cb
|
Implement `BinaryExpression.ToString()`
|
ForNeVeR/Pash,ForNeVeR/Pash,sillvan/Pash,mrward/Pash,ForNeVeR/Pash,mrward/Pash,sillvan/Pash,WimObiwan/Pash,mrward/Pash,mrward/Pash,sillvan/Pash,WimObiwan/Pash,sillvan/Pash,Jaykul/Pash,sburnicki/Pash,sburnicki/Pash,Jaykul/Pash,JayBazuzi/Pash,JayBazuzi/Pash,JayBazuzi/Pash,JayBazuzi/Pash,Jaykul/Pash,Jaykul/Pash,WimObiwan/Pash,ForNeVeR/Pash,sburnicki/Pash,WimObiwan/Pash,sburnicki/Pash
|
Source/Pash.System.Management/Pash/ParserIntrinsics/BinaryExpressionAst.cs
|
Source/Pash.System.Management/Pash/ParserIntrinsics/BinaryExpressionAst.cs
|
using System;
using System.Collections.Generic;
using System.Management.Automation;
namespace System.Management.Automation.Language
{
public class BinaryExpressionAst : ExpressionAst
{
public BinaryExpressionAst(IScriptExtent extent, ExpressionAst left, TokenKind @operator, ExpressionAst right, IScriptExtent errorPosition)
: base(extent)
{
this.Left = left;
this.Operator = @operator;
this.Right = @right;
this.ErrorPosition = errorPosition;
}
public IScriptExtent ErrorPosition { get; private set; }
public ExpressionAst Left { get; private set; }
public TokenKind Operator { get; private set; }
public ExpressionAst Right { get; private set; }
public override Type StaticType { get { return typeof(object); } }
internal override IEnumerable<Ast> Children
{
get
{
yield return this.Left;
yield return this.Right;
foreach (var item in base.Children) yield return item;
}
}
public override string ToString()
{
return string.Format("{0} {1} {2}", this.Left, this.Operator, this.Right);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Management.Automation;
namespace System.Management.Automation.Language
{
public class BinaryExpressionAst : ExpressionAst
{
public BinaryExpressionAst(IScriptExtent extent, ExpressionAst left, TokenKind @operator, ExpressionAst right, IScriptExtent errorPosition)
: base(extent)
{
this.Left = left;
this.Operator = @operator;
this.Right = @right;
this.ErrorPosition = errorPosition;
}
public IScriptExtent ErrorPosition { get; private set; }
public ExpressionAst Left { get; private set; }
public TokenKind Operator { get; private set; }
public ExpressionAst Right { get; private set; }
public override Type StaticType { get { return typeof(object); } }
internal override IEnumerable<Ast> Children
{
get
{
yield return this.Left;
yield return this.Right;
foreach (var item in base.Children) yield return item;
}
}
}
}
|
bsd-3-clause
|
C#
|
199bd7cf38c925527a923f1470ebdbf965ab2e8b
|
Fix typo in DirectoryTransferContext.cs
|
Azure/azure-storage-net-data-movement
|
lib/DirectoryTransferContext.cs
|
lib/DirectoryTransferContext.cs
|
//------------------------------------------------------------------------------
// <copyright file="DirectoryTransferContext.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
using System.IO;
/// <summary>
/// Represents the context for a directory transfer, and provides additional runtime information about its execution.
/// </summary>
public class DirectoryTransferContext : TransferContext
{
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryTransferContext" /> class.
/// </summary>
public DirectoryTransferContext()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryTransferContext" /> class.
/// </summary>
/// <param name="checkpoint">An <see cref="TransferCheckpoint"/> object representing the last checkpoint from which the transfer continues on.</param>
public DirectoryTransferContext(TransferCheckpoint checkpoint)
:base(checkpoint)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryTransferContext" /> class.
/// </summary>
/// <param name="journalStream">The stream into which the transfer journal info will be written into.
/// It can resume the previous paused transfer from its journal stream.</param>
public DirectoryTransferContext(Stream journalStream)
:base(journalStream)
{
}
/// <summary>
/// Gets or sets the callback invoked to tell whether a transfer should be done.
/// </summary>
public ShouldTransferCallbackAsync ShouldTransferCallbackAsync
{
get;
set;
}
}
}
|
//------------------------------------------------------------------------------
// <copyright file="DirectoryTransferContext.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
using System.IO;
/// <summary>
/// Represents the context for a directory transfer, and provides additional runtime information about its execution.
/// </summary>
public class DirectoryTransferContext : TransferContext
{
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryTransferContext" /> class.
/// </summary>
public DirectoryTransferContext()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryTransferContext" /> class.
/// </summary>
/// <param name="checkpoint">An <see cref="TransferCheckpoint"/> object representing the last checkpoint from which the transfer continues on.</param>
public DirectoryTransferContext(TransferCheckpoint checkpoint)
:base(checkpoint)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryTransferContext" /> class.
/// </summary>
/// <param name="journalStream">The stream into which the transfer journal info will be written into.
/// It can resume the previours paused transfer from its journal stream.</param>
public DirectoryTransferContext(Stream journalStream)
:base(journalStream)
{
}
/// <summary>
/// Gets or sets the callback invoked to tell whether a transfer should be done.
/// </summary>
public ShouldTransferCallbackAsync ShouldTransferCallbackAsync
{
get;
set;
}
}
}
|
mit
|
C#
|
4e53e57b5c034fedb4c0d081b11eccb2cbc793db
|
Add version information
|
cd01/sudo-in-windows,cd01/sudo-in-windows
|
sudo.cs
|
sudo.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
[assembly: AssemblyVersion("0.0.0.1")]
[assembly: AssemblyCopyright("Copyright cd01 2014")]
[assembly: AssemblyDescription("Elevate UAC")]
class sudo
{
static void Main(string[] args)
{
var startInfo = new System.Diagnostics.ProcessStartInfo()
{
FileName = args[0],
UseShellExecute = true,
Verb = "runas",
Arguments = new Func<IEnumerable<string>, string>((argsInShell) =>
{
return string.Join(" ", argsInShell);
})(args.Skip(1))
};
try
{
var proc = System.Diagnostics.Process.Start(startInfo);
proc.WaitForExit();
}
catch(Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sudo
{
class Program
{
static void Main(string[] args)
{
var startInfo = new System.Diagnostics.ProcessStartInfo()
{
FileName = args[0],
UseShellExecute = true,
Verb = "runas",
Arguments = new Func<IEnumerable<string>, string>((argsInShell) =>
{
return string.Join(" ", argsInShell);
})(args.Skip(1))
};
try
{
var proc = System.Diagnostics.Process.Start(startInfo);
proc.WaitForExit();
}
catch(Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
}
}
|
mit
|
C#
|
c7ca84ff53e265c9125c766153471346d9a291ee
|
Update RestVerb.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Web/Rest/RestVerb.cs
|
TIKSN.Core/Web/Rest/RestVerb.cs
|
namespace TIKSN.Web.Rest
{
public enum RestVerb
{
Get,
Delete,
Put,
Post
}
}
|
namespace TIKSN.Web.Rest
{
public enum RestVerb
{
Get,
Delete,
Put,
Post
}
}
|
mit
|
C#
|
93441272cdef1a8c1a8890d88c6f608b49d11fa7
|
Rename from Path to Extension of IMediaFile.
|
ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey
|
client/BlueMonkey/BlueMonkey.MediaServices/IMediaFile.cs
|
client/BlueMonkey/BlueMonkey.MediaServices/IMediaFile.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlueMonkey.MediaServices
{
public interface IMediaFile : IDisposable
{
/// <summary>
/// Extension of media file. Start with a period.
/// </summary>
string Extension { get; }
/// <summary>
/// Get stream if available
/// </summary>
/// <returns></returns>
Stream GetStream();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlueMonkey.MediaServices
{
public interface IMediaFile : IDisposable
{
/// <summary>
/// Path to file.
/// </summary>
string Path { get; }
/// <summary>
/// Get stream if available
/// </summary>
/// <returns></returns>
Stream GetStream();
}
}
|
mit
|
C#
|
1a6d39cb5fbe115c20a1e267c6a210446830d422
|
Use external console when running DNX apps.
|
mrward/monodevelop-dnx-addin
|
src/MonoDevelop.Dnx/MonoDevelop.Dnx/DnxProjectConfiguration.cs
|
src/MonoDevelop.Dnx/MonoDevelop.Dnx/DnxProjectConfiguration.cs
|
//
// DnxProjectConfiguration.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (c) 2015 Matthew Ward
//
// 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 MonoDevelop.Projects;
namespace MonoDevelop.Dnx
{
public class DnxProjectConfiguration : DotNetProjectConfiguration
{
public DnxProjectConfiguration (string name)
: base (name)
{
ExternalConsole = true;
}
public DnxProjectConfiguration ()
{
ExternalConsole = true;
}
}
}
|
//
// DnxProjectConfiguration.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (c) 2015 Matthew Ward
//
// 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 MonoDevelop.Projects;
namespace MonoDevelop.Dnx
{
public class DnxProjectConfiguration : DotNetProjectConfiguration
{
public DnxProjectConfiguration (string name)
: base (name)
{
}
public DnxProjectConfiguration ()
{
}
}
}
|
mit
|
C#
|
1882c825e1f53e8c377084716b78dac15893ec72
|
Change route name to be unique (#835)
|
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
|
src/SFA.DAS.EAS.Api/Controllers/EmployerAgreementController.cs
|
src/SFA.DAS.EAS.Api/Controllers/EmployerAgreementController.cs
|
using System.Threading.Tasks;
using System.Web.Http;
using NLog;
using SFA.DAS.EAS.Api.Attributes;
using SFA.DAS.EAS.Api.Orchestrators;
namespace SFA.DAS.EAS.Api.Controllers
{
[RoutePrefix("api/accounts/{hashedAccountId}/legalEntities/{hashedlegalEntityId}/agreements")]
public class EmployerAgreementController : ApiController
{
private readonly AgreementOrchestrator _orchestrator;
private readonly ILogger _logger;
public EmployerAgreementController(AgreementOrchestrator orchestrator, ILogger logger)
{
_orchestrator = orchestrator;
_logger = logger;
}
[Route("{agreementId}", Name = "AgreementById")]
[ApiAuthorize(Roles = "ReadAllEmployerAgreements")]
[HttpGet]
public async Task<IHttpActionResult> GetAgreement(string agreementId)
{
var response = await _orchestrator.GetAgreement(agreementId);
_logger.Info("Incorrect get agreement API call received");
return Ok(response);
}
[Route("{agreementId}/agreement", Name = "GetAgreement")]
[ApiAuthorize(Roles = "ReadAllEmployerAgreements")]
[HttpGet]
public async Task<IHttpActionResult> GetAgreementById(string agreementId)
{
var response = await _orchestrator.GetAgreement(agreementId);
if (response.Data == null)
{
return NotFound();
}
return Ok(response.Data);
}
}
}
|
using System.Threading.Tasks;
using System.Web.Http;
using NLog;
using SFA.DAS.EAS.Api.Attributes;
using SFA.DAS.EAS.Api.Orchestrators;
namespace SFA.DAS.EAS.Api.Controllers
{
[RoutePrefix("api/accounts/{hashedAccountId}/legalEntities/{hashedlegalEntityId}/agreements")]
public class EmployerAgreementController : ApiController
{
private readonly AgreementOrchestrator _orchestrator;
private readonly ILogger _logger;
public EmployerAgreementController(AgreementOrchestrator orchestrator, ILogger logger)
{
_orchestrator = orchestrator;
_logger = logger;
}
[Route("{agreementId}", Name = "AgreementById")]
[ApiAuthorize(Roles = "ReadAllEmployerAgreements")]
[HttpGet]
public async Task<IHttpActionResult> GetAgreement(string agreementId)
{
var response = await _orchestrator.GetAgreement(agreementId);
_logger.Info("Incorrect get agreement API call received");
return Ok(response);
}
[Route("{agreementId}/agreement", Name = "AgreementById")]
[ApiAuthorize(Roles = "ReadAllEmployerAgreements")]
[HttpGet]
public async Task<IHttpActionResult> GetAgreementById(string agreementId)
{
var response = await _orchestrator.GetAgreement(agreementId);
if (response.Data == null)
{
return NotFound();
}
return Ok(response.Data);
}
}
}
|
mit
|
C#
|
974101624b560bdb4cb6a2fd084e075176ffee4e
|
fix text
|
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
|
BTCPayServer/Views/Account/LoginWithU2F.cshtml
|
BTCPayServer/Views/Account/LoginWithU2F.cshtml
|
@model BTCPayServer.U2F.Models.LoginWithU2FViewModel
<form id="u2fForm" asp-action="LoginWithU2F" method="post" asp-route-returnUrl="@ViewData["ReturnUrl"]">
<input type="hidden" asp-for="Version" />
<input type="hidden" asp-for="Challenge" />
<input type="hidden" asp-for="AppId" />
<input type="hidden" asp-for="DeviceResponse" />
@for (int i = 0; i < Model.Challenges.Count; i++)
{
@Html.HiddenFor(m => m.Challenges[i])
}
<input type="hidden" asp-for="UserId" />
<input type="hidden" asp-for="RememberMe" />
</form>
<section>
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading"><span class="fa fa-spinner fa-spin"></span>U2F Authentication</h2>
<hr class="primary">
<p>Insert your U2F device or a hardware wallet into your computer's USB port. If it has a button, tap on it.</p>
</div>
</div>
<div class="row">
<a id="error-response" class="text-danger" href="javascript:window.location.reload()"> </a>
</div>
</div>
</section>
<script src="~/vendor/u2f/u2f-api-1.1.js"></script>
<script type="text/javascript">
var errorMap = {
1: 'Unknown error, try again',
2: "Bad request error, try again",
3: "This key isn't supported, please try another one",
4: 'The device is not registered, please try another one',
5: 'Authentication timed out. Please reload to try again.'
};
setTimeout(function() {
window.u2f.sign(
@Safe.Json(Model.AppId),
@Safe.Json(Model.Challenge),
@Safe.Json(Model.Challenges), function (data) {
if (data.errorCode) {
$("#error-response").text(errorMap[data.errorCode]);
return;
}
$('#DeviceResponse').val(JSON.stringify(data));
$('#u2fForm').submit();
return "";
});
}, 1000);
</script>
|
@model BTCPayServer.U2F.Models.LoginWithU2FViewModel
<form id="u2fForm" asp-action="LoginWithU2F" method="post" asp-route-returnUrl="@ViewData["ReturnUrl"]">
<input type="hidden" asp-for="Version" />
<input type="hidden" asp-for="Challenge" />
<input type="hidden" asp-for="AppId" />
<input type="hidden" asp-for="DeviceResponse" />
@for (int i = 0; i < Model.Challenges.Count; i++)
{
@Html.HiddenFor(m => m.Challenges[i])
}
<input type="hidden" asp-for="UserId" />
<input type="hidden" asp-for="RememberMe" />
</form>
<section>
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading"><span class="fa fa-spinner fa-spin"></span>U2F Authentication</h2>
<hr class="primary">
<p>Insert your U2F device or a hardware wallet into your computer's USB port. If it has a button, tap on it.</p>
</div>
</div>
<div class="row">
<a id="error-response" class="text-danger" href="javascript:window.location.reload()"> </a>
</div>
</div>
</section>
<script src="~/vendor/u2f/u2f-api-1.1.js"></script>
<script type="text/javascript">
var errorMap = {
1: 'Unknown error, try again',
2: "Bad request error, try again",
3: "This key isn't supported, please try another one",
4: 'The device is already registered, please login',
5: 'Authentication timed out. Please reload to try again.'
};
setTimeout(function() {
window.u2f.sign(
@Safe.Json(Model.AppId),
@Safe.Json(Model.Challenge),
@Safe.Json(Model.Challenges), function (data) {
if (data.errorCode) {
$("#error-response").text(errorMap[data.errorCode]);
return;
}
$('#DeviceResponse').val(JSON.stringify(data));
$('#u2fForm').submit();
return "";
});
}, 1000);
</script>
|
mit
|
C#
|
ac44e1d6e2ab4a81eee12d55fd291eb714b3f635
|
Update PERSTATReportJob.cs
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Jobs/PERSTATReportJob.cs
|
Battery-Commander.Web/Jobs/PERSTATReportJob.cs
|
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using FluentEmail.Core;
using FluentEmail.Core.Models;
using FluentScheduler;
using System.Collections.Generic;
using System.IO;
namespace BatteryCommander.Web.Jobs
{
public class PERSTATReportJob : IJob
{
private static IList<Address> Recipients => new List<Address>(new Address[]
{
FROM
// new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" }
});
internal static Address FROM => new Address { Name = "C-2-116 FA", EmailAddress = "BatteryCommander@redleg.app" };
private readonly Database db;
private readonly IFluentEmail emailSvc;
public PERSTATReportJob(Database db, IFluentEmail emailSvc)
{
this.db = db;
this.emailSvc = emailSvc;
}
public virtual void Execute()
{
foreach (var unit in UnitService.List(db).GetAwaiter().GetResult())
{
// HACK - Configure the recipients and units that this is going to be wired up for
emailSvc
.To(Recipients)
.SetFrom(FROM.EmailAddress, FROM.Name)
.Subject($"{unit.Name} | RED 1 PERSTAT")
.UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit)
.Send();
}
}
}
}
|
using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using FluentEmail.Core;
using FluentEmail.Core.Models;
using FluentScheduler;
using System.Collections.Generic;
using System.IO;
namespace BatteryCommander.Web.Jobs
{
public class PERSTATReportJob : IJob
{
private static IList<Address> Recipients => new List<Address>(new Address[]
{
FROM
// new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" }
});
internal static Address FROM => new Address { Name = "C-2-116 FA", EmailAddress = "C-2-116FA@redleg.app" };
private readonly Database db;
private readonly IFluentEmail emailSvc;
public PERSTATReportJob(Database db, IFluentEmail emailSvc)
{
this.db = db;
this.emailSvc = emailSvc;
}
public virtual void Execute()
{
foreach (var unit in UnitService.List(db).GetAwaiter().GetResult())
{
// HACK - Configure the recipients and units that this is going to be wired up for
emailSvc
.To(Recipients)
.SetFrom(FROM.EmailAddress, FROM.Name)
.Subject($"{unit.Name} | RED 1 PERSTAT")
.UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit)
.Send();
}
}
}
}
|
mit
|
C#
|
e8d74ba067d1495b7a1724febbb473203c39affa
|
Remove 'Beta' from version
|
Jericho/CakeMail.RestClient
|
CakeMail.RestClient/Properties/AssemblyInfo.cs
|
CakeMail.RestClient/Properties/AssemblyInfo.cs
|
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0.0")]
|
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta07")]
|
mit
|
C#
|
6fc5f5c904d37d2be643e2a91b6310948a0808d5
|
Make AudioSource mandatory for AudioObject.
|
dimixar/audio-controller-unity
|
AudioController/Assets/Source/AudioObject.cs
|
AudioController/Assets/Source/AudioObject.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class AudioObject : MonoBehaviour {
public System.Action<AudioObject> OnFinishedPlaying;
#region private fields
private string _id;
private AudioClip _clip;
private AudioSource _source;
private Coroutine _playingRoutine;
#endregion
#region Public methods and properties
public string clipName {
get {
return _clip != null ? _clip.name : "NONE";
}
}
public void Setup(string id, AudioClip clip)
{
_id = id;
_clip = clip;
}
public void Play()
{
if (_source == null)
_source = GetComponent<AudioSource>();
_source.clip = _clip;
_source.Play();
_playingRoutine = StartCoroutine(PlayingRoutine());
}
public void Stop()
{
if (_playingRoutine == null)
return;
_source.Stop();
}
[ContextMenu("Test Play")]
private void TestPlay()
{
Play();
}
#endregion
private IEnumerator PlayingRoutine()
{
Debug.Log("Playing Started");
while(true)
{
Debug.Log("Checking if it's playing.");
yield return new WaitForSeconds(0.05f);
if (!_source.isPlaying)
{
Debug.Log("AudioSource Finished Playing");
break;
}
}
Debug.Log("Not playing anymore");
if (OnFinishedPlaying != null)
{
OnFinishedPlaying(this);
}
_source.clip = null;
_playingRoutine = null;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioObject : MonoBehaviour {
public System.Action<AudioObject> OnFinishedPlaying;
#region private fields
private string _id;
private AudioClip _clip;
private AudioSource _source;
private Coroutine _playingRoutine;
#endregion
#region Public methods and properties
public string clipName {
get {
return _clip != null ? _clip.name : "NONE";
}
}
public void Setup(string id, AudioClip clip)
{
_id = id;
_clip = clip;
}
public void Play(AudioSource source)
{
_source = source;
_source.clip = _clip;
_source.Play();
_playingRoutine = StartCoroutine(PlayingRoutine());
}
public void Stop()
{
if (_playingRoutine == null)
return;
_source.Stop();
}
[ContextMenu("Test Play")]
private void TestPlay()
{
Play(_source);
}
#endregion
private IEnumerator PlayingRoutine()
{
Debug.Log("Playing Started");
while(true)
{
Debug.Log("Checking if it's playing.");
yield return new WaitForSeconds(0.05f);
if (!_source.isPlaying)
{
Debug.Log("AudioSource Finished Playing");
break;
}
}
Debug.Log("Not playing anymore");
if (OnFinishedPlaying != null)
{
OnFinishedPlaying(this);
}
_source.clip = null;
_source = null;
_playingRoutine = null;
}
}
|
mit
|
C#
|
4882137ffb2127fd9dd6c5dbb7af18e9e44c4b30
|
Add indicator to APFT list
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Views/APFT/List.cshtml
|
Battery-Commander.Web/Views/APFT/List.cshtml
|
@model IEnumerable<APFT>
<div class="page-header">
<h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped" id="dt">
<thead>
<tr>
<th>Soldier</th>
<th>Date</th>
<th>Score</th>
<th>Result</th>
<th>Details</th>
</tr>
</thead>
<tbody>
@foreach (var model in Model)
{
<tr>
<td>@Html.DisplayFor(_ => model.Soldier)</td>
<td>
<a href="@Url.Action("Index", new { date = model.Date })">
@Html.DisplayFor(_ => model.Date)
</a>
</td>
<td>
@Html.DisplayFor(_ => model.TotalScore)
@if(model.IsAlternateAerobicEvent)
{
<span class="label">Alt. Aerobic</span>
}
</td>
<td>
@if (model.IsPassing)
{
<span class="label label-success">Passing</span>
}
else
{
<span class="label label-danger">Failure</span>
}
</td>
<td>@Html.ActionLink("Details", "Details", new { model.Id })</td>
</tr>
}
</tbody>
</table>
|
@model IEnumerable<APFT>
<div class="page-header">
<h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped" id="dt">
<thead>
<tr>
<th>Soldier</th>
<th>Date</th>
<th>Score</th>
<th>Result</th>
<th>Details</th>
</tr>
</thead>
<tbody>
@foreach (var model in Model)
{
<tr>
<td>@Html.DisplayFor(_ => model.Soldier)</td>
<td>
<a href="@Url.Action("Index", new { date = model.Date })">
@Html.DisplayFor(_ => model.Date)
</a>
</td>
<td>@Html.DisplayFor(_ => model.TotalScore)</td>
<td>
@if (model.IsPassing)
{
<span class="label label-success">Passing</span>
}
else
{
<span class="label label-danger">Failure</span>
}
</td>
<td>@Html.ActionLink("Details", "Details", new { model.Id })</td>
</tr>
}
</tbody>
</table>
|
mit
|
C#
|
a1f26a74ec68f492065cc99bdb7812d1f4bc48ea
|
Fix sending
|
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer
|
Client/Systems/VesselFlightStateSys/VesselFlightStateMessageSender.cs
|
Client/Systems/VesselFlightStateSys/VesselFlightStateMessageSender.cs
|
using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaClient.Network;
using LunaClient.Systems.TimeSyncer;
using LunaClient.Systems.Warp;
using LunaClient.VesselStore;
using LunaCommon.Message.Client;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;
namespace LunaClient.Systems.VesselFlightStateSys
{
public class VesselFlightStateMessageSender : SubSystem<VesselFlightStateSystem>, IMessageSender
{
public void SendMessage(IMessageData msg)
{
NetworkSender.QueueOutgoingMessage(MessageFactory.CreateNew<VesselCliMsg>(msg));
}
public void SendCurrentFlightState()
{
var flightState = new FlightCtrlState();
flightState.CopyFrom(FlightGlobals.ActiveVessel.ctrlState);
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<VesselFlightStateMsgData>();
msgData.GameTime = TimeSyncerSystem.UniversalTime;
msgData.SubspaceId = WarpSystem.Singleton.CurrentSubspace;
msgData.VesselId = FlightGlobals.ActiveVessel.id;
msgData.GearDown = flightState.gearDown;
msgData.GearUp = flightState.gearUp;
msgData.Headlight = flightState.headlight;
msgData.KillRot = flightState.killRot;
msgData.MainThrottle = flightState.mainThrottle;
msgData.Pitch = flightState.pitch;
msgData.PitchTrim = flightState.pitchTrim;
msgData.Roll = flightState.roll;
msgData.RollTrim = flightState.rollTrim;
msgData.WheelSteer = flightState.wheelSteer;
msgData.WheelSteerTrim = flightState.wheelSteerTrim;
msgData.WheelThrottle = flightState.wheelThrottle;
msgData.WheelThrottleTrim = flightState.wheelThrottleTrim;
msgData.X = flightState.X;
msgData.Y = flightState.Y;
msgData.Yaw = flightState.yaw;
msgData.YawTrim = flightState.yawTrim;
msgData.Z = flightState.Z;
SendMessage(msgData);
VesselsProtoStore.UpdateVesselProtoFlightState(msgData);
System.UpdateFlightStateInProtoVessel(FlightGlobals.ActiveVessel.protoVessel, msgData);
}
}
}
|
using LunaClient.Base;
using LunaClient.Base.Interface;
using LunaClient.Network;
using LunaClient.Systems.TimeSyncer;
using LunaClient.VesselStore;
using LunaCommon.Message.Client;
using LunaCommon.Message.Data.Vessel;
using LunaCommon.Message.Interface;
namespace LunaClient.Systems.VesselFlightStateSys
{
public class VesselFlightStateMessageSender : SubSystem<VesselFlightStateSystem>, IMessageSender
{
public void SendMessage(IMessageData msg)
{
NetworkSender.QueueOutgoingMessage(MessageFactory.CreateNew<VesselCliMsg>(msg));
}
public void SendCurrentFlightState()
{
var flightState = new FlightCtrlState();
flightState.CopyFrom(FlightGlobals.ActiveVessel.ctrlState);
var msgData = NetworkMain.CliMsgFactory.CreateNewMessageData<VesselFlightStateMsgData>();
msgData.GameTime = TimeSyncerSystem.UniversalTime;
msgData.VesselId = FlightGlobals.ActiveVessel.id;
msgData.GearDown = flightState.gearDown;
msgData.GearUp = flightState.gearUp;
msgData.Headlight = flightState.headlight;
msgData.KillRot = flightState.killRot;
msgData.MainThrottle = flightState.mainThrottle;
msgData.Pitch = flightState.pitch;
msgData.PitchTrim = flightState.pitchTrim;
msgData.Roll = flightState.roll;
msgData.RollTrim = flightState.rollTrim;
msgData.WheelSteer = flightState.wheelSteer;
msgData.WheelSteerTrim = flightState.wheelSteerTrim;
msgData.WheelThrottle = flightState.wheelThrottle;
msgData.WheelThrottleTrim = flightState.wheelThrottleTrim;
msgData.X = flightState.X;
msgData.Y = flightState.Y;
msgData.Yaw = flightState.yaw;
msgData.YawTrim = flightState.yawTrim;
msgData.Z = flightState.Z;
msgData.GameTime = TimeSyncerSystem.UniversalTime;
SendMessage(msgData);
VesselsProtoStore.UpdateVesselProtoFlightState(msgData);
System.UpdateFlightStateInProtoVessel(FlightGlobals.ActiveVessel.protoVessel, msgData);
}
}
}
|
mit
|
C#
|
240401a3baca6ac857c399ff9821cbc0f0f5edf0
|
Remove unnecessary using
|
danielmarbach/nunit,JustinRChou/nunit,Therzok/nunit,dicko2/nunit,JohanO/nunit,mikkelbu/nunit,michal-franc/nunit,zmaruo/nunit,jhamm/nunit,NarohLoyahl/nunit,jnm2/nunit,Green-Bug/nunit,jadarnel27/nunit,akoeplinger/nunit,cPetru/nunit-params,pcalin/nunit,ggeurts/nunit,NikolayPianikov/nunit,nivanov1984/nunit,mikkelbu/nunit,OmicronPersei/nunit,dicko2/nunit,JustinRChou/nunit,nunit/nunit,agray/nunit,elbaloo/nunit,ArsenShnurkov/nunit,modulexcite/nunit,michal-franc/nunit,passaro/nunit,zmaruo/nunit,mjedrzejek/nunit,JohanO/nunit,ChrisMaddock/nunit,ggeurts/nunit,appel1/nunit,nivanov1984/nunit,Suremaker/nunit,JohanO/nunit,Green-Bug/nunit,modulexcite/nunit,akoeplinger/nunit,cPetru/nunit-params,elbaloo/nunit,akoeplinger/nunit,passaro/nunit,nunit/nunit,Therzok/nunit,jnm2/nunit,agray/nunit,danielmarbach/nunit,OmicronPersei/nunit,appel1/nunit,jadarnel27/nunit,passaro/nunit,NikolayPianikov/nunit,ChrisMaddock/nunit,pcalin/nunit,agray/nunit,Therzok/nunit,NarohLoyahl/nunit,mjedrzejek/nunit,jhamm/nunit,Green-Bug/nunit,zmaruo/nunit,jeremymeng/nunit,ArsenShnurkov/nunit,danielmarbach/nunit,modulexcite/nunit,Suremaker/nunit,jeremymeng/nunit,NarohLoyahl/nunit,michal-franc/nunit,pflugs30/nunit,pflugs30/nunit,elbaloo/nunit,pcalin/nunit,acco32/nunit,jeremymeng/nunit,dicko2/nunit,jhamm/nunit,ArsenShnurkov/nunit,acco32/nunit,acco32/nunit
|
NUnitConsole/src/nunit-console/OutputWriters/NUnit3XmlOutputWriter.cs
|
NUnitConsole/src/nunit-console/OutputWriters/NUnit3XmlOutputWriter.cs
|
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// 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.Text;
using System.Xml;
using System.IO;
namespace NUnit.ConsoleRunner
{
public class NUnit3XmlOutputWriter : IResultWriter
{
public void WriteResultFile(XmlNode resultNode, string outputPath)
{
using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8))
{
WriteResultFile(resultNode, writer);
}
}
public void WriteResultFile(XmlNode resultNode, TextWriter writer)
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument(false);
resultNode.WriteTo(xmlWriter);
}
}
}
}
|
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole
//
// 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.Text;
using System.Xml;
using NUnit.Engine;
using System.IO;
namespace NUnit.ConsoleRunner
{
public class NUnit3XmlOutputWriter : IResultWriter
{
public void WriteResultFile(XmlNode resultNode, string outputPath)
{
using (StreamWriter writer = new StreamWriter(outputPath, false, Encoding.UTF8))
{
WriteResultFile(resultNode, writer);
}
}
public void WriteResultFile(XmlNode resultNode, TextWriter writer)
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteStartDocument(false);
resultNode.WriteTo(xmlWriter);
}
}
}
}
|
mit
|
C#
|
24302020bc0bc975c5767c538e464e97b13a5630
|
Remove file header
|
Spreads/Spreads
|
tests/Spreads.Extensions.Tests/Storage/SQLite/SqlitePerformanceTest.cs
|
tests/Spreads.Extensions.Tests/Storage/SQLite/SqlitePerformanceTest.cs
|
using System;
using System.Data;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using Dapper;
//using Dapper;
using NUnit.Framework;
using Microsoft.Data.Sqlite.Utilities;
using static Microsoft.Data.Sqlite.TestUtilities.Constants;
namespace Microsoft.Data.Sqlite {
[TestFixture]
public class SqlitePerformanceTest {
[SetUp]
public void Init() {
var bs = Bootstrap.Bootstrapper.Instance;
}
[Test]
public void InsertSpeed() {
var connectionString = "Data Source=perf_test.db;";
using (var connection = new SqliteConnection(connectionString)) {
connection.Open();
connection.ExecuteNonQuery("PRAGMA main.page_size = 4096;");
connection.ExecuteNonQuery("PRAGMA main.cache_size = 10000;");
connection.ExecuteNonQuery("PRAGMA synchronous = OFF;"); // NORMAL or OFF 20% faster
connection.ExecuteNonQuery("PRAGMA journal_mode = WAL;");
connection.ExecuteNonQuery("PRAGMA main.cache_size = 5000;");
connection.ExecuteNonQuery("DROP TABLE IF EXISTS Numbers");
connection.ExecuteNonQuery("CREATE TABLE Numbers (Key INTEGER, Value REAL);");
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 200000; i++) {
connection.ExecuteNonQuery($"INSERT INTO Numbers VALUES ({i}, {i});");
//connection.Execute("INSERT INTO Numbers VALUES (@Key, @Value);",
// new[] { new { Key = (long)i, Value = (double)i } });
}
sw.Stop();
Console.WriteLine($"Elapsed, msec {sw.ElapsedMilliseconds}");
}
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Data;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using Dapper;
//using Dapper;
using NUnit.Framework;
using Microsoft.Data.Sqlite.Utilities;
using static Microsoft.Data.Sqlite.TestUtilities.Constants;
namespace Microsoft.Data.Sqlite {
[TestFixture]
public class SqlitePerformanceTest {
[SetUp]
public void Init() {
var bs = Bootstrap.Bootstrapper.Instance;
}
[Test]
public void InsertSpeed() {
var connectionString = "Data Source=perf_test.db;";
using (var connection = new SqliteConnection(connectionString)) {
connection.Open();
connection.ExecuteNonQuery("PRAGMA main.page_size = 4096;");
connection.ExecuteNonQuery("PRAGMA main.cache_size = 10000;");
connection.ExecuteNonQuery("PRAGMA synchronous = OFF;"); // NORMAL or OFF 20% faster
connection.ExecuteNonQuery("PRAGMA journal_mode = WAL;");
connection.ExecuteNonQuery("PRAGMA main.cache_size = 5000;");
connection.ExecuteNonQuery("DROP TABLE IF EXISTS Numbers");
connection.ExecuteNonQuery("CREATE TABLE Numbers (Key INTEGER, Value REAL);");
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 200000; i++) {
connection.ExecuteNonQuery($"INSERT INTO Numbers VALUES ({i}, {i});");
//connection.Execute("INSERT INTO Numbers VALUES (@Key, @Value);",
// new[] { new { Key = (long)i, Value = (double)i } });
}
sw.Stop();
Console.WriteLine($"Elapsed, msec {sw.ElapsedMilliseconds}");
}
}
}
}
|
mpl-2.0
|
C#
|
5b64903e9b0f1da283a4b0e704534d01d27e6eab
|
Fix null deref in NetInfo (#477)
|
lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows
|
ReactWindows/ReactNative/Modules/NetInfo/DefaultNetworkInformation.cs
|
ReactWindows/ReactNative/Modules/NetInfo/DefaultNetworkInformation.cs
|
using Windows.Networking.Connectivity;
namespace ReactNative.Modules.NetInfo
{
class DefaultNetworkInformation : INetworkInformation
{
public event NetworkStatusChangedEventHandler NetworkStatusChanged;
public void Start()
{
NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged;
}
public void Stop()
{
NetworkInformation.NetworkStatusChanged -= OnNetworkStatusChanged;
}
public IConnectionProfile GetInternetConnectionProfile()
{
var profile = NetworkInformation.GetInternetConnectionProfile();
return profile != null
? new ConnectionProfileImpl(profile)
: null;
}
private void OnNetworkStatusChanged(object sender)
{
NetworkStatusChanged?.Invoke(sender);
}
class ConnectionProfileImpl : IConnectionProfile
{
private readonly ConnectionProfile _profile;
public ConnectionProfileImpl(ConnectionProfile profile)
{
_profile = profile;
}
public NetworkConnectivityLevel ConnectivityLevel
{
get
{
return _profile.GetNetworkConnectivityLevel();
}
}
}
}
}
|
using Windows.Networking.Connectivity;
namespace ReactNative.Modules.NetInfo
{
class DefaultNetworkInformation : INetworkInformation
{
public event NetworkStatusChangedEventHandler NetworkStatusChanged;
public void Start()
{
NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged;
}
public void Stop()
{
NetworkInformation.NetworkStatusChanged -= OnNetworkStatusChanged;
}
public IConnectionProfile GetInternetConnectionProfile()
{
var profile = NetworkInformation.GetInternetConnectionProfile();
var connectivity = profile.GetNetworkConnectivityLevel();
return profile != null
? new ConnectionProfileImpl(profile)
: null;
}
private void OnNetworkStatusChanged(object sender)
{
NetworkStatusChanged?.Invoke(sender);
}
class ConnectionProfileImpl : IConnectionProfile
{
private readonly ConnectionProfile _profile;
public ConnectionProfileImpl(ConnectionProfile profile)
{
_profile = profile;
}
public NetworkConnectivityLevel ConnectivityLevel
{
get
{
return _profile.GetNetworkConnectivityLevel();
}
}
}
}
}
|
mit
|
C#
|
aabe669444c16383c39a74f376e93e2385dfd199
|
Update copyright
|
aarondemarre/DRLeagueParser
|
DRNumberCrunchers/Properties/AssemblyInfo.cs
|
DRNumberCrunchers/Properties/AssemblyInfo.cs
|
using System.Resources;
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DRNumberCrunchers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DRNumberCrunchers")]
[assembly: AssemblyCopyright("Copyright © enamelizer 2016")]
[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.4.2.0")]
[assembly: AssemblyFileVersion("1.4.2.0")]
|
using System.Resources;
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DRNumberCrunchers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DRNumberCrunchers")]
[assembly: AssemblyCopyright("Copyright © Aaron DeMarre 2016")]
[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.4.2.0")]
[assembly: AssemblyFileVersion("1.4.2.0")]
|
mit
|
C#
|
c678a24f0fa6fec80436d8846b36056b63ad27d8
|
Fix a failing test
|
rockfordlhotka/csla,rockfordlhotka/csla,JasonBock/csla,MarimerLLC/csla,JasonBock/csla,rockfordlhotka/csla,MarimerLLC/csla,MarimerLLC/csla,JasonBock/csla
|
Source/csla.netcore.test/DataPortal/ServiceProviderInvocationTests.cs
|
Source/csla.netcore.test/DataPortal/ServiceProviderInvocationTests.cs
|
//-----------------------------------------------------------------------
// <copyright file="ServiceProviderMethodCallerTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Csla;
using Csla.Reflection;
using Microsoft.Extensions.DependencyInjection;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif
namespace Csla.Test.DataPortal
{
[TestClass]
public class ServiceProviderInvocationTests
{
[TestInitialize]
public void Initialize()
{
Csla.ApplicationContext.DefaultServiceProvider = null;
Csla.ApplicationContext.ServiceProviderScope = null;
}
[TestMethod]
public async Task NoServiceProvider()
{
var obj = new TestMethods();
var method = new ServiceProviderMethodInfo { MethodInfo = obj.GetType().GetMethod("Method1") };
Assert.IsNotNull(method, "needed method");
await Assert.ThrowsExceptionAsync<InvalidOperationException>(async () => await ServiceProviderMethodCaller.CallMethodTryAsync(obj, method, new object[] { 123 }));
}
[TestMethod]
public async Task WithServiceProvider()
{
IServiceCollection services = new ServiceCollection();
services.AddSingleton<ISpeak, Dog>();
Csla.ApplicationContext.DefaultServiceProvider = services.BuildServiceProvider();
var obj = new TestMethods();
var method = new ServiceProviderMethodInfo { MethodInfo = obj.GetType().GetMethod("GetSpeech") };
Assert.IsNotNull(method, "needed method");
var result = (string)await ServiceProviderMethodCaller.CallMethodTryAsync(obj, method, new object[] { 123 });
Assert.AreEqual("Bark", result);
}
}
public interface ISpeak
{
string Speak();
}
public class Dog : ISpeak
{
public string Speak()
{
return "Bark";
}
}
public class TestMethods
{
public bool Method1(int id, [Inject] ISpeak speaker)
{
return speaker == null;
}
public string GetSpeech(int id, [Inject] ISpeak speaker)
{
return speaker.Speak();
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="ServiceProviderMethodCallerTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Csla;
using Csla.Reflection;
using Microsoft.Extensions.DependencyInjection;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif
namespace Csla.Test.DataPortal
{
[TestClass]
public class ServiceProviderInvocationTests
{
[TestInitialize]
public void Initialize()
{
Csla.ApplicationContext.DefaultServiceProvider = null;
Csla.ApplicationContext.ServiceProviderScope = null;
}
[TestMethod]
public async Task NoServiceProvider()
{
var obj = new TestMethods();
var method = new ServiceProviderMethodInfo { MethodInfo = obj.GetType().GetMethod("Method1") };
Assert.IsNotNull(method, "needed method");
var result = (bool) await ServiceProviderMethodCaller.CallMethodTryAsync(obj, method, new object[] { 123 });
Assert.IsTrue(result);
}
[TestMethod]
public async Task WithServiceProvider()
{
IServiceCollection services = new ServiceCollection();
services.AddSingleton<ISpeak, Dog>();
Csla.ApplicationContext.DefaultServiceProvider = services.BuildServiceProvider();
var obj = new TestMethods();
var method = new ServiceProviderMethodInfo { MethodInfo = obj.GetType().GetMethod("GetSpeech") };
Assert.IsNotNull(method, "needed method");
var result = (string)await ServiceProviderMethodCaller.CallMethodTryAsync(obj, method, new object[] { 123 });
Assert.AreEqual("Bark", result);
}
}
public interface ISpeak
{
string Speak();
}
public class Dog : ISpeak
{
public string Speak()
{
return "Bark";
}
}
public class TestMethods
{
public bool Method1(int id, [Inject]ISpeak speaker)
{
return speaker == null;
}
public string GetSpeech(int id, [Inject]ISpeak speaker)
{
return speaker.Speak();
}
}
}
|
mit
|
C#
|
c1fc6e038baca7301769192236b2053a5f352b98
|
Fix enum GroupingTreeNodeFlags
|
martin211/aimp_dotnet,martin211/aimp_dotnet,martin211/aimp_dotnet,martin211/aimp_dotnet,martin211/aimp_dotnet
|
AIMP.SDK/MusicLibrary/DataStorage/IAimpGroupingTreeDataProviderSelection.cs
|
AIMP.SDK/MusicLibrary/DataStorage/IAimpGroupingTreeDataProviderSelection.cs
|
using System;
namespace AIMP.SDK.MusicLibrary.DataStorage
{
[Flags]
public enum GroupingTreeNodeFlags
{
AIMPML_GROUPINGTREENODE_FLAG_HASCHILDREN = 1,
AIMPML_GROUPINGTREENODE_FLAG_STANDALONE = 2
}
public enum FieldImageIndex
{
AIMPML_FIELDIMAGE_FOLDER = 0,
AIMPML_FIELDIMAGE_ARTIST = 1,
AIMPML_FIELDIMAGE_DISK = 2,
AIMPML_FIELDIMAGE_NOTE = 3,
AIMPML_FIELDIMAGE_STAR = 4,
AIMPML_FIELDIMAGE_CALENDAR = 5,
AIMPML_FIELDIMAGE_LABEL = 6
}
/// <summary>
/// Interface provides an access to data from the <seealso cref="IAimpGroupingTreeDataProvider.GetData"/>.
/// </summary>
public interface IAimpGroupingTreeDataProviderSelection
{
/// <summary>
/// Returns text to display to end user (optionally).
/// </summary>
/// <param name="displayValue">The display value.</param>
/// <returns></returns>
AimpActionResult GetDisplayValue(out string displayValue);
/// <summary>
/// Gets the tree node flags.
/// </summary>
GroupingTreeNodeFlags GetFlags();
AimpActionResult GetImageIndex(out FieldImageIndex imageIndex);
AimpActionResult GetValue(out string fieldName, out object value);
/// <summary>
/// Jumps to the next record. Returns False if current node is last.
/// </summary>
bool NextRow();
}
}
|
namespace AIMP.SDK.MusicLibrary.DataStorage
{
public enum GroupingTreeNodeFlags
{
AIMPML_GROUPINGTREENODE_FLAG_HASCHILDREN = 1,
AIMPML_GROUPINGTREENODE_FLAG_STANDALONE = 2
}
public enum FieldImageIndex
{
AIMPML_FIELDIMAGE_FOLDER = 0,
AIMPML_FIELDIMAGE_ARTIST = 1,
AIMPML_FIELDIMAGE_DISK = 2,
AIMPML_FIELDIMAGE_NOTE = 3,
AIMPML_FIELDIMAGE_STAR = 4,
AIMPML_FIELDIMAGE_CALENDAR = 5,
AIMPML_FIELDIMAGE_LABEL = 6
}
/// <summary>
/// Interface provides an access to data from the <seealso cref="IAimpGroupingTreeDataProvider.GetData"/>.
/// </summary>
public interface IAimpGroupingTreeDataProviderSelection
{
/// <summary>
/// Returns text to display to end user (optionally).
/// </summary>
/// <param name="displayValue">The display value.</param>
/// <returns></returns>
AimpActionResult GetDisplayValue(out string displayValue);
/// <summary>
/// Gets the tree node flags.
/// </summary>
GroupingTreeNodeFlags GetFlags();
AimpActionResult GetImageIndex(out FieldImageIndex imageIndex);
AimpActionResult GetValue(out string fieldName, out object value);
/// <summary>
/// Jumps to the next record. Returns False if current node is last.
/// </summary>
bool NextRow();
}
}
|
apache-2.0
|
C#
|
4bd846f89267f964e00c71674ee5176f57d46c8e
|
Update InsertDeleteRows.cs
|
asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
|
Examples/CSharp/Articles/InsertDeleteRows.cs
|
Examples/CSharp/Articles/InsertDeleteRows.cs
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class InsertDeleteRows
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate a Workbook object.
//Load a template file.
Workbook workbook = new Workbook(dataDir+ "book1.xlsx");
//Get the first worksheet in the book.
Worksheet sheet = workbook.Worksheets[0];
//Insert 10 rows at row index 2 (insertion starts at 3rd row)
sheet.Cells.InsertRows(2, 10);
//Delete 5 rows now. (8th row - 12th row)
sheet.Cells.DeleteRows(7, 5);
//Save the excel file.
workbook.Save(dataDir+ "out_book1.out.xlsx");
//ExEnd:1
}
}
}
|
using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class InsertDeleteRows
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate a Workbook object.
//Load a template file.
Workbook workbook = new Workbook(dataDir+ "book1.xlsx");
//Get the first worksheet in the book.
Worksheet sheet = workbook.Worksheets[0];
//Insert 10 rows at row index 2 (insertion starts at 3rd row)
sheet.Cells.InsertRows(2, 10);
//Delete 5 rows now. (8th row - 12th row)
sheet.Cells.DeleteRows(7, 5);
//Save the excel file.
workbook.Save(dataDir+ "out_book1.out.xlsx");
}
}
}
|
mit
|
C#
|
491b83b394968d3e8a9b84f7801d97ff2e84f9de
|
Update Program.cs
|
grzesiek-galezowski/component-based-test-tool
|
ComponentBasedTestTool/Playground/Program.cs
|
ComponentBasedTestTool/Playground/Program.cs
|
using Flurl.Http;
using Playground;
string AuthorizationHeaderValue()
{
var personalAccessToken = File.ReadAllText("C:\\Users\\HYPERBOOK\\Documents\\__KEYS\\azure-pipelines.txt");
var base64String = Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes(
$":{personalAccessToken}"));
return $"Basic {base64String}";
}
var organization = "grzesiekgalezowski";
var project = "grzesiekgalezowski";
// LIST of pipelines request
var jsonAsync = await $"https://dev.azure.com/{organization}/{project}/_apis/pipelines?api-version=7.1-preview.1"
.GetJsonAsync<ListOfPipelines>();
var pipelineIds = jsonAsync.Value.Select(p => p.Id);
Console.WriteLine(string.Join(',', pipelineIds));
var pipelineId = pipelineIds.First();
//GET pipeline info
var str = await $"https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}?api-version=6.0-preview.1"
.WithHeader("Authorization", AuthorizationHeaderValue())
.GetStringAsync();
Console.WriteLine(str);
//RUN pipeline
// requires sign in
var runPipelineJson = await $"https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=7.1-preview.1"
.WithHeader("Authorization", AuthorizationHeaderValue())
.PostJsonAsync(new
{
previewRun = false
});
var runPipelineResult = await runPipelineJson.GetJsonAsync<Run>();
Console.WriteLine(runPipelineResult);
Run runInfo = null;
do
{
// GET run status
runInfo = await
$"https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs/{runPipelineResult.Id}?api-version=6.0-preview.1"
.WithHeader("Authorization", AuthorizationHeaderValue())
.GetJsonAsync<Run>();
Console.WriteLine(runInfo.State);
await Task.Delay(TimeSpan.FromSeconds(20));
} while (runInfo.State != "completed");
public class Resources
{
public Repositories repositories { get; set; }
}
public class Repositories
{
public Self1 self { get; set; }
}
public class Self1
{
public Repository repository { get; set; }
public string refName { get; set; }
public string version { get; set; }
}
public class Repository
{
public string fullName { get; set; }
public Connection connection { get; set; }
public string type { get; set; }
}
public class Connection
{
public string id { get; set; }
}
namespace Playground
{
//List of pipelines DTO
public record ListOfPipelines(int Count, Pipeline[] Value);
public record Pipeline(
ReferenceLinks Links,
string Url,
int Id,
int Revision,
string Name,
string Folder
);
public record Self(string Href);
public record Web(string Href);
// run pipeline response
public record Run
(
ReferenceLinks Links,
Pipeline Pipeline,
string State,
DateTime CreatedDate,
string Url,
Resources Resources,
string FinalYaml,
int Id,
object Name
);
public record ReferenceLinks(
Self Self,
Web Web,
Web Pipelineweb,
Web Pipeline
);
}
|
using Flurl.Http;
using Playground;
string AuthorizationHeaderValue()
{
var personalAccessToken = File.ReadAllText("C:\\Users\\HYPERBOOK\\Documents\\__KEYS\\azure-pipelines.txt");
var base64String = Convert.ToBase64String(
System.Text.Encoding.ASCII.GetBytes(
$":{personalAccessToken}"));
return $"Basic {base64String}";
}
var organization = "grzesiekgalezowski";
var project = "grzesiekgalezowski";
// LIST of pipelines request
var jsonAsync = await $"https://dev.azure.com/{organization}/{project}/_apis/pipelines?api-version=7.1-preview.1"
.GetJsonAsync<ListOfPipelines>();
var pipelineIds = jsonAsync.Value.Select(p => p.Id);
Console.WriteLine(string.Join(',', pipelineIds));
//RUN pipeline
// requires sign in
var pipelineId = pipelineIds.First();
var runPipelineJson = await $"https://dev.azure.com/{organization}/{project}/_apis/pipelines/{pipelineId}/runs?api-version=7.1-preview.1"
.WithHeader("Authorization", AuthorizationHeaderValue())
.PostJsonAsync(new
{
previewRun = true
});
var runPipelineResult = await runPipelineJson.GetJsonAsync<RunPipelineResult>();
Console.WriteLine(runPipelineResult);
namespace Playground
{
//List of pipelines DTO
public record ListOfPipelines(int Count, Pipeline[] Value);
public record Pipeline(
ReferenceLinks Links,
string Url,
int Id,
int Revision,
string Name,
string Folder
);
public record ReferenceLinks(Self Self, Web Web);
public record Self(string Href);
public record Web(string Href);
// run pipeline response
public class RunPipelineResult
{
public RunPipelineLinks Links { get; set; }
public Pipeline Pipeline { get; set; }
public string State { get; set; }
public string Url { get; set; }
public string FinalYaml { get; set; }
public int Id { get; set; }
public object Name { get; set; }
}
public class RunPipelineLinks
{
public Self Self { get; set; }
public Web Web { get; set; }
public Web Pipelineweb { get; set; }
public Web Pipeline { get; set; }
}
}
|
mit
|
C#
|
48c525f50f5712ce74343cfd480e31e5553b092f
|
Bump version number
|
CSIS/EnrollmentStation
|
EnrollmentStation/Properties/AssemblyInfo.cs
|
EnrollmentStation/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EnrollmentStation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EnrollmentStation")]
[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("80874570-42c0-4473-8dc5-bea5af3e110e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.1.0")]
[assembly: AssemblyFileVersion("0.3.1.0")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EnrollmentStation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EnrollmentStation")]
[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("80874570-42c0-4473-8dc5-bea5af3e110e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
|
mit
|
C#
|
80fc10e23efa7e3eba4450291b1555179e2002f1
|
Remove excess code
|
wbap/hackathon-2017-sample,wbap/hackathon-2017-sample,wbap/hackathon-2017-sample,wbap/hackathon-2017-sample
|
environment/Assets/Scripts/OneDimTask2.cs
|
environment/Assets/Scripts/OneDimTask2.cs
|
using UnityEngine;
public class OneDimTask2 : OneDimTaskBase {
public GameObject reward;
bool rewardShown = false;
public override string Name() { return "One Dimensional Task 2"; }
void Update() {
float z = agent.transform.position.z;
if(11.5F <= z && z <= 15.5F) {
if(!rewardShown) {
rewardCount += 1;
Reward.Add(2.0F);
GameObject rewardObj = (GameObject)GameObject.Instantiate(
reward, new Vector3(0.0F, 0.5F, 23.0F), Quaternion.identity
);
rewardObj.transform.parent = transform;
rewardShown = true;
}
}
}
}
|
using UnityEngine;
public class OneDimTask2 : OneDimTaskBase {
public GameObject reward;
bool rewardShown = false;
public override string Name() { return "One Dimensional Task 2"; }
public override bool Success() {
return rewardCount > 1;
}
void Update() {
float z = agent.transform.position.z;
if(11.5F <= z && z <= 15.5F) {
if(!rewardShown) {
rewardCount += 1;
Reward.Add(2.0F);
GameObject rewardObj = (GameObject)GameObject.Instantiate(
reward, new Vector3(0.0F, 0.5F, 23.0F), Quaternion.identity
);
rewardObj.transform.parent = transform;
rewardShown = true;
}
}
}
}
|
apache-2.0
|
C#
|
45914cf0542e456ef6149a34f03d52286948e52e
|
Update ModuleHelpData - use var as standard, add Ordinal comparison type
|
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
|
Modix.Services/CommandHelp/ModuleHelpData.cs
|
Modix.Services/CommandHelp/ModuleHelpData.cs
|
using System.Collections.Generic;
using System.Linq;
using Discord.Commands;
using Humanizer;
namespace Modix.Services.CommandHelp
{
using System;
public class ModuleHelpData
{
public string Name { get; set; }
public string Summary { get; set; }
public List<CommandHelpData> Commands { get; set; } = new List<CommandHelpData>();
public static ModuleHelpData FromModuleInfo(ModuleInfo module)
{
var moduleName = module.Name;
var suffixPosition = moduleName.IndexOf("Module", StringComparison.Ordinal);
if (suffixPosition > -1)
{
moduleName = module.Name.Substring(0, suffixPosition).Humanize();
}
var ret = new ModuleHelpData
{
Name = moduleName,
Summary = string.IsNullOrWhiteSpace(module.Summary) ? "No Summary" : module.Summary
};
foreach (var command in module.Commands)
{
if (command.Preconditions.Any(precon => precon is RequireOwnerAttribute) ||
command.Attributes.Any(attr => attr is HiddenFromHelpAttribute))
{
continue;
}
ret.Commands.AddRange(CommandHelpData.FromCommandInfo(command));
}
return ret;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Discord.Commands;
using Humanizer;
namespace Modix.Services.CommandHelp
{
public class ModuleHelpData
{
public string Name { get; set; }
public string Summary { get; set; }
public List<CommandHelpData> Commands { get; set; } = new List<CommandHelpData>();
public static ModuleHelpData FromModuleInfo(ModuleInfo module)
{
string moduleName = module.Name;
int suffixPosition = moduleName.IndexOf("Module");
if (suffixPosition > -1)
{
moduleName = module.Name.Substring(0, suffixPosition).Humanize();
}
var ret = new ModuleHelpData
{
Name = moduleName,
Summary = string.IsNullOrWhiteSpace(module.Summary) ? "No Summary" : module.Summary
};
foreach (var command in module.Commands)
{
if (command.Preconditions.Any(precon => precon is RequireOwnerAttribute) ||
command.Attributes.Any(attr => attr is HiddenFromHelpAttribute))
{
continue;
}
ret.Commands.AddRange(CommandHelpData.FromCommandInfo(command));
}
return ret;
}
}
}
|
mit
|
C#
|
faa40d4b0120e74ca31cfca6bdb6d27d41bbd4ab
|
Convert XmlLicenseTransformTest
|
krk/corefx,gkhanna79/corefx,twsouthwick/corefx,alexperovich/corefx,marksmeltzer/corefx,JosephTremoulet/corefx,billwert/corefx,ericstj/corefx,wtgodbe/corefx,Petermarcu/corefx,stone-li/corefx,rahku/corefx,Ermiar/corefx,gkhanna79/corefx,stephenmichaelf/corefx,rubo/corefx,richlander/corefx,mazong1123/corefx,ViktorHofer/corefx,ViktorHofer/corefx,marksmeltzer/corefx,marksmeltzer/corefx,rahku/corefx,yizhang82/corefx,YoupHulsebos/corefx,mmitche/corefx,Ermiar/corefx,billwert/corefx,seanshpark/corefx,billwert/corefx,ravimeda/corefx,DnlHarvey/corefx,shimingsg/corefx,billwert/corefx,BrennanConroy/corefx,stone-li/corefx,nbarbettini/corefx,stone-li/corefx,stephenmichaelf/corefx,JosephTremoulet/corefx,shimingsg/corefx,mmitche/corefx,axelheer/corefx,alexperovich/corefx,cydhaselton/corefx,ravimeda/corefx,MaggieTsang/corefx,ravimeda/corefx,krk/corefx,ViktorHofer/corefx,krytarowski/corefx,krytarowski/corefx,twsouthwick/corefx,twsouthwick/corefx,yizhang82/corefx,mazong1123/corefx,rjxby/corefx,rahku/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,weltkante/corefx,rubo/corefx,nbarbettini/corefx,wtgodbe/corefx,elijah6/corefx,billwert/corefx,stone-li/corefx,the-dwyer/corefx,ptoonen/corefx,krk/corefx,tijoytom/corefx,alexperovich/corefx,seanshpark/corefx,JosephTremoulet/corefx,ptoonen/corefx,dhoehna/corefx,mmitche/corefx,elijah6/corefx,elijah6/corefx,dhoehna/corefx,yizhang82/corefx,krytarowski/corefx,cydhaselton/corefx,parjong/corefx,DnlHarvey/corefx,cydhaselton/corefx,parjong/corefx,Petermarcu/corefx,YoupHulsebos/corefx,ravimeda/corefx,seanshpark/corefx,parjong/corefx,nchikanov/corefx,ericstj/corefx,richlander/corefx,Petermarcu/corefx,stone-li/corefx,Petermarcu/corefx,nchikanov/corefx,mazong1123/corefx,the-dwyer/corefx,jlin177/corefx,YoupHulsebos/corefx,the-dwyer/corefx,YoupHulsebos/corefx,zhenlan/corefx,rahku/corefx,stephenmichaelf/corefx,fgreinacher/corefx,the-dwyer/corefx,rahku/corefx,yizhang82/corefx,marksmeltzer/corefx,ViktorHofer/corefx,Jiayili1/corefx,DnlHarvey/corefx,alexperovich/corefx,Ermiar/corefx,Ermiar/corefx,yizhang82/corefx,dotnet-bot/corefx,MaggieTsang/corefx,cydhaselton/corefx,dotnet-bot/corefx,dhoehna/corefx,tijoytom/corefx,weltkante/corefx,axelheer/corefx,the-dwyer/corefx,wtgodbe/corefx,DnlHarvey/corefx,richlander/corefx,JosephTremoulet/corefx,cydhaselton/corefx,dhoehna/corefx,ptoonen/corefx,cydhaselton/corefx,rjxby/corefx,jlin177/corefx,dotnet-bot/corefx,krk/corefx,the-dwyer/corefx,zhenlan/corefx,dotnet-bot/corefx,dhoehna/corefx,YoupHulsebos/corefx,weltkante/corefx,ravimeda/corefx,parjong/corefx,marksmeltzer/corefx,rahku/corefx,yizhang82/corefx,Jiayili1/corefx,ericstj/corefx,rubo/corefx,Jiayili1/corefx,richlander/corefx,tijoytom/corefx,wtgodbe/corefx,MaggieTsang/corefx,ptoonen/corefx,parjong/corefx,nchikanov/corefx,Jiayili1/corefx,the-dwyer/corefx,shimingsg/corefx,axelheer/corefx,Jiayili1/corefx,DnlHarvey/corefx,elijah6/corefx,nchikanov/corefx,ptoonen/corefx,rjxby/corefx,zhenlan/corefx,tijoytom/corefx,jlin177/corefx,stephenmichaelf/corefx,dotnet-bot/corefx,rjxby/corefx,fgreinacher/corefx,twsouthwick/corefx,tijoytom/corefx,Ermiar/corefx,shimingsg/corefx,ericstj/corefx,richlander/corefx,krk/corefx,mmitche/corefx,fgreinacher/corefx,parjong/corefx,YoupHulsebos/corefx,seanshpark/corefx,nbarbettini/corefx,ptoonen/corefx,jlin177/corefx,rjxby/corefx,ericstj/corefx,weltkante/corefx,mazong1123/corefx,seanshpark/corefx,twsouthwick/corefx,BrennanConroy/corefx,alexperovich/corefx,mazong1123/corefx,fgreinacher/corefx,gkhanna79/corefx,stone-li/corefx,seanshpark/corefx,ericstj/corefx,gkhanna79/corefx,mmitche/corefx,yizhang82/corefx,Ermiar/corefx,DnlHarvey/corefx,JosephTremoulet/corefx,Petermarcu/corefx,gkhanna79/corefx,parjong/corefx,Petermarcu/corefx,ViktorHofer/corefx,krytarowski/corefx,MaggieTsang/corefx,Petermarcu/corefx,krytarowski/corefx,rubo/corefx,marksmeltzer/corefx,axelheer/corefx,krk/corefx,mazong1123/corefx,billwert/corefx,dhoehna/corefx,alexperovich/corefx,zhenlan/corefx,richlander/corefx,axelheer/corefx,YoupHulsebos/corefx,mmitche/corefx,jlin177/corefx,rahku/corefx,wtgodbe/corefx,Jiayili1/corefx,mmitche/corefx,nbarbettini/corefx,jlin177/corefx,BrennanConroy/corefx,elijah6/corefx,gkhanna79/corefx,rubo/corefx,stephenmichaelf/corefx,alexperovich/corefx,dhoehna/corefx,shimingsg/corefx,stephenmichaelf/corefx,marksmeltzer/corefx,ptoonen/corefx,jlin177/corefx,MaggieTsang/corefx,rjxby/corefx,richlander/corefx,MaggieTsang/corefx,tijoytom/corefx,MaggieTsang/corefx,nbarbettini/corefx,zhenlan/corefx,tijoytom/corefx,cydhaselton/corefx,gkhanna79/corefx,zhenlan/corefx,axelheer/corefx,rjxby/corefx,nchikanov/corefx,Ermiar/corefx,ravimeda/corefx,krytarowski/corefx,nbarbettini/corefx,weltkante/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,twsouthwick/corefx,zhenlan/corefx,nbarbettini/corefx,ravimeda/corefx,krytarowski/corefx,billwert/corefx,elijah6/corefx,weltkante/corefx,twsouthwick/corefx,DnlHarvey/corefx,mazong1123/corefx,nchikanov/corefx,elijah6/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,stephenmichaelf/corefx,nchikanov/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,krk/corefx,Jiayili1/corefx,weltkante/corefx,stone-li/corefx,wtgodbe/corefx,seanshpark/corefx
|
src/System.Security.Cryptography.Xml/tests/XmlLicenseTransformTest.cs
|
src/System.Security.Cryptography.Xml/tests/XmlLicenseTransformTest.cs
|
//
// XmlLicenseTransformTest.cs - Test Cases for XmlLicenseTransform
//
// Author:
// original:
// Sebastien Pouliot <sebastien@ximian.com>
// Aleksey Sanin (aleksey@aleksey.com)
// this file:
// Gert Driesen <drieseng@users.sourceforge.net>
//
// (C) 2003 Aleksey Sanin (aleksey@aleksey.com)
// (C) 2004 Novell (http://www.novell.com)
// (C) 2008 Gert Driesen
//
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
using System.Xml;
using Xunit;
namespace System.Security.Cryptography.Xml.Tests
{
public class UnprotectedXmlLicenseTransform : XmlLicenseTransform
{
public XmlNodeList UnprotectedGetInnerXml()
{
return base.GetInnerXml();
}
}
public class XmlLicenseTransformTest
{
private UnprotectedXmlLicenseTransform transform;
public XmlLicenseTransformTest()
{
transform = new UnprotectedXmlLicenseTransform();
}
[Fact] // ctor ()
public void Constructor1()
{
Assert.Equal("urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform",
transform.Algorithm);
Assert.Null(transform.Decryptor);
Type[] input = transform.InputTypes;
Assert.Equal(1, input.Length);
Assert.Equal(typeof(XmlDocument), input[0]);
Type[] output = transform.OutputTypes;
Assert.Equal(1, output.Length);
Assert.Equal(typeof(XmlDocument), output[0]);
}
[Fact]
public void InputTypes()
{
// property does not return a clone
transform.InputTypes[0] = null;
Assert.Null(transform.InputTypes[0]);
// it's not a static array
transform = new UnprotectedXmlLicenseTransform();
Assert.NotNull(transform.InputTypes[0]);
}
[Fact]
public void GetInnerXml()
{
XmlNodeList xnl = transform.UnprotectedGetInnerXml();
Assert.Null(xnl);
}
[Fact]
public void OutputTypes()
{
// property does not return a clone
transform.OutputTypes[0] = null;
Assert.Null(transform.OutputTypes[0]);
// it's not a static array
transform = new UnprotectedXmlLicenseTransform();
Assert.NotNull(transform.OutputTypes[0]);
}
}
}
|
//
// XmlLicenseTransformTest.cs - NUnit Test Cases for XmlLicenseTransform
//
// Author:
// original:
// Sebastien Pouliot <sebastien@ximian.com>
// Aleksey Sanin (aleksey@aleksey.com)
// this file:
// Gert Driesen <drieseng@users.sourceforge.net>
//
// (C) 2003 Aleksey Sanin (aleksey@aleksey.com)
// (C) 2004 Novell (http://www.novell.com)
// (C) 2008 Gert Driesen
//
using System.Xml;
namespace System.Security.Cryptography.Xml.Tests {
public class UnprotectedXmlLicenseTransform : XmlLicenseTransform {
public XmlNodeList UnprotectedGetInnerXml ()
{
return base.GetInnerXml ();
}
}
[TestFixture]
public class XmlLicenseTransformTest {
private UnprotectedXmlLicenseTransform transform;
[SetUp]
public void SetUp ()
{
transform = new UnprotectedXmlLicenseTransform ();
}
[Test] // ctor ()
public void Constructor1 ()
{
Assert.AreEqual ("urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform",
transform.Algorithm, "Algorithm");
Assert.IsNull (transform.Decryptor, "Decryptor");
Type[] input = transform.InputTypes;
Assert.AreEqual (1, input.Length, "Input #");
Assert.AreEqual (typeof (XmlDocument), input [0], "Input Type");
Type[] output = transform.OutputTypes;
Assert.AreEqual (1, output.Length, "Output #");
Assert.AreEqual (typeof (XmlDocument), output [0], "Output Type");
}
[Test]
public void InputTypes ()
{
// property does not return a clone
transform.InputTypes [0] = null;
Assert.IsNull (transform.InputTypes [0]);
// it's not a static array
transform = new UnprotectedXmlLicenseTransform ();
Assert.IsNotNull (transform.InputTypes [0]);
}
[Test]
public void GetInnerXml ()
{
XmlNodeList xnl = transform.UnprotectedGetInnerXml ();
Assert.IsNull (xnl, "Default InnerXml");
}
[Test]
public void OutputTypes ()
{
// property does not return a clone
transform.OutputTypes [0] = null;
Assert.IsNull (transform.OutputTypes [0], "#1");
// it's not a static array
transform = new UnprotectedXmlLicenseTransform ();
Assert.IsNotNull (transform.OutputTypes [0], "#2");
}
}
}
|
mit
|
C#
|
94683d2743ba66ab386e039ca958b1a762d640c0
|
Update MainWindow
|
HunterStanton/SOE-SRAM-Editor
|
SOE_SRAM_Editor/Forms/MainWindow.Designer.cs
|
SOE_SRAM_Editor/Forms/MainWindow.Designer.cs
|
namespace SOE_SRAM_Editor
{
partial class MainWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// MainWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(616, 364);
this.Name = "MainWindow";
this.Text = "Secret of Evermore SRAM Editor - No ROM Loaded";
this.ResumeLayout(false);
}
#endregion
}
}
|
namespace SOE_SRAM_Editor
{
partial class MainWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// MainWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(616, 364);
this.Name = "MainWindow";
this.Text = "Secret of Evermore SRAM Editor";
this.ResumeLayout(false);
}
#endregion
}
}
|
mit
|
C#
|
8ca8893c8e4eb8f8d9c223131ef79b037c291fb1
|
Remove unused code
|
benjamin-hodgson/Pidgin
|
Pidgin/ExpectedUtil.cs
|
Pidgin/ExpectedUtil.cs
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Pidgin
{
internal static class ExpectedUtil
{
public static ImmutableSortedSet<T> Union<T>(ref PooledList<ImmutableSortedSet<T>> input)
{
var builder = ImmutableSortedSet.CreateBuilder<T>();
for (var i = 0; i < input.Count; i++)
{
builder.UnionWith(input[i]);
}
return builder.ToImmutable();
}
}
}
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Pidgin
{
internal static class ExpectedUtil
{
public static ImmutableSortedSet<T> Union<T>(params ImmutableSortedSet<T>[] input)
=> Union(input.AsEnumerable());
public static ImmutableSortedSet<T> Union<T>(IEnumerable<ImmutableSortedSet<T>> input)
{
var builder = ImmutableSortedSet.CreateBuilder<T>();
foreach (var set in input)
{
builder.UnionWith(set);
}
return builder.ToImmutable();
}
public static ImmutableSortedSet<T> Union<T>(ref PooledList<ImmutableSortedSet<T>> input)
{
var builder = ImmutableSortedSet.CreateBuilder<T>();
for (var i = 0; i < input.Count; i++)
{
builder.UnionWith(input[i]);
}
return builder.ToImmutable();
}
}
}
|
mit
|
C#
|
66b5ae93fef2a6249ef2860913ee94d3e4432820
|
Add throws and doesnotthrow
|
aikeru/quack.csx,aikeru/quack.csx
|
RapidTesting/Assert.cs
|
RapidTesting/Assert.cs
|
public class Assert {
public static void IsTrue(bool exp) {
if(!exp) { throw new Exception("Expected true but was false."); }
}
public static void IsFalse(bool exp) {
if(exp) { throw new Exception("Expected false but was true."); }
}
public static void IsNull(object obj) {
if(obj != null) { throw new Exception("Expected null, but was non-null."); }
}
public static void IsNotNull(object obj) {
if(obj == null) { throw new Exception("Expected non-null, but was null."); }
}
public static void Throws(Action throwAction) {
try {
throwAction();
} catch {
return;
}
throw new Exception("Expected an exception to be thrown.");
}
public static void DoesNotThrow(Action nonThrowAction) {
try {
nonThrowAction();
} catch (Exception inner) {
throw new Exception("Expected no exception, but one was thrown.", inner);
}
}
}
|
public class Assert {
public static void IsTrue(bool exp) {
if(!exp) { throw new Exception("Expected true but was false."); }
}
public static void IsFalse(bool exp) {
if(exp) { throw new Exception("Expected false but was true."); }
}
public static void IsNull(object obj) {
if(obj != null) { throw new Exception("Expected null, but was non-null."); }
}
public static void IsNotNull(object obj) {
if(obj == null) { throw new Exception("Expected non-null, but was null."); }
}
}
|
mit
|
C#
|
f5497ba80186a58739e437fb8e138bc392f5b93d
|
fix bug
|
xuanbg/Utility
|
Utils/Entity/Region.cs
|
Utils/Entity/Region.cs
|
namespace Insight.Utils.Entity
{
/// <summary>
/// 行政区划基础数据实体类
/// </summary>
public class Region
{
/// <summary>
/// 行政区划唯一ID
/// </summary>
public string id { get; set; }
/// <summary>
/// 父级ID
/// </summary>
public string parentId { get; set; }
/// <summary>
/// 编码
/// </summary>
public string code { get; set; }
/// <summary>
/// 名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 简称
/// </summary>
public string alias { get; set; }
}
}
|
namespace Insight.Utils.Entity
{
/// <summary>
/// 行政区划基础数据实体类
/// </summary>
public class Region
{
/// <summary>
/// 行政区划唯一ID
/// </summary>
public string id { get; set; }
/// <summary>
/// 父级ID
/// </summary>
public string parentId { get; set; }
/// <summary>
/// 编码
/// </summary>
public int code { get; set; }
/// <summary>
/// 名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 简称
/// </summary>
public string alias { get; set; }
}
}
|
mit
|
C#
|
095ba54bc94b7602484c3105c3724de100def981
|
Fix showing dialog centred to another modal dialog
|
PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto
|
Source/Eto.Platform.Wpf/Forms/DialogHandler.cs
|
Source/Eto.Platform.Wpf/Forms/DialogHandler.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eto.Forms;
using sw = System.Windows;
using swc = System.Windows.Controls;
using Eto.Platform.Wpf.Forms.Controls;
namespace Eto.Platform.Wpf.Forms
{
public class DialogHandler : WpfWindow<sw.Window, Dialog>, IDialog
{
Button defaultButton;
Button abortButton;
public DialogHandler ()
{
Control = new sw.Window { ShowInTaskbar = false };
Setup ();
Resizable = false;
}
public override bool Resizable
{
get { return Control.ResizeMode == sw.ResizeMode.CanResize || Control.ResizeMode == sw.ResizeMode.CanResizeWithGrip; }
set
{
if (value) Control.ResizeMode = sw.ResizeMode.CanResizeWithGrip;
else Control.ResizeMode = sw.ResizeMode.NoResize;
}
}
public DialogResult ShowDialog (Control parent)
{
var parentWindow = parent.ParentWindow;
if (parentWindow != null)
{
var owner = ((IWpfWindow)parentWindow.Handler).Control;
Control.Owner = owner;
if (owner.Owner == null)
Control.WindowStartupLocation = sw.WindowStartupLocation.CenterOwner;
else
{
Control.WindowStartupLocation = sw.WindowStartupLocation.Manual;
Control.SourceInitialized += HandleSourceInitialized;
}
}
Control.ShowDialog ();
return Widget.DialogResult;
}
void HandleSourceInitialized (object sender, EventArgs e)
{
var owner = this.Control.Owner;
Control.Left = owner.Left + (owner.ActualWidth - Control.Width) / 2;
Control.Top = owner.Top + (owner.ActualHeight - Control.Height) / 2;
Control.SourceInitialized -= HandleSourceInitialized;
}
public Button DefaultButton
{
get { return defaultButton; }
set
{
if (defaultButton != null) {
var handler = defaultButton.Handler as ButtonHandler;
handler.Control.IsDefault = false;
}
defaultButton = value;
if (defaultButton != null) {
var handler = defaultButton.Handler as ButtonHandler;
handler.Control.IsDefault = true;
}
}
}
public Button AbortButton
{
get { return abortButton; }
set
{
if (abortButton != null) {
var handler = abortButton.Handler as ButtonHandler;
handler.Control.IsCancel = false;
}
abortButton = value;
if (abortButton != null) {
var handler = abortButton.Handler as ButtonHandler;
handler.Control.IsCancel = true;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Eto.Forms;
using sw = System.Windows;
using swc = System.Windows.Controls;
using Eto.Platform.Wpf.Forms.Controls;
namespace Eto.Platform.Wpf.Forms
{
public class DialogHandler : WpfWindow<sw.Window, Dialog>, IDialog
{
Button defaultButton;
Button abortButton;
public DialogHandler ()
{
Control = new sw.Window { ShowInTaskbar = false };
Setup ();
Resizable = false;
}
public override bool Resizable
{
get { return Control.ResizeMode == sw.ResizeMode.CanResize || Control.ResizeMode == sw.ResizeMode.CanResizeWithGrip; }
set
{
if (value) Control.ResizeMode = sw.ResizeMode.CanResizeWithGrip;
else Control.ResizeMode = sw.ResizeMode.NoResize;
}
}
public DialogResult ShowDialog (Control parent)
{
var parentWindow = parent.ParentWindow;
if (parentWindow != null)
Control.Owner = ((IWpfWindow)parentWindow.Handler).Control;
Control.WindowStartupLocation = sw.WindowStartupLocation.CenterOwner;
Control.ShowDialog ();
return Widget.DialogResult;
}
public Button DefaultButton
{
get { return defaultButton; }
set
{
if (defaultButton != null) {
var handler = defaultButton.Handler as ButtonHandler;
handler.Control.IsDefault = false;
}
defaultButton = value;
if (defaultButton != null) {
var handler = defaultButton.Handler as ButtonHandler;
handler.Control.IsDefault = true;
}
}
}
public Button AbortButton
{
get { return abortButton; }
set
{
if (abortButton != null) {
var handler = abortButton.Handler as ButtonHandler;
handler.Control.IsCancel = false;
}
abortButton = value;
if (abortButton != null) {
var handler = abortButton.Handler as ButtonHandler;
handler.Control.IsCancel = true;
}
}
}
}
}
|
bsd-3-clause
|
C#
|
5058fa3bc28c74be80afec60ab3fee686b5ec25e
|
Move IsDialogOpen = false outside
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/ViewModels/Dialogs/DialogScreenViewModel.cs
|
WalletWasabi.Fluent/ViewModels/Dialogs/DialogScreenViewModel.cs
|
using System;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
public class DialogScreenViewModel : ViewModelBase, IScreen
{
private bool _isClosing;
private bool _isDialogOpen;
public DialogScreenViewModel()
{
Observable.FromEventPattern(Router.NavigationStack, nameof(Router.NavigationStack.CollectionChanged))
.Subscribe(_ =>
{
if (!_isClosing)
{
IsDialogOpen = Router.NavigationStack.Count >= 1;
}
});
this.WhenAnyValue(x => x.IsDialogOpen)
.Skip(1) // Skip the initial value change (which is false).
.DistinctUntilChanged()
.Subscribe(x =>
{
if (!x && !_isClosing)
{
// Reset navigation when Dialog is using IScreen for navigation instead of the default IDialogHost.
Close();
}
});
}
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public bool IsDialogOpen
{
get => _isDialogOpen;
set => this.RaiseAndSetIfChanged(ref _isDialogOpen, value);
}
public void Close()
{
if (!_isClosing)
{
_isClosing = true;
if (Router.NavigationStack.Count >= 1)
{
foreach (var routable in Router.NavigationStack)
{
// Close all dialogs so the awaited tasks can complete.
// - DialogViewModelBase.ShowDialogAsync()
// - DialogViewModelBase.GetDialogResultAsync()
if (routable is DialogViewModelBase dialog)
{
dialog.IsDialogOpen = false;
}
}
Router.NavigationStack.Clear();
}
IsDialogOpen = false;
_isClosing = false;
}
}
}
}
|
using System;
using System.Reactive;
using System.Reactive.Linq;
using ReactiveUI;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Fluent.ViewModels.Dialogs
{
public class DialogScreenViewModel : ViewModelBase, IScreen
{
private bool _isClosing;
private bool _isDialogOpen;
public DialogScreenViewModel()
{
Observable.FromEventPattern(Router.NavigationStack, nameof(Router.NavigationStack.CollectionChanged))
.Subscribe(_ =>
{
if (!_isClosing)
{
IsDialogOpen = Router.NavigationStack.Count >= 1;
}
});
this.WhenAnyValue(x => x.IsDialogOpen)
.Skip(1) // Skip the initial value change (which is false).
.DistinctUntilChanged()
.Subscribe(x =>
{
if (!x && !_isClosing)
{
// Reset navigation when Dialog is using IScreen for navigation instead of the default IDialogHost.
Close();
}
});
}
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public bool IsDialogOpen
{
get => _isDialogOpen;
set => this.RaiseAndSetIfChanged(ref _isDialogOpen, value);
}
public void Close()
{
if (!_isClosing)
{
_isClosing = true;
if (Router.NavigationStack.Count >= 1)
{
foreach (var routable in Router.NavigationStack)
{
// Close all dialogs so the awaited tasks can complete.
// - DialogViewModelBase.ShowDialogAsync()
// - DialogViewModelBase.GetDialogResultAsync()
if (routable is DialogViewModelBase dialog)
{
dialog.IsDialogOpen = false;
}
}
Router.NavigationStack.Clear();
IsDialogOpen = false;
}
_isClosing = false;
}
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.