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 |
|---|---|---|---|---|---|---|---|---|
50690013015f15f27bedb167891ccc38023ab49c | add extension | luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate | src/Abp/ObjectComparators/ObjectComparatorExtensions.cs | src/Abp/ObjectComparators/ObjectComparatorExtensions.cs | using Abp.Extensions;
using System;
namespace Abp.ObjectComparators
{
public static class ObjectComparatorExtensions
{
public static bool IsNullOrEmpty<T1, T2>(this ObjectComparatorCondition<T1, T2> objectComparator) where T2 : Enum
{
return objectComparator == null;
}
public static bool IsNullOrEmpty<T>(this ObjectComparatorCondition<T> objectComparator)
{
return objectComparator == null || objectComparator.CompareType.IsNullOrWhiteSpace();
}
}
}
| mit | C# | |
20458d4b4636defc3e26ddbf66fcf31f90c1ea28 | Add InvalidDataException | killnine/s7netplus | S7.Net/InvalidDataException.cs | S7.Net/InvalidDataException.cs | using System;
namespace S7.Net
{
#if NET_FULL
[Serializable]
#endif
public class InvalidDataException : Exception
{
public byte[] ReceivedData { get; }
public int ErrorIndex { get; }
public byte ExpectedValue { get; }
public InvalidDataException(string message, byte[] receivedData, int errorIndex, byte expectedValue)
: base(FormatMessage(message, receivedData, errorIndex, expectedValue))
{
ReceivedData = receivedData;
ErrorIndex = errorIndex;
ExpectedValue = expectedValue;
}
#if NET_FULL
protected InvalidDataException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context)
{
ReceivedData = (byte[]) info.GetValue(nameof(ReceivedData), typeof(byte[]));
ErrorIndex = info.GetInt32(nameof(ErrorIndex));
ExpectedValue = info.GetByte(nameof(ExpectedValue));
}
#endif
private static string FormatMessage(string message, byte[] receivedData, int errorIndex, byte expectedValue)
{
if (errorIndex >= receivedData.Length)
throw new ArgumentOutOfRangeException(nameof(errorIndex),
$"{nameof(errorIndex)} {errorIndex} is outside the bounds of {nameof(receivedData)} with length {receivedData.Length}.");
return $"{message} Invalid data received. Expected '{expectedValue}' at index {errorIndex}, " +
$"but received {receivedData[errorIndex]}. See the {nameof(ReceivedData)} property " +
"for the full message received.";
}
}
} | mit | C# | |
0076dbc16a2cb30e4d5f1a96d3e139b5523f0ea4 | Add missing file | ilovepi/Compiler,ilovepi/Compiler | compiler/middleend/ir/SsaVariable.cs | compiler/middleend/ir/SsaVariable.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework.Internal;
namespace compiler.middleend.ir
{
class SsaVariable
{
public int UuId { get; set; }
public Instruction Location { get; set; }
/// <summary>
/// Previous Instruction
/// </summary>
public Instruction Prev { get; set; }
public string Name { get; set; }
public SsaVariable()
{
Name = null;
Prev = null;
Location = null;
UuId = 0;
}
public SsaVariable(int puuid, Instruction plocation, Instruction pPrev, string pName)
{
Name = pName;
Prev = pPrev;
Location = plocation;
UuId = puuid;
}
public override string ToString()
{
return Name + Location.Num;
}
}
}
| mit | C# | |
58e66cb1e27bd76fa56aa2507801b79df9ba7511 | Add CueTextBox Control | stefan-baumann/AeroSuite | AeroSuite/Controls/CueTextBox.cs | AeroSuite/Controls/CueTextBox.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace AeroSuite.Controls
{
/// <summary>
/// A TextBox with cue banner support.
/// </summary>
/// <remarks>
/// A cue banner is the text that is shown when the TextBox is empty.
/// </remarks>
[DesignerCategory("Code")]
[DisplayName("Aero TreeView")]
[Description("A TextBox with cue banner support.")]
[ToolboxItem(true)]
[ToolboxBitmap(typeof(TextBox))]
public class CueTextBox
: TextBox
{
private const int EM_SETCUEBANNER = 0x1501;
/// <summary>
/// Initializes a new instance of the <see cref="CueTextBox"/> class.
/// </summary>
public CueTextBox()
{
this.UpdateCue();
}
private string cue = string.Empty;
/// <summary>
/// The text shown on the Cue Banner.
/// </summary>
/// <value>
/// The cue.
/// </value>
[Category("Appearance")]
[Description("The text shown on the Cue Banner.")]
public string Cue
{
get
{
return this.cue;
}
set
{
this.cue = value;
this.UpdateCue();
}
}
private bool retainCue = false;
/// <summary>
/// Determines if the cue banner is shown even when the textbox is focused.
/// </summary>
/// <value>
/// The cue.
/// </value>
[Category("Appearance")]
[Description("Determines if the cue banner is shown even when the textbox is focused.")]
public bool RetainCue
{
get
{
return this.retainCue;
}
set
{
this.retainCue = value;
this.UpdateCue();
}
}
/// <summary>
/// Updates the cue.
/// </summary>
private void UpdateCue()
{
if (PlatformHelper.XpOrHigher)
{
if (this.IsHandleCreated && this.cue != null)
{
NativeMethods.SendMessage(this.Handle, EM_SETCUEBANNER, this.retainCue ? new IntPtr(1) : IntPtr.Zero, this.cue);
}
}
}
/// <summary>
/// Raises the <see cref="E:HandleCreated" /> event.
/// </summary>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
this.UpdateCue();
}
}
}
| mit | C# | |
502376f17e370e668acf52f751f9b6ef2f9b2b6d | Add missing file to repository | Therzok/nunit,Therzok/nunit,NikolayPianikov/nunit,jeremymeng/nunit,ArsenShnurkov/nunit,nunit/nunit,dicko2/nunit,ChrisMaddock/nunit,akoeplinger/nunit,akoeplinger/nunit,Suremaker/nunit,elbaloo/nunit,mikkelbu/nunit,passaro/nunit,Green-Bug/nunit,OmicronPersei/nunit,zmaruo/nunit,acco32/nunit,cPetru/nunit-params,jhamm/nunit,nunit/nunit,appel1/nunit,ArsenShnurkov/nunit,jhamm/nunit,jadarnel27/nunit,NarohLoyahl/nunit,pcalin/nunit,dicko2/nunit,michal-franc/nunit,modulexcite/nunit,danielmarbach/nunit,acco32/nunit,JohanO/nunit,cPetru/nunit-params,jnm2/nunit,agray/nunit,JohanO/nunit,jhamm/nunit,modulexcite/nunit,JustinRChou/nunit,dicko2/nunit,nivanov1984/nunit,ggeurts/nunit,agray/nunit,jeremymeng/nunit,modulexcite/nunit,NikolayPianikov/nunit,pcalin/nunit,Green-Bug/nunit,elbaloo/nunit,jnm2/nunit,passaro/nunit,michal-franc/nunit,mjedrzejek/nunit,NarohLoyahl/nunit,passaro/nunit,zmaruo/nunit,mjedrzejek/nunit,mikkelbu/nunit,pcalin/nunit,pflugs30/nunit,Green-Bug/nunit,ChrisMaddock/nunit,jadarnel27/nunit,pflugs30/nunit,Suremaker/nunit,danielmarbach/nunit,JustinRChou/nunit,NarohLoyahl/nunit,michal-franc/nunit,JohanO/nunit,danielmarbach/nunit,agray/nunit,acco32/nunit,OmicronPersei/nunit,zmaruo/nunit,nivanov1984/nunit,appel1/nunit,ArsenShnurkov/nunit,akoeplinger/nunit,Therzok/nunit,elbaloo/nunit,jeremymeng/nunit,ggeurts/nunit | src/framework/Api/ISetRunState.cs | src/framework/Api/ISetRunState.cs | // ***********************************************************************
// Copyright (c) 2010 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;
namespace NUnit.Framework.Api
{
public interface ISetRunState
{
RunState GetRunState();
string GetReason();
}
}
| mit | C# | |
76bcfbc81987a5502797528e7080f283ba24bd02 | Fix missing files for release 3.7.4.2704 | Patagames/Pdf.Wpf | Print/PrintSizeMode.cs | Print/PrintSizeMode.cs | namespace Patagames.Pdf.Net.Controls.Wpf
{
/// <summary>
/// Represents the scaling options of the page for printing
/// </summary>
public enum PrintSizeMode
{
/// <summary>
/// Fit page
/// </summary>
Fit,
/// <summary>
/// Actual size
/// </summary>
ActualSize,
/// <summary>
/// Custom scale
/// </summary>
CustomScale
}
}
| apache-2.0 | C# | |
4dab3b6ce703052793d0b0c6c0abe4b2970f5670 | Create Problem123.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem123.cs | Problems/Problem123.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace ProjectEuler.Problems
{
class Problem123
{
Sieve s = new Sieve(10000000);
private BigInteger p(int n)
{
long pn = s.primeList[n-1];
BigInteger pn_sq = BigInteger.Pow(pn, 2);
return (BigInteger.ModPow(pn - 1, n, pn_sq) + BigInteger.ModPow(pn + 1, n, pn_sq)) % pn_sq;
}
public void Run()
{
int upper = s.primeList.Count;
BigInteger bigUpper = BigInteger.Pow(10, 10);
BigInteger remainder;
for (int i = 7000; i < upper; i++)
{
if (BigInteger.Pow(s.primeList[i], 2) > bigUpper)
{
remainder = p(i);
if (remainder > bigUpper)
{
Console.WriteLine("Rem:");
Console.WriteLine(remainder);
Console.WriteLine(i);
Console.WriteLine(s.primeList[i]);
break;
}
}
}
Console.WriteLine("Finished");
Console.ReadLine();
}
}
}
| mit | C# | |
a69df37b18e8809802f075d640f2d7f80ad999bc | add missing file. | venj/Clipy | Clipy/stringExtension.cs | Clipy/stringExtension.cs | using System;
namespace Clipy
{
public static class StringExtension
{
public static string FirstLine(this string self)
{
var lines = self.Split(new Char[]{'\n'});
return lines[0];
}
}
}
| mit | C# | |
475098109537000afd5fbb9505c35749b6eddfef | 添加rule 的单元测试的框架 | Sandwych/slipstream,Sandwych/slipstream,Sandwych/slipstream,Sandwych/slipstream | src/ObjectServer.Test/Core/RuleTest.cs | src/ObjectServer.Test/Core/RuleTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
namespace ObjectServer.Core.Test
{
[TestFixture]
public sealed class RuleTest : LocalTestCase
{
[Ignore]
public void Test_ComputeDomain()
{
}
}
}
| agpl-3.0 | C# | |
44d22390108a5f9c1f0e8449eeaea83bdfde52c4 | Add the new ILedgerIndexes interface | openchain/openchain | src/Openchain.Ledger/ILedgerIndexes.cs | src/Openchain.Ledger/ILedgerIndexes.cs | // Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Openchain.Ledger
{
public interface ILedgerIndexes
{
Task<IReadOnlyList<Record>> GetAllRecords(RecordType type, string name);
}
}
| apache-2.0 | C# | |
a52d1b0f0ad42511c2c3f05689ffb165206a54d5 | Add RSA class for encryption | MihaelaNicoleta/compression-algorithms | RSAEncryption/RSA.cs | RSAEncryption/RSA.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RSAEncryption
{
class RSA
{
public Boolean encrypt(String fileToRead)
{
return true;
}
public Boolean decrypt(String fileToRead)
{
return true;
}
| mit | C# | |
817b4f25110e4d760406283a1f6ef5bc2b0840e5 | add method for update of the transaction | paymill/paymill-net,paymill/paymill-net | UnitTest/Net/TestTransactions.cs | UnitTest/Net/TestTransactions.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PaymillWrapper;
using PaymillWrapper.Service;
using System.Collections.Generic;
using PaymillWrapper.Models;
namespace UnitTest.Net
{
[TestClass]
public class TestTransactions
{
[TestInitialize]
public void Initialize()
{
Paymill.ApiKey = "9a4129b37640ea5f62357922975842a1";
Paymill.ApiUrl = "https://api.paymill.de/v2";
}
[TestMethod]
public void UpdateTransaction()
{
TransactionService service = Paymill.GetService<TransactionService>();
Transaction transaction = new Transaction();
PaymentService paymentService = Paymill.GetService<PaymentService>();
ClientService clientService = Paymill.GetService<ClientService>();
Payment payment = paymentService.Create("098f6bcd4621d373cade4e832627b4f6");
transaction.Amount = 3500;
transaction.Currency = "EUR";
transaction.Description = "Test API c#";
transaction.Payment = payment;
transaction = service.Create(transaction);
transaction.Client = clientService.Create("javicantos22@hotmail.es", "Test API");
Assert.IsTrue(transaction.Id != String.Empty, "Create Transaction Fail");
transaction.Description = "My updated transaction description";
var updatetedClient = service.Update(transaction);
Assert.IsTrue(transaction.Description == "My updated transaction description", "Update Transaction Failed");
}
}
}
| mit | C# | |
f3ca11d77f8af4e62f4a5436a95592dfec19a46f | Fix #425 | PoESkillTree/PoESkillTree,MLanghof/PoESkillTree,EmmittJ/PoESkillTree,mihailim/PoESkillTree,l0g0sys/PoESkillTree | WPFSKillTree/Utils/RegexTools.cs | WPFSKillTree/Utils/RegexTools.cs | using System;
using System.Text.RegularExpressions;
namespace POESKillTree.Utils
{
public static class RegexTools
{
public static bool IsValidRegex(string pattern)
{
if (pattern == null) return false;
try
{
Regex.Match("", pattern);
}
catch (ArgumentException)
{
return false;
}
return true;
}
}
}
| using System;
using System.Text.RegularExpressions;
namespace POESKillTree.Utils
{
public static class RegexTools
{
public static bool IsValidRegex(string pattern)
{
if (string.IsNullOrEmpty(pattern)) return false;
try
{
Regex.Match("", pattern);
}
catch (ArgumentException)
{
return false;
}
return true;
}
}
}
| mit | C# |
3b5ab0da40058888802effb5f2577a98ade21982 | Create RemoveDuplicates.cs | michaeljwebb/Algorithm-Practice | Other/RemoveDuplicates.cs | Other/RemoveDuplicates.cs | //Remove duplicates from given string
using System;
public class Test
{
public static void Main()
{
string testValue = "Google";
Console.WriteLine(RemoveDuplicateChars(testValue));
}
public static string RemoveDuplicateChars(string key){
string table = "";
string result = "";
foreach(char value in key){
if (table.IndexOf(value) == -1){
table += value;
result += value;
}
}
return result;
}
}
| mit | C# | |
7b1d4f382954f40d77fffa5237d89a3f8e1a6191 | Add web request generator | caronyan/CSharpRecipe | CSharpRecipe/Recipe.Web/HttpWebRequest.cs | CSharpRecipe/Recipe.Web/HttpWebRequest.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Recipe.Web
{
public class HttpWebRequestTest
{
public static HttpWebRequest GenerateHttpWebRequest(Uri uri)
{
HttpWebRequest httpRequest = (HttpWebRequest) WebRequest.Create(uri);
return httpRequest;
}
public static HttpWebRequest GenerateHttpWebRequest(Uri uri, string postData, string contentType)
{
HttpWebRequest httpRequest = GenerateHttpWebRequest(uri);
byte[] bytes = Encoding.UTF8.GetBytes(postData);
httpRequest.ContentType = contentType;
httpRequest.ContentLength = postData.Length;
using (Stream requeStream=httpRequest.GetRequestStream())
{
requeStream.Write(bytes, 0, bytes.Length);
}
return httpRequest;
}
}
}
| mit | C# | |
701aa6478663a5e0460d15791a53991a2d68fd32 | Disable test parallelization in Marten.Testing | JasperFx/Marten,ericgreenmix/marten,JasperFx/Marten,mysticmind/marten,ericgreenmix/marten,mysticmind/marten,ericgreenmix/marten,ericgreenmix/marten,mysticmind/marten,JasperFx/Marten,mysticmind/marten | src/Marten.Testing/AssemblyInfo.cs | src/Marten.Testing/AssemblyInfo.cs | using Xunit;
// 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: CollectionBehavior(DisableTestParallelization = true)]
| mit | C# | |
53c7d3e5b035f6e6cd394e6d36f39a6034ed6a48 | Optimize coins management with CoinRegistry | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Models/CoinsRegistry.cs | WalletWasabi/Models/CoinsRegistry.cs | using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using NBitcoin;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.Models
{
public class CoinsRegistry
{
private HashSet<SmartCoin> _coins;
private object _lock;
public event NotifyCollectionChangedEventHandler CollectionChanged;
public CoinsRegistry()
{
_coins = new HashSet<SmartCoin>();
_lock = new object();
}
public CoinsView AsCoinsView()
{
return new CoinsView(_coins);
}
public bool IsEmpty => !_coins.Any();
public SmartCoin GetByOutPoint(OutPoint outpoint)
{
return _coins.FirstOrDefault(x => x.GetOutPoint() == outpoint);
}
public bool TryAdd(SmartCoin coin)
{
var added = false;
lock (_lock)
{
added = _coins.Add(coin);
}
if( added )
{
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, coin));
}
return added;
}
public void Remove(SmartCoin coin)
{
var coinsToRemove = AsCoinsView().DescendatOf(coin).ToList();
coinsToRemove.Add(coin);
lock (_lock)
{
foreach(var toRemove in coinsToRemove)
{
_coins.Remove(coin);
}
}
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, coinsToRemove));
}
public void Clear()
{
lock (_lock)
{
_coins.Clear();
}
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
} | mit | C# | |
185c4c644588f39881deba2fe16ae85450331212 | add MongoDb MessageStoreDaemon implementation | IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework | Src/iFramework.Plugins/IFramework.MessageStores.MongoDb/MessageStoreDaemon.cs | Src/iFramework.Plugins/IFramework.MessageStores.MongoDb/MessageStoreDaemon.cs | using System.Linq;
using IFramework.MessageStores.Abstracts;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
namespace IFramework.MessageStores.MongoDb
{
public class MessageStoreDaemon : Abstracts.MessageStoreDaemon
{
protected override void RemoveUnSentCommands(Abstracts.MessageStore messageStore, string[] toRemoveCommands)
{
if (messageStore.InMemoryStore)
{
base.RemoveUnSentCommands(messageStore, toRemoveCommands);
return;
}
messageStore.GetMongoDbDatabase()
.GetCollection<UnSentCommand>("unSentCommands")
.DeleteMany(Builders<UnSentCommand>.Filter
.AnyIn("_id", toRemoveCommands));
}
protected override void RemoveUnPublishedEvents(Abstracts.MessageStore messageStore, string[] toRemoveEvents)
{
if (messageStore.InMemoryStore)
{
base.RemoveUnPublishedEvents(messageStore, toRemoveEvents);
return;
}
messageStore.GetMongoDbDatabase()
.GetCollection<UnPublishedEvent>("unPublishedEvents")
.DeleteMany(Builders<UnPublishedEvent>.Filter
.AnyIn("_id", toRemoveEvents));
}
public MessageStoreDaemon(ILogger<Abstracts.MessageStoreDaemon> logger) : base(logger) { }
}
} | mit | C# | |
9995b33cb9f4e551879c94a1061fd5325f8d99e7 | Simplify the handling of OperationCanceledException in net35-cf library | cocosli/antlr4,antlr/antlr4,antlr/antlr4,cocosli/antlr4,chienjchienj/antlr4,krzkaczor/antlr4,lncosie/antlr4,Distrotech/antlr4,parrt/antlr4,parrt/antlr4,lncosie/antlr4,chandler14362/antlr4,chienjchienj/antlr4,joshids/antlr4,supriyantomaftuh/antlr4,Distrotech/antlr4,ericvergnaud/antlr4,parrt/antlr4,parrt/antlr4,supriyantomaftuh/antlr4,joshids/antlr4,antlr/antlr4,Pursuit92/antlr4,ericvergnaud/antlr4,worsht/antlr4,ericvergnaud/antlr4,worsht/antlr4,chandler14362/antlr4,Pursuit92/antlr4,Pursuit92/antlr4,antlr/antlr4,wjkohnen/antlr4,cooperra/antlr4,joshids/antlr4,sidhart/antlr4,parrt/antlr4,joshids/antlr4,jvanzyl/antlr4,wjkohnen/antlr4,joshids/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,sidhart/antlr4,parrt/antlr4,parrt/antlr4,Pursuit92/antlr4,cooperra/antlr4,mcanthony/antlr4,antlr/antlr4,antlr/antlr4,supriyantomaftuh/antlr4,mcanthony/antlr4,mcanthony/antlr4,wjkohnen/antlr4,cocosli/antlr4,Pursuit92/antlr4,wjkohnen/antlr4,chandler14362/antlr4,jvanzyl/antlr4,Pursuit92/antlr4,wjkohnen/antlr4,sidhart/antlr4,Distrotech/antlr4,worsht/antlr4,cooperra/antlr4,mcanthony/antlr4,Pursuit92/antlr4,chandler14362/antlr4,antlr/antlr4,mcanthony/antlr4,joshids/antlr4,parrt/antlr4,hce/antlr4,krzkaczor/antlr4,krzkaczor/antlr4,Pursuit92/antlr4,ericvergnaud/antlr4,jvanzyl/antlr4,chienjchienj/antlr4,hce/antlr4,cocosli/antlr4,cooperra/antlr4,antlr/antlr4,joshids/antlr4,chandler14362/antlr4,sidhart/antlr4,worsht/antlr4,chandler14362/antlr4,antlr/antlr4,chandler14362/antlr4,chienjchienj/antlr4,ericvergnaud/antlr4,hce/antlr4,Distrotech/antlr4,supriyantomaftuh/antlr4,wjkohnen/antlr4,wjkohnen/antlr4,ericvergnaud/antlr4,parrt/antlr4,wjkohnen/antlr4,krzkaczor/antlr4,wjkohnen/antlr4,chandler14362/antlr4,lncosie/antlr4,chienjchienj/antlr4,worsht/antlr4,sidhart/antlr4,supriyantomaftuh/antlr4,ericvergnaud/antlr4,antlr/antlr4,chandler14362/antlr4,parrt/antlr4,lncosie/antlr4,ericvergnaud/antlr4,jvanzyl/antlr4,hce/antlr4,joshids/antlr4,Distrotech/antlr4,Pursuit92/antlr4,lncosie/antlr4,krzkaczor/antlr4 | runtime/CSharp/Antlr4.Runtime/Misc/ParseCanceledException.cs | runtime/CSharp/Antlr4.Runtime/Misc/ParseCanceledException.cs | /*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
using System;
using Antlr4.Runtime.Sharpen;
#if COMPACT
using OperationCanceledException = System.Exception;
#endif
namespace Antlr4.Runtime.Misc
{
/// <summary>This exception is thrown to cancel a parsing operation.</summary>
/// <remarks>
/// This exception is thrown to cancel a parsing operation. This exception does
/// not extend
/// <see cref="Antlr4.Runtime.RecognitionException">Antlr4.Runtime.RecognitionException</see>
/// , allowing it to bypass the standard
/// error recovery mechanisms.
/// <see cref="Antlr4.Runtime.BailErrorStrategy">Antlr4.Runtime.BailErrorStrategy</see>
/// throws this exception in
/// response to a parse error.
/// </remarks>
/// <author>Sam Harwell</author>
#if !PORTABLE
[System.Serializable]
#endif
public class ParseCanceledException : OperationCanceledException
{
public ParseCanceledException()
{
}
public ParseCanceledException(string message)
: base(message)
{
}
public ParseCanceledException(Exception cause)
: base("The parse operation was cancelled.", cause)
{
}
public ParseCanceledException(string message, Exception cause)
: base(message, cause)
{
}
}
}
| /*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
using System;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
/// <summary>This exception is thrown to cancel a parsing operation.</summary>
/// <remarks>
/// This exception is thrown to cancel a parsing operation. This exception does
/// not extend
/// <see cref="Antlr4.Runtime.RecognitionException">Antlr4.Runtime.RecognitionException</see>
/// , allowing it to bypass the standard
/// error recovery mechanisms.
/// <see cref="Antlr4.Runtime.BailErrorStrategy">Antlr4.Runtime.BailErrorStrategy</see>
/// throws this exception in
/// response to a parse error.
/// </remarks>
/// <author>Sam Harwell</author>
#if !PORTABLE
[System.Serializable]
#endif
public class ParseCanceledException
#if COMPACT
: Exception
#else
: OperationCanceledException
#endif
{
public ParseCanceledException()
{
}
public ParseCanceledException(string message)
: base(message)
{
}
public ParseCanceledException(Exception cause)
: base("The parse operation was cancelled.", cause)
{
}
public ParseCanceledException(string message, Exception cause)
: base(message, cause)
{
}
}
}
| bsd-3-clause | C# |
13378c71b8424833a9c14c90d757ee61a3aaf488 | Add base class for DataPoints | CB17Echo/DroneSafety,CB17Echo/DroneSafety,CB17Echo/DroneSafety | AzureFunctions/Models/DataPoint.csx | AzureFunctions/Models/DataPoint.csx | using Microsoft.Azure.Documents.Spatial;
using System;
public abstract class DataPoint
{
public DateTime Time { get; set; }
public Point Location { get; set; }
}
| apache-2.0 | C# | |
0ce72f35b966bdec447cf31693ceae579e79ec3c | add IApplication interface | AspectCore/Mvvm | src/AspectCore.Extensions.Mvvm/IApplication.cs | src/AspectCore.Extensions.Mvvm/IApplication.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AspectCore.Extensions.Mvvm
{
public interface IApplication
{
void Run();
}
}
| mit | C# | |
80d5725e9b68026ae9fce2701ad95589fa9e1bb9 | Create Problem16.cs | neilopet/projecteuler_cs | Problem16.cs | Problem16.cs | /*
* Problem 16
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
*/
using System;
using System.Numerics;
public class Problem16
{
public static void Main()
{
/* Left bit shifting is the same as raising to power of 2 */
BigInteger n = new BigInteger(1);
n<<=1000;
String s = n.ToString();
int sum = 0;
for(int i = 0, j = s.Length; i < j; sum += Int32.Parse(s.Substring(i, 1)), i++)
;
Console.WriteLine(sum);
}
}
| mit | C# | |
c3de71a69f22770303a1cf51eae448a5b36b07bb | Create Greetings.cs | SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming,SurgicalSteel/Competitive-Programming | Kattis-Solutions/Greetings.cs | Kattis-Solutions/Greetings.cs | using System;
namespace Greetings
{
class Program
{
static void Main(string[] args)
{
string g = Console.ReadLine();
int x = (g.Length - 2) * 2;
string n = "h";
for(int i = 0; i < x; i++) { n += "e"; }
n += "y";
Console.WriteLine(n);
}
}
}
| mit | C# | |
97b8736245b9db477581715b2520bb0138455c4b | Create Details.cshtml | CarmelSoftware/Generic-Data-Repository-for-ASP.NET-MVC | Views/Blogs/Details.cshtml | Views/Blogs/Details.cshtml | @model GenericRepository.Models.Blog
@{
ViewBag.Title = "Details";
}
<div class="jumbotron">
<h2>Generic Data Repository - Details</h2><br /><h4>By Carmel Schvartzman</h4>
</div>
<div class="jumbotron">
<fieldset>
<legend>Blog</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Title)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Title)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Text)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Text)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.DatePosted)
</div>
<div class="display-field">
@String.Format("{0:yyyy-MM-dd}",Model.DatePosted.Value )
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.MainPicture)
</div>
<div class="display-field">
<img src="/Content/Images/@Html.DisplayFor(model => model.MainPicture)"/>
</div>
<div class="display-label">
Blogger Name
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Blogger.Name)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.BlogID }, new { @class="btn btn-success" }) |
@Html.ActionLink("Back to List", "Index",null, new { @class="btn btn-success" })
</p>
</div>
| mit | C# | |
0ec149f067d0a930794e9ed2e6ca6bd9fefb0f47 | Create a CellFormatterFactory to select correct formatter | Seddryck/NBi,Seddryck/NBi | NBi.Framework/FailureMessage/Formatter/CellFormatterFactory.cs | NBi.Framework/FailureMessage/Formatter/CellFormatterFactory.cs | using NBi.Core.ResultSet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Unit.Framework.FailureMessage.Formatter
{
public class CellFormatterFactory
{
public CellFormatter GetObject(ColumnType columnType)
{
switch (columnType)
{
case ColumnType.Text:
return new TextCellFormatter();
case ColumnType.Numeric:
return new NumericCellFormatter();
case ColumnType.DateTime:
return new DateTimeCellFormatter();
case ColumnType.Boolean:
return new BooleanCellFormatter();
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
| apache-2.0 | C# | |
410fbf092cb74ae38e1d719f2efa6097613b532f | Add DotNetTestSettings.AddTeamCityLogger | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/CI/TeamCity/DotNetTestSettingsExtensions.cs | source/Nuke.Common/CI/TeamCity/DotNetTestSettingsExtensions.cs | // Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
namespace Nuke.Common.CI.TeamCity
{
[PublicAPI]
public static class DotNetTestSettingsExtensions
{
public static DotNetTestSettings AddTeamCityLogger(this DotNetTestSettings toolSettings)
{
ControlFlow.Assert(TeamCity.Instance != null, "TeamCity.Instance != null");
var teamcityPackage = NuGetPackageResolver
.GetLocalInstalledPackage("TeamCity.Dotnet.Integration", ToolPathResolver.NuGetPackagesConfigFile)
.NotNull("teamcityPackage != null");
var loggerPath = teamcityPackage.Directory / "build" / "_common" / "vstest15";
ControlFlow.Assert(Directory.Exists(loggerPath), $"Directory.Exists({loggerPath})");
return toolSettings
.SetLogger("teamcity")
.SetTestAdapterPath(loggerPath);
}
}
}
| mit | C# | |
6cdae1a7d4daf09907daba16be45c42dcbbd2db2 | Create AddQuestion.cs | Si-143/Application-and-Web-Development | AddQuestion.cs | AddQuestion.cs | public partial class Add_Questions : System.Web.UI.Page
{
List<string> test = new List<string>() {"1","2","3","4","5",};
List<string> test2 = new List<string>() { "a", "b", "c", "d", "e" };
List<TextBox> answerBox;
List<RadioButton> buttons;
List<CheckBox> CBox;
protected void Page_Load(object sender, EventArgs e)
{
TestList.DataSource = DB.ListTest(); TestList.DataTextField = "TestName";
TestList.DataValueField = "TestID";
list
TestList.DataBind();// use to ListTest method to fill the dropdown
Courselist.DataSource = DB.ListCourse(); Courselist.DataTextField = "CourseName";
Courselist.DataValueField = "CourID";
Courselist.DataBind();// same method but with course instead
if (IsPostBack)
}
{
show();
}
private void show()
{
if (MC.Checked)// if MC is checked then shows five radio buttons
and TextBoxes
{
RadioButton1.Text = test[0]; RadioButton2.Text = test[1]; RadioButton3.Text = test[2]; RadioButton4.Text = test[3]; RadioButton5.Text = test[4];
answerBox = new List<TextBox>();
answerBox.Add(TextBox1); answerBox.Add(TextBox2); answerBox.Add(TextBox3); answerBox.Add(TextBox4); answerBox.Add(TextBox5);
buttons = new List<RadioButton>();
buttons.Add(RadioButton1); buttons.Add(RadioButton2); buttons.Add(RadioButton3); buttons.Add(RadioButton4); buttons.Add(RadioButton5);
RadioButton1.ID = test2[0]; RadioButton2.ID = test2[1]; RadioButton3.ID = test2[2]; RadioButton4.ID = test2[3]; RadioButton5.ID = test2[4];
RadioButtonTable.Visible = true;
}
else// else show 5 checkBoxes and textboxes instead
{
CheckBox1.Text = test[0]; CheckBox2.Text = test[1]; CheckBox3.Text = test[2]; CheckBox4.Text = test[3]; CheckBox5.Text = test[4];
answerBox = new List<TextBox>();
answerBox.Add(TextBox6); answerBox.Add(TextBox7); answerBox.Add(TextBox8); answerBox.Add(TextBox9);
answerBox.Add(TextBox10);
CBox = new List<CheckBox>();
CBox.Add(CheckBox1); CBox.Add(CheckBox2); CBox.Add(CheckBox3); CBox.Add(CheckBox4); CBox.Add(CheckBox5);
}
}
CheckBox1.ID = test2[0]; CheckBox2.ID = test2[1]; CheckBox3.ID = test2[2]; CheckBox4.ID = test2[3]; CheckBox5.ID = test2[4];
CheckBoxTable.Visible = true;
RadioButtonTable.Visible = false;
protected void Button1_Click(object sender, EventArgs e)
{
int C = int.Parse(Courselist.SelectedValue.ToString());
string Q = Question.Text;
string I = InsBox.Text;
int testID = int.Parse(TestList.SelectedValue);
// assign values into variables, to use in methods.
if (Question.Text == "" || Points.Text == "" ||InsBox.Text == "")
{
output.Text = ("Try again");
Question.Text = "";
Points.Text = ""; InsBox.Text = "";
//check if the textboxes are blank and if they are then clear
the textboxes and display "try again"
}
else
{
int points = int.Parse(Points.Text);
DB.addquestions(Q, points, I, testID, C);
}
for (int i = 0; i < 5; i++)// add five more buttons and textboxes.
if (MC.Checked){// check is MC is ticked.
}
}
}
//Label1.Text = DB.addanswer(answerBox[i].Text,
Convert.ToInt32(buttons[i].Checked), Question.Text);
else{
DB.addanswer(answerBox[i].Text,
Convert.ToInt32(CBox[i].Checked),Question.Text);// else do this method with
protected void Clear_Click(object sender, EventArgs e)
{
Response.Redirect("Add Questions");// reload up Add questions class
protected void AddTest_Click(object sender, EventArgs e)
{
string T = NewName.Text; string P = NewPass.Text;
string connString;
//assign them to variables.
connString = @"Provider=Microsoft.JET.OLEDB.4.0;Data
Source=I:\AWD\WebApplication1\cwDBExample.mdb";// open connection
OleDbConnection myConnection = new OleDbConnection(connString);
string myQuery = "INSERT INTO test( [testName], [password]) VALUES
( '" + T + "' , '" + P +"')";// add variables into the database.
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
Response.Redirect("Add Questions");// reloads the add question
class
}
catch (Exception ex)
{
message then errors appears
Console.WriteLine("Exception in DBHandler", ex);// show this
}
finally
{
}
myConnection.Close();// close connection.
}
}
| mit | C# | |
02c86d62d575629156ecd78ad5c9555529e9ac82 | Create StubAction.cs | XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors,XamlBehaviors/XamlBehaviors | tests/Avalonia.Xaml.Interactivity.UnitTests/StubAction.cs | tests/Avalonia.Xaml.Interactivity.UnitTests/StubAction.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
namespace Avalonia.Xaml.Interactivity.UnitTests
{
public class StubAction : AvaloniaObject, IAction
{
private readonly object returnValue;
public StubAction()
{
returnValue = null;
}
public StubAction(object returnValue)
{
this.returnValue = returnValue;
}
public object Sender
{
get;
private set;
}
public object Parameter
{
get;
private set;
}
public int ExecuteCount
{
get;
private set;
}
public object Execute(object sender, object parameter)
{
ExecuteCount++;
Sender = sender;
Parameter = parameter;
return returnValue;
}
}
}
| mit | C# | |
c7917ac2151677456d3adaab7d860071f8ba9ace | Add HardwareControllerSwitchChannel which abstracts several types of switched channel. Missing from a previous commit. | ColdMatter/EDMSuite,ColdMatter/EDMSuite,ColdMatter/EDMSuite,Stok/EDMSuite,Stok/EDMSuite,jstammers/EDMSuite,jstammers/EDMSuite,jstammers/EDMSuite,jstammers/EDMSuite,jstammers/EDMSuite,ColdMatter/EDMSuite | EDMBlockHead/HardwareControllerSwitchChannel.cs | EDMBlockHead/HardwareControllerSwitchChannel.cs | using System;
using System.Windows.Forms;
using NationalInstruments.DAQmx;
using DAQ.Environment;
using DAQ.HAL;
namespace EDMBlockHead.Acquire.Channels
{
/// <summary>
/// A channel to map a modulation to the E-field switches. This channel connects to the
/// hardware helper and uses it to switch the fields.
/// </summary>
public class HardwareControllerSwitchChannel : SwitchedChannel
{
public bool Invert;
private bool currentState = false;
static private EDMHardwareControl.Controller hardwareController;
public string Channel;
public override bool State
{
get
{
return currentState;
}
set
{
currentState = value;
try
{
hardwareController.Switch(Channel, value);
}
catch (Exception e)
{
MessageBox.Show("Unable to switch " + Channel + Environment.NewLine + e, "Switch error ...");
}
}
}
public override void AcquisitionStarting()
{
try
{
if (hardwareController == null) hardwareController = new EDMHardwareControl.Controller();
}
catch (Exception e)
{
MessageBox.Show("BlockHead can't connect to the " +
"hardware controller. It won't be able to switch " + Channel +
"Check to make sure it's running." + Environment.NewLine + e, "Connect error ...");
}
}
public override void AcquisitionFinishing()
{
// disconnect from the hardware helper
}
}
}
| mit | C# | |
1c2a5ee1a3dad5bb7ca5463379666acbd1965765 | Fix compile errors in unity3d. | jbruening/lidgren-network-gen3,PowerOfCode/lidgren-network-gen3,SacWebDeveloper/lidgren-network-gen3,RainsSoft/lidgren-network-gen3,lidgren/lidgren-network-gen3,dragutux/lidgren-network-gen3,forestrf/lidgren-network-gen3 | Lidgren.Network/Platform/PlatformConstrained.cs | Lidgren.Network/Platform/PlatformConstrained.cs | #if __CONSTRAINED__ || UNITY_STANDALONE_LINUX
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography;
namespace Lidgren.Network
{
public static partial class NetUtility
{
private static byte[] s_randomMacBytes;
static NetUtility()
{
s_randomMacBytes = new byte[8];
MWCRandom.Instance.NextBytes(s_randomMacBytes);
}
[CLSCompliant(false)]
public static ulong GetPlatformSeed(int seedInc)
{
ulong seed = (ulong)Environment.TickCount + (ulong)seedInc;
return seed ^ ((ulong)(new object().GetHashCode()) << 32);
}
/// <summary>
/// Gets my local IPv4 address (not necessarily external) and subnet mask
/// </summary>
public static IPAddress GetMyAddress(out IPAddress mask)
{
#if UNITY_ANDROID || UNITY_STANDALONE_OSX || UNITY_STANDLONE_WIN || UNITY_STANDLONE_LINUX || UNITY_IOS
try
{
if (!(UnityEngine.Application.internetReachability == UnityEngine.NetworkReachability.NotReachable))
{
mask = null;
return null;
}
return IPAddress.Parse(UnityEngine.Network.player.externalIP);
}
catch // Catch Access Denied errors
{
mask = null;
return null;
}
#endif
mask = null;
return null;
}
public static byte[] GetMacAddressBytes()
{
return s_randomMacBytes;
}
public static IPAddress GetBroadcastAddress()
{
return IPAddress.Broadcast;
}
public static void Sleep(int milliseconds)
{
System.Threading.Thread.Sleep(milliseconds);
}
public static IPAddress CreateAddressFromBytes(byte[] bytes)
{
return new IPAddress(bytes);
}
private static readonly SHA1 s_sha = SHA1.Create();
public static byte[] ComputeSHAHash(byte[] bytes, int offset, int count)
{
return s_sha.ComputeHash(bytes, offset, count);
}
}
public static partial class NetTime
{
private static readonly long s_timeInitialized = Environment.TickCount;
/// <summary>
/// Get number of seconds since the application started
/// </summary>
public static double Now { get { return (double)((uint)Environment.TickCount - s_timeInitialized) / 1000.0; } }
}
}
#endif
| #if __CONSTRAINED__ || UNITY_STANDALONE_LINUX
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography;
namespace Lidgren.Network
{
public static partial class NetUtility
{
private static byte[] s_randomMacBytes;
static NetUtility()
{
s_randomMacBytes = new byte[8];
MWCRandom.Instance.NextBytes(s_randomMacBytes);
}
[CLSCompliant(false)]
public static ulong GetPlatformSeed(int seedInc)
{
ulong seed = (ulong)Environment.TickCount + (ulong)seedInc;
return seed ^ ((ulong)(new object().GetHashCode()) << 32);
}
/// <summary>
/// Gets my local IPv4 address (not necessarily external) and subnet mask
/// </summary>
public static IPAddress GetMyAddress(out IPAddress mask)
{
#if UNITY_ANDROID || UNITY_STANDALONE_OSX || UNITY_STANDLONE_WIN || UNITY_STANDLONE_LINX || UNITY_IOS
try
{
if (!(UnityEngine.Application.internetReachability == UnityEngine.NetworkReachability.NotReachable))
return null;
return IPAddress.Parse(UnityEngine.Network.player.externalIP);
}
catch // Catch Access Denied errors
{
return null;
}
#endif
mask = null;
return null;
}
public static byte[] GetMacAddressBytes()
{
return s_randomMacBytes;
}
public static IPAddress GetBroadcastAddress()
{
return IPAddress.Broadcast;
}
public static void Sleep(int milliseconds)
{
System.Threading.Thread.Sleep(milliseconds);
}
public static IPAddress CreateAddressFromBytes(byte[] bytes)
{
return new IPAddress(bytes);
}
private static readonly SHA1 s_sha = SHA1.Create();
public static byte[] ComputeSHAHash(byte[] bytes, int offset, int count)
{
return s_sha.ComputeHash(bytes, offset, count);
}
}
public static partial class NetTime
{
private static readonly long s_timeInitialized = Environment.TickCount;
/// <summary>
/// Get number of seconds since the application started
/// </summary>
public static double Now { get { return (double)((uint)Environment.TickCount - s_timeInitialized) / 1000.0; } }
}
}
#endif
| mit | C# |
60f5fbddbcfb71779a755cf56705563eb13b14d3 | add IsolationLevelExtensions | IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework | Src/iFramework.Plugins/IFramework.EntityFrameworkCore/IsolationLevelExtensions.cs | Src/iFramework.Plugins/IFramework.EntityFrameworkCore/IsolationLevelExtensions.cs | using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using IsolationLevel = System.Transactions.IsolationLevel;
namespace IFramework.EntityFrameworkCore
{
public static class IsolationLevelExtensions
{
public static System.Data.IsolationLevel ToDataIsolationLevel(this IsolationLevel level)
{
System.Data.IsolationLevel systemLevel = System.Data.IsolationLevel.Serializable;
switch (level)
{
case IsolationLevel.Chaos:
systemLevel = System.Data.IsolationLevel.Chaos;
break;
case IsolationLevel.Serializable:
systemLevel = System.Data.IsolationLevel.Serializable;
break;
case IsolationLevel.ReadCommitted:
systemLevel = System.Data.IsolationLevel.ReadCommitted;
break;
case IsolationLevel.ReadUncommitted:
systemLevel = System.Data.IsolationLevel.ReadUncommitted;
break;
case IsolationLevel.RepeatableRead:
systemLevel = System.Data.IsolationLevel.RepeatableRead;
break;
case IsolationLevel.Snapshot:
systemLevel = System.Data.IsolationLevel.Snapshot;
break;
case IsolationLevel.Unspecified:
systemLevel = System.Data.IsolationLevel.Snapshot;
break;
}
return systemLevel;
}
public static IsolationLevel ToSystemIsolationLevel(this System.Data.IsolationLevel level)
{
IsolationLevel systemLevel = IsolationLevel.Serializable;
switch (level)
{
case System.Data.IsolationLevel.Chaos:
systemLevel = IsolationLevel.Chaos;
break;
case System.Data.IsolationLevel.Serializable:
systemLevel = IsolationLevel.Serializable;
break;
case System.Data.IsolationLevel.ReadCommitted:
systemLevel = IsolationLevel.ReadCommitted;
break;
case System.Data.IsolationLevel.ReadUncommitted:
systemLevel = IsolationLevel.ReadUncommitted;
break;
case System.Data.IsolationLevel.RepeatableRead:
systemLevel = IsolationLevel.RepeatableRead;
break;
case System.Data.IsolationLevel.Snapshot:
systemLevel = IsolationLevel.Snapshot;
break;
case System.Data.IsolationLevel.Unspecified:
systemLevel = IsolationLevel.Snapshot;
break;
}
return systemLevel;
}
}
}
| mit | C# | |
f6f20326808fad9d9a22c175932eb0bb2c48d1ec | check in MemoryPackagePartOutputStream.cs | tonyqus/npoi,akrisiun/npoi,stuartwmurray/npoi,antony-liu/npoi,tkalubi/npoi-1,Yijtx/npoi,JesseQin/npoi,vinod1988/npoi,xl1/npoi,jcridev/npoi | ooxml/openxml4Net/OPC/Internal/MemoryPackagePartOutputStream.cs | ooxml/openxml4Net/OPC/Internal/MemoryPackagePartOutputStream.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace NPOI.OpenXml4Net.OPC.Internal
{
public class MemoryPackagePartOutputStream : Stream
{
private MemoryPackagePart _part;
private MemoryStream _buff;
public MemoryPackagePartOutputStream(MemoryPackagePart part)
{
this._part = part;
_buff = new MemoryStream();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override bool CanRead
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public void Write(int b)
{
_buff.WriteByte((byte)b);
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
/**
* Close this stream and flush the content.
* @see #flush()
*/
public override void Close()
{
this.Flush();
}
/**
* Flush this output stream. This method is called by the close() method.
* Warning : don't call this method for output consistency.
* @see #close()
*/
public override void Flush()
{
_buff.Flush();
if (_part.data != null)
{
byte[] newArray = new byte[_part.data.Length + _buff.Length];
// copy the previous contents of part.data in newArray
Array.Copy(_part.data, 0, newArray, 0, _part.data.Length);
// append the newly added data
byte[] buffArr = _buff.ToArray();
Array.Copy(buffArr, 0, newArray, _part.data.Length,
buffArr.Length);
// save the result as new data
_part.data = newArray;
}
else
{
// was empty, just fill it
_part.data = _buff.ToArray();
}
/*
* Clear this streams buffer, in case flush() is called a second time
* Fix bug 1921637 - provided by Rainer Schwarze
*/
_buff.Position = 0;
}
public override void Write(byte[] b, int off, int len)
{
_buff.Write(b, off, len);
}
public void Write(byte[] b)
{
_buff.Write(b, (int)_buff.Position, b.Length);
}
}
}
| apache-2.0 | C# | |
281e4d1710bbce216f37f3320a2a3719ff93472f | Update WhatsConstants.cs | rvriens/Chat-API-NET,andrebires/Chat-API-NET,rvriens/Chat-API-NET,andrebires/Chat-API-NET,mgp25/Chat-API-NET,rvriens/Chat-API-NET,mgp25/Chat-API-NET,andrebires/Chat-API-NET,mgp25/Chat-API-NET | WhatsAppApi/Settings/WhatsConstants.cs | WhatsAppApi/Settings/WhatsConstants.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace WhatsAppApi.Settings
{
/// <summary>
/// Holds constant information used to connect to whatsapp server
/// </summary>
public class WhatsConstants
{
#region ServerConstants
/// <summary>
/// The whatsapp host
/// </summary>
public const string WhatsAppHost = "c3.whatsapp.net";
/// <summary>
/// The whatsapp XMPP realm
/// </summary>
public const string WhatsAppRealm = "s.whatsapp.net";
/// <summary>
/// The whatsapp server
/// </summary>
public const string WhatsAppServer = "s.whatsapp.net";
/// <summary>
/// The whatsapp group chat server
/// </summary>
public const string WhatsGroupChat = "g.us";
/// <summary>
/// The whatsapp version the client complies to
/// </summary>
public const string WhatsAppVer = "2.13.21";
/// <summary>
/// The port that needs to be connected to
/// </summary>
public const int WhatsPort = 443;
/// <summary>
/// iPhone device
/// </summary>
public const string Device = "S40";
/// <summary>
/// The useragent used for http requests
/// </summary>
public const string UserAgent = "WhatsApp/2.13.21 S40Version/14.26 Device/Nokia302";
#endregion
#region ParserConstants
/// <summary>
/// The number style used
/// </summary>
public static NumberStyles WhatsAppNumberStyle = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign);
/// <summary>
/// Unix epoch DateTime
/// </summary>
public static DateTime UnixEpoch = new DateTime(0x7b2, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace WhatsAppApi.Settings
{
/// <summary>
/// Holds constant information used to connect to whatsapp server
/// </summary>
public class WhatsConstants
{
#region ServerConstants
/// <summary>
/// The whatsapp host
/// </summary>
public const string WhatsAppHost = "c3.whatsapp.net";
/// <summary>
/// The whatsapp XMPP realm
/// </summary>
public const string WhatsAppRealm = "s.whatsapp.net";
/// <summary>
/// The whatsapp server
/// </summary>
public const string WhatsAppServer = "s.whatsapp.net";
/// <summary>
/// The whatsapp group chat server
/// </summary>
public const string WhatsGroupChat = "g.us";
/// <summary>
/// The whatsapp version the client complies to
/// </summary>
public const string WhatsAppVer = "2.12.96";
/// <summary>
/// The port that needs to be connected to
/// </summary>
public const int WhatsPort = 443;
/// <summary>
/// iPhone device
/// </summary>
public const string Device = "S40";
/// <summary>
/// The useragent used for http requests
/// </summary>
public const string UserAgent = "WhatsApp/2.12.96 S40Version/14.26 Device/Nokia302";
#endregion
#region ParserConstants
/// <summary>
/// The number style used
/// </summary>
public static NumberStyles WhatsAppNumberStyle = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign);
/// <summary>
/// Unix epoch DateTime
/// </summary>
public static DateTime UnixEpoch = new DateTime(0x7b2, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
#endregion
}
}
| mit | C# |
5541de5f95b5b6bf4a1906c48256488d8847228f | Add tests to cover TestSuite.Copy | mjedrzejek/nunit,nunit/nunit,mjedrzejek/nunit,nunit/nunit | src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs | src/NUnitFramework/tests/Internal/TestSuiteCopyTests.cs | using NUnit.Framework.Api;
using NUnit.TestData.OneTimeSetUpTearDownData;
using NUnit.TestData.TestFixtureSourceData;
using NUnit.TestUtilities;
namespace NUnit.Framework.Internal
{
// Tests that Copy is properly overridden for all types extending TestSuite - #3171
public class TestSuiteCopyTests
{
[Test]
public void CopyTestSuiteReturnsCorrectType()
{
TestSuite testSuite =
new TestSuite(new TypeWrapper(typeof(NUnit.TestData.ParameterizedTestFixture)));
var copiedTestSuite = testSuite.Copy(TestFilter.Empty);
Assert.AreEqual(copiedTestSuite.GetType(), typeof(TestSuite));
}
[Test]
public void CopyParameterizedTestFixtureReturnsCorrectType()
{
TestSuite parameterizedTestFixture =
new ParameterizedFixtureSuite(new TypeWrapper(typeof(NUnit.TestData.ParameterizedTestFixture)));
var copiedParameterizedTestFixture = parameterizedTestFixture.Copy(TestFilter.Empty);
Assert.AreEqual(copiedParameterizedTestFixture.GetType(), typeof(ParameterizedFixtureSuite));
}
[Test]
public void CopyParameterizedMethodSuiteReturnsCorrectType()
{
TestSuite parameterizedMethodSuite = new ParameterizedMethodSuite(new MethodWrapper(
typeof(NUnit.TestData.ParameterizedTestFixture),
nameof(NUnit.TestData.ParameterizedTestFixture.MethodWithParams)));
var copiedparameterizedMethodSuite = parameterizedMethodSuite.Copy(TestFilter.Empty);
Assert.AreEqual(copiedparameterizedMethodSuite.GetType(), typeof(ParameterizedMethodSuite));
}
[Test]
public void CopyTestFixtureReturnsCorrectType()
{
TestSuite testFixture = TestBuilder.MakeFixture(typeof(FixtureWithNoTests));
var copiedTestFixture = testFixture.Copy(TestFilter.Empty);
Assert.AreEqual(copiedTestFixture.GetType(), typeof(TestFixture));
}
[Test]
public void CopySetUpFixtureReturnsCorrectType()
{
TestSuite setUpFixture =
new SetUpFixture(
new TypeWrapper(typeof(NUnit.TestData.SetupFixture.Namespace1.NUnitNamespaceSetUpFixture1)));
var copiedSetupFixture = setUpFixture.Copy(TestFilter.Empty);
Assert.AreEqual(copiedSetupFixture.GetType(), typeof(SetUpFixture));
}
[Test]
public void CopyTestAssemblyReturnsCorrectType()
{
var runner = new NUnitTestAssemblyRunner(new DefaultTestAssemblyBuilder());
TestSuite assembly = new TestAssembly(AssemblyHelper.Load("mock-assembly.dll"), "mock-assembly");
var copiedAssembly = assembly.Copy(TestFilter.Empty);
Assert.AreEqual(copiedAssembly.GetType(), typeof(TestAssembly));
}
}
}
| mit | C# | |
fcdbc8c57e9c1094a25683b8e78169861b14c863 | Create BoxColliderFitChildren.cs | UnityCommunity/UnityLibrary | Assets/Scripts/Editor/ContextMenu/BoxColliderFitChildren.cs | Assets/Scripts/Editor/ContextMenu/BoxColliderFitChildren.cs | // Adjust Box Collider to fit child meshes inside
// usage: You have empty parent transform, with child meshes inside, add box collider to parent then use this
using UnityEngine;
using UnityEditor;
namespace UnityLibrary
{
public class BoxColliderFitChildren : MonoBehaviour
{
[MenuItem("CONTEXT/BoxCollider/Fit to Children")]
static void FixSize(MenuCommand command)
{
BoxCollider col = (BoxCollider)command.context;
// record undo
Undo.RecordObject(col.transform, "Fit Box Collider To Children");
// get child mesh bounds
var b = GetRecursiveMeshBounds(col.gameObject);
// set collider local center and size
col.center = col.transform.root.InverseTransformVector(b.center) - col.transform.position;
col.size = b.size;
}
public static Bounds GetRecursiveMeshBounds(GameObject go)
{
var r = go.GetComponentsInChildren<Renderer>();
if (r.Length > 0)
{
var b = r[0].bounds;
for (int i = 1; i < r.Length; i++)
{
b.Encapsulate(r[i].bounds);
}
return b;
}
else // TODO no renderers
{
return new Bounds(Vector3.one, Vector3.one);
}
}
}
}
| mit | C# | |
fdc9bc9a01fe5657e6b06c348c8f41097cdeedda | Create Test that dapper works wil Session | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/ExampleTests/RepositoryQueryTests.cs | src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/ExampleTests/RepositoryQueryTests.cs | using System.Collections.Generic;
using System.Linq;
using Dapper;
using FakeItEasy;
using NUnit.Framework;
using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.ExampleTests
{
[TestFixture]
public class RepositoryQueryTests : CommonTestDataSetup
{
[Test, Category("Integration")]
public static void Query_Returns_DataFromBrave()
{
IEnumerable<Brave> results = null;
Assert.DoesNotThrow(()=> results = Connection.Query<Brave>("Select * FROM Braves"));
Assert.That(results, Is.Not.Null);
Assert.That(results, Is.Not.Empty);
Assert.That(results.Count(), Is.EqualTo(3));
}
}
}
| mit | C# | |
824f8dc44e9d47c11475dfee81494c07e9cce1d2 | Check in missing file | cjbhaines/MemBroker | src/MemBroker/WeakActionListDictionary.cs | src/MemBroker/WeakActionListDictionary.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace MemBroker
{
/// <summary>
/// The class is thread-safe insofar as it shouldn't throw exceptions if you're using it in a multi-threaded
/// environment, but its behaviour under various race conditions, or pertaining to dirty reads is variable
/// (e.g. a listener cannot guarantee to receive no more messages after an Unregister call, although it can
/// be sure it will not receive any messages that were sent after its Unregister call completes).
/// </summary>
internal class WeakActionListDictionary
{
private readonly ConcurrentDictionary<Type, ISet<WeakActionBase>> dictionary = new ConcurrentDictionary<Type, ISet<WeakActionBase>>();
public void Add<TMessage>(WeakAction<TMessage> action)
{
dictionary.AddOrUpdate(typeof(TMessage), t => new HashSet<WeakActionBase> { action }, (t, l) => { l.UnionWith(new[] { action }); return l; });
}
public IEnumerable<WeakActionBase> GetValue(Type typeToFind)
{
ISet<WeakActionBase> innerBag;
if (dictionary.TryGetValue(typeToFind, out innerBag))
{
return innerBag.Select(wa => wa);
}
return new List<WeakActionBase>();
}
public IEnumerable<WeakAction<TMessage>> GetValue<TMessage>()
{
ISet<WeakActionBase> innerBag;
if (dictionary.TryGetValue(typeof(TMessage), out innerBag))
{
return innerBag.Select(wa => (WeakAction<TMessage>)wa);
}
return new List<WeakAction<TMessage>>();
}
public void RemoveRecipient(object recipient)
{
foreach (var innerBag in dictionary.Values)
{
lock (innerBag)
{
var weakActionsToRemove = innerBag.Where(wa => wa != null && wa.Target == recipient).ToArray();
foreach (var action in weakActionsToRemove)
{
innerBag.Remove(action);
}
}
}
}
public void Cleanup()
{
var keysToRemove = new List<Type>();
foreach (var pair in dictionary.ToList())
{
lock (pair.Value)
{
var deadSubscribers = pair.Value.Where(item => item == null || !item.IsAlive).ToList();
pair.Value.ExceptWith(deadSubscribers);
if (!pair.Value.Any())
{
keysToRemove.Add(pair.Key);
}
}
}
ISet<WeakActionBase> removedValue;
keysToRemove.ForEach(key => dictionary.TryRemove(key, out removedValue));
}
public void Clear()
{
dictionary.Clear();
}
}
} | mit | C# | |
649e41240705ee79a21e166fe6067c11d5c26fbe | Create NumberRule.cs | shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/hackerrank | NumberRule.cs | NumberRule.cs | /*
Method to check if all the digits in a number are present in a non-descending order
Eg:
returns true for: 1, 123, 1357, 1112, 1233345
returns false for: 10, 1243, 192, 890, 543
*/
bool NumberRule(int n) {
while(n>0){
if(n%100/10>n%10) //check if last-1th digit is greater than the last digit
return 0!=0; //if so, number is invalid
n/=10; //keep taking out last digit from n
}
return true;
}
| mit | C# | |
99309c64a36aba4588ef365c93ccf65f0c1544ac | Revert "Upgrade_20211111_ReplaceDefaultExecute" | signumsoftware/framework,signumsoftware/framework | Signum.Upgrade/Upgrades/Upgrade_20211111_ReplaceDefaultExecute.cs | Signum.Upgrade/Upgrades/Upgrade_20211111_ReplaceDefaultExecute.cs | namespace Signum.Upgrade.Upgrades;
class Upgrade_20211111_ReplaceDefaultExecute : CodeUpgradeBase
{
public override string Description => "Replace eoc.defaultClick( with return eoc.defaultClick(";
public override void Execute(UpgradeContext uctx)
{
uctx.ForeachCodeFile($@"*.tsx", uctx.ReactDirectory, file =>
{
file.Replace("eoc.defaultClick(", "/*TODO: fix*/ eoc.defaultClick(");
});
}
}
| mit | C# | |
27b3e643c9d7636039689f7d8589a052ce56031d | Add Win32 functionality to get foreground process | BrunoBrux/ArticulateDVS,Mpstark/articulate | Articulate/Components/ForegroundProcess.cs | Articulate/Components/ForegroundProcess.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Articulate
{
/// <summary>
/// Gets information about the currently active window
/// </summary>
public static class ForegroundProcess
{
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out IntPtr lpdwProcessId);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
/// <summary>
/// Gets the Full Path to the current foreground window's executable file
/// </summary>
public static string FullPath
{
get
{
IntPtr processID;
GetWindowThreadProcessId(GetForegroundWindow(), out processID);
Process p = Process.GetProcessById((int)processID);
return p.MainModule.FileName;
}
}
/// <summary>
/// Gets the executable's filename without extension
/// </summary>
public static string ExecutableName
{
get
{
return Path.GetFileNameWithoutExtension(FullPath);
}
}
}
}
| mit | C# | |
93bf191ba47b534551e3265cfc69c09378b97f1a | Add failing test | DixonD-git/structuremap,DixonD-git/structuremap,DixonD-git/structuremap,DixonDs/structuremap,DixonD-git/structuremap,DixonDs/structuremap | src/StructureMap.Testing/Bugs/Bug_557_unique_instances_when_using_with.cs | src/StructureMap.Testing/Bugs/Bug_557_unique_instances_when_using_with.cs | using Xunit;
namespace StructureMap.Testing.Bugs
{
public class Bug_557_unique_instances_when_using_with
{
[Fact]
public void should_return_unique_instances_when_using_With()
{
var root = new Container();
var nested1 = root.GetNestedContainer();
var nested2 = root.GetNestedContainer();
var i1_1 = nested1.With(new Arg()).GetInstance<Target>();
var i1_2 = nested1.With(new Arg()).GetInstance<Target>();
i1_1.ShouldNotBeTheSameAs(i1_2);
// Make sure that normal lifecycle was not affected by the other container
var i2_1 = nested2.GetInstance<Target>();
var i2_2 = nested2.GetInstance<Target>();
i2_1.ShouldBeTheSameAs(i2_2);
}
public class Target
{
public Target(Arg arg) {}
}
public class Arg { }
}
} | apache-2.0 | C# | |
241ad6a221ffb2e1f2ca612c170921bdafae6067 | Add a very simple Should implementation, adding some of the missing nunit features i need that arent available in MDs old version. | jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos | src/Manos.Tests/Nunit-Extensions/Nunit_Extension_Methods.cs | src/Manos.Tests/Nunit-Extensions/Nunit_Extension_Methods.cs | using System;
using NUnit.Framework;
//
// Lets you use some of Nunits modern assert methods on monodevelops archaic nunit
//
namespace Manos.ShouldExt
{
public delegate void TestSnippet ();
public class Should {
public static void Throw<T> (TestSnippet snippet) where T : Exception
{
try {
snippet ();
} catch (Exception e) {
if (e.GetType () == typeof (T))
return;
throw new Exception (String.Format ("Invalid exception type. Expected '{0}' got '{1}'", typeof (T), e.GetType ()));
}
throw new Exception ("No exception thrown.");
}
public static void Throw<T> (TestSnippet snippet, string message) where T : Exception
{
try {
snippet ();
} catch (Exception e) {
if (e.GetType () == typeof (T))
return;
throw new Exception (String.Format ("{0}: Invalid exception type. Expected '{1}' got '{2}'", message, typeof (T), e.GetType ()));
}
throw new Exception (String.Format ("{0}: No exception thrown.", message));
}
public static void NotBeNull (object o)
{
if (o == null)
throw new Exception ("Object is null.");
}
public static void NotBeNull (object o, string message)
{
if (o == null)
throw new Exception (String.Format ("{0}: should not be null.", message));
}
public static void BeInstanceOf<T> (object o)
{
if (o == null)
throw new Exception ("Item is null.");
if (o.GetType () != typeof (T))
throw new Exception (String.Format ("Expected '{0}' got '{1}'", typeof (T), o.GetType ()));
}
public static void BeInstanceOf<T> (object o, string message)
{
if (o == null)
throw new Exception (String.Format ("{0}: Item is null.", message));
if (o.GetType () != typeof (T))
throw new Exception (String.Format ("{0}: Expected '{1}' got '{2}'", message, typeof (T), o.GetType ()));
}
public static void NotThrow (TestSnippet snippet)
{
snippet ();
}
}
}
| mit | C# | |
be1239c81ee891d4a00ee669a82e25df78ba5f79 | Update DommelPropertyMap.cs | arumata/Dapper-FluentMap,thomasbargetz/Dapper-FluentMap,henkmollema/Dapper-FluentMap,bondarenkod/Dapper-FluentMap,henkmollema/Dapper-FluentMap | src/Dapper.FluentMap.Dommel/Mapping/DommelPropertyMap.cs | src/Dapper.FluentMap.Dommel/Mapping/DommelPropertyMap.cs | using System.Reflection;
using Dapper.FluentMap.Mapping;
namespace Dapper.FluentMap.Dommel.Mapping
{
/// <summary>
/// Represents mapping of a property for Dommel.
/// </summary>
public class DommelPropertyMap : PropertyMapBase<DommelPropertyMap>, IPropertyMap
{
/// <summary>
/// Initializes a new instance of the <see cref="Dapper.FluentMap.Dommel.Mapping.DommelPropertyMap"/> class
/// with the specified <see cref="System.Reflection.PropertyInfo"/> object.
/// </summary>
/// <param name="info">The information about the property.</param>
public DommelPropertyMap(PropertyInfo info)
: base(info)
{
}
public bool Key { get; private set; }
/// <summary>
/// Marks the current property as key for the entity.
/// </summary>
/// <returns>The current instance of <see cref="T:Dapper.FluentMap.Dommel.Mapping.DommelPropertyMap"/>.</returns>
public DommelPropertyMap IsKey()
{
Key = true;
return this;
}
}
}
| using System.Reflection;
using Dapper.FluentMap.Mapping;
namespace Dapper.FluentMap.Dommel.Mapping
{
/// <summary>
/// Represents mapping of a property for Dommel.
/// </summary>
public class DommelPropertyMap : PropertyMapBase<DommelPropertyMap>, IPropertyMap
{
/// <summary>
/// Initializes a new instance of the <see cref="Dapper.FluentMap.Dommel.Mapping.DommelPropertyMap"/> class
/// with the specified <see cref="System.Reflection.PropertyInfo"/> object.
/// </summary>
/// <param name="info">The information about the property.</param>
public DommelPropertyMap(PropertyInfo info)
: base(info)
{
}
internal bool Key { get; private set; }
/// <summary>
/// Marks the current property as key for the entity.
/// </summary>
/// <returns>The current instance of <see cref="T:Dapper.FluentMap.Dommel.Mapping.DommelPropertyMap"/>.</returns>
public DommelPropertyMap IsKey()
{
Key = true;
return this;
}
}
}
| mit | C# |
11af33933330142234a441b677578a90aac1f2ed | Create StarTringle.cs | aAmitSengar/MyWorks | StarTringle.cs | StarTringle.cs | /*
* *
** **
*** ***
**** ****
***** *****
****** ******
******* *******
******** ********
********* *********
********************
*/
string aa = string.Empty;
for (int i = 0; i < 10; i++)
{
int ii = i;
var space = 0;
string stars = "";
for (int j = i; j >= 0; j--)
{
for (; ii >= 0; ii--)
{
stars += "*";
}
space = 10 - i;
}
aa += string.Format("{0,-10:X2}", stars) + string.Format("{0,10:X2}", stars);
aa += "\r\n";
}
Console.WriteLine(aa);
| mit | C# | |
6c2bfb9af67f43da1fad18a9306f225cf916a352 | Add PPPoE Support | danikf/tik4net | tik4net.objects/Interface/InterfacePppoeserverServer..cs | tik4net.objects/Interface/InterfacePppoeserverServer..cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace tik4net.Objects.Interface
{
/// <summary>
/// /interface
/// </summary>
[TikEntity("interface/pppoe-server/server", IncludeDetails = true)]
public class InterfacePppoeserverServer
{
/// <summary>
/// .id
/// </summary>
[TikProperty(".id", IsReadOnly = true, IsMandatory = true)]
public string Id { get; private set; }
/// <summary>
/// service-name
/// </summary>
[TikProperty("service-name", IsMandatory = true)]
public string ServiceName { get; set; }
/// <summary>
/// interface
/// </summary>
[TikProperty("interface", IsMandatory = true)]
public string Iface { get; set; }
/// <summary>
/// max-mtu
/// </summary>
[TikProperty("max-mtu")]
public string MaxMtu { get; set; }
/// <summary>
/// max-mtu
/// </summary>
[TikProperty("max-mtu")]
public string MaxMru { get; set; }
/// <summary>
/// mrru
/// </summary>
[TikProperty("mrru")]
public string Mrru { get; set; }
/// <summary>
/// authentication
/// </summary>
[TikProperty("authentication", IsMandatory = true, DefaultValue = "pap,chap,mschap1,mschap2")]
public string Authentication { get; set; }
/// <summary>
/// keepalive-timeout
/// </summary>
[TikProperty("keepalive-timeout",DefaultValue ="10")]
public string KeepaliveTimeout { get; set; }
/// <summary>
/// one-session-per-host
/// </summary>
[TikProperty("one-session-per-host")]
public bool OneSessionPerHost { get; set; }
/// <summary>
/// max-sessions
/// </summary>
[TikProperty("max-sessions")]
public string MaxSessions { get; set; }
/// <summary>
/// pado-delay
/// </summary>
[TikProperty("pado-delay")]
public string PadoDelay { get; set; }
/// <summary>
/// default-profile
/// </summary>
[TikProperty("default-profile", IsMandatory = true, DefaultValue = "default")]
public string DefaultProfile { get; set; }
/// <summary>
/// running
/// </summary>
[TikProperty("invalid", IsReadOnly = true)]
public bool Running { get; private set; }
/// <summary>
/// disabled
/// </summary>
[TikProperty("disabled")]
public bool Disabled { get; set; }
}
}
| apache-2.0 | C# | |
1eefef008061c3b5445f417def7142f009b109e2 | Add True | farity/farity | Farity/True.cs | Farity/True.cs | namespace Farity
{
public static partial class F
{
public static readonly FuncAny<bool> True = args => true;
}
} | mit | C# | |
e2db845193b331a21b7878a5850205781cd3b1fa | Add LogField that regroup all constant for log field in Lucene. | ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton | src/CK.Glouton.Model/Logs/LogField.cs | src/CK.Glouton.Model/Logs/LogField.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace CK.Glouton.Model.Logs
{
public class LogField
{
public const string LOG_TYPE = "LogType";
public const string EXCEPTION = "Exception";
public const string LOG_TIME = "LogTime";
public const string LOG_LEVEL = "LogLevel";
public const string TAGS = "Tags";
public const string SOURCE_FILE_NAME = "FileName";
public const string MONITOR_ID = "MonitorId";
public const string GROUP_DEPTH = "GroupDepth";
public const string PREVIOUS_ENTRY_TYPE = "PreviousEntryType";
public const string APP_ID = "AppId";
public const string INNER_EXCEPTION = "InnerException";
public const string CONCLUSION = "Conclusion";
public const string TEXT = "Text";
public const string PREVIOUS_LOG_TIME = "PreviousLogTime";
public const string LINE_NUMBER = "LineNumber";
public const string APP_NAME = "AppName";
public const string INDEX_DTS = "IndexDTS";
public const string STACK = "Stack";
public const string DETAILS = "Details";
public const string MONITOR_ID_LIST = "MonitorIdList";
public const string APP_NAME_LIST = "AppNameList";
public const string DATE_TIME_STAMP = "DateTimeStamp";
public const string CK_EXCEPTION_DATA = "CKExceptionData";
public const string CK_TRAIT = "CKTrait";
public const string AGGREGATED_EXCEPTIONS = "AggregatedExceptions";
public const string EXCEPTION_DEPTH = "ExceptionDepth";
}
}
| mit | C# | |
f23f53babf948504065279017cea316eb88bebd1 | add captransaction interface. | dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP | src/DotNetCore.CAP/ICapTransaction.cs | src/DotNetCore.CAP/ICapTransaction.cs | using System;
namespace DotNetCore.CAP
{
public interface ICapTransaction : IDisposable
{
bool AutoCommit { get; set; }
object DbTransaction { get; set; }
void Commit();
void Rollback();
}
}
| mit | C# | |
6cdae29a3b218948db1127678355ccc84ceed106 | Add an xUnit test discoverer that ignores tests when run on AppVeyor | jbogard/Respawn,jbogard/Respawn | Respawn.DatabaseTests/SkipOnAppVeyorAttribute.cs | Respawn.DatabaseTests/SkipOnAppVeyorAttribute.cs | namespace Respawn.DatabaseTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
public class SkipOnAppVeyorTestDiscoverer : IXunitTestCaseDiscoverer
{
private readonly IMessageSink _diagnosticMessageSink;
public SkipOnAppVeyorTestDiscoverer(IMessageSink diagnosticMessageSink)
{
_diagnosticMessageSink = diagnosticMessageSink;
}
public IEnumerable<IXunitTestCase> Discover(ITestFrameworkDiscoveryOptions discoveryOptions, ITestMethod testMethod, IAttributeInfo factAttribute)
{
if (Environment.GetEnvironmentVariable("Appveyor")?.ToUpperInvariant() == "TRUE")
{
return Enumerable.Empty<IXunitTestCase>();
}
return new[] { new XunitTestCase(_diagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), testMethod) };
}
}
[XunitTestCaseDiscoverer("Respawn.DatabaseTests.SkipOnAppVeyorTestDiscoverer", "Respawn.DatabaseTests")]
public class SkipOnAppVeyorAttribute : FactAttribute
{
}
}
| apache-2.0 | C# | |
644e01a0b771b51dfef768f312c79fa51136b0ee | Create DylanBerry.cs (#583) | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/DylanBerry.cs | src/Firehose.Web/Authors/DylanBerry.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class DylanBerry : IAmACommunityMember
{
public string FirstName => "Dylan";
public string LastName => "Berry";
public string ShortBioOrTagLine => "Genetically Predisposed Programmer";
public string StateOrRegion => "Toronto, Canada";
public string EmailAddress => "dylanberry@gmail.com";
public string TwitterHandle => "dylbot9000";
public string GravatarHash => "8ef85938904ff43397d50caa9b0eebed";
public string GitHubHandle => "dylanberry";
public GeoPosition Position => new GeoPosition(43.653493, -79.384095);
public Uri WebSite => new Uri("https://www.dylanberry.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.dylanberry.com/feed/"); } }
public string FeedLanguageCode => "en";
}
} | mit | C# | |
1c066719c16f9dc9031413f33b466262b59f6395 | Change DropDownButton, Change Sepparotor name on Menu, Logout if unsuccessful ping Part VII | moscrif/ide,moscrif/ide | components/DropDownRadioButton.cs | components/DropDownRadioButton.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Gtk;
namespace Moscrif.IDE.Components
{
class DropDownRadioButton: DropDownButton
{
public DropDownRadioButton()
{
}
protected override void OnPressed ()
{
//base.OnPressed ();
Gtk.Menu menu = new Gtk.Menu ();
if (menu.Children.Length > 0) {
Gtk.SeparatorMenuItem sep = new Gtk.SeparatorMenuItem ();
sep.Show ();
menu.Insert (sep, -1);
}
Gtk.RadioMenuItem grp = new Gtk.RadioMenuItem ("");
foreach (ComboItem ci in items) {
Gtk.RadioMenuItem mi = new Gtk.RadioMenuItem (grp, ci.Label.Replace ("_","__"));
if (ci.Item == items.CurrentItem || ci.Item.Equals (items.CurrentItem))
mi.Active = true;
ComboItemSet isetLocal = items;
ComboItem ciLocal = ci;
mi.Activated += delegate {
SelectItem (isetLocal, ciLocal);
};
mi.ShowAll ();
menu.Insert (mi, -1);
}
menu.Popup (null, null, PositionFunc, 0, Gtk.Global.CurrentEventTime);
}
}
}
| bsd-3-clause | C# | |
9c471f01a746b1ea38eccced248ec1e752ad0c29 | Enable use of C# 9 records. | sharpjs/PSql,sharpjs/PSql | PSql.Tests/Tests.Support/IsExternalInit.cs | PSql.Tests/Tests.Support/IsExternalInit.cs | /*
Copyright 2021 Jeffrey Sharp
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System.Diagnostics.CodeAnalysis;
#if !NET5_0
namespace System.Runtime.CompilerServices
{
[ExcludeFromCodeCoverage]
internal static class IsExternalInit
{
// The presence of this class is required to make the compiler happy
// when using C# 9 record types on target frameworks < net5.0.
}
}
#endif
| isc | C# | |
709f4889f7a3fa3ba923720db6846730a951295f | Create ext.cs | FrostCat/nefarious-octo-spork | ext.cs | ext.cs | using System.Reflection;
using System.Windows.Forms;
[assembly: AssemblyVersionAttribute("1.0.0.1")]
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("keyfile.snk")]
namespace External
{
public class ext
{
public string thing()
{
return "External.ext.thing(): [" + Assembly.GetExecutingAssembly().FullName + "]";
}
}
}
| mit | C# | |
87c7987bcc3282803ff12363e7c7b85e11cba380 | Add IDuplexSocket interface. | jgoz/netzmq,jgoz/netzmq,jgoz/netzmq,jgoz/netzmq,jgoz/netzmq | src/proj/ZeroMQ/IDuplexSocket.cs | src/proj/ZeroMQ/IDuplexSocket.cs | namespace ZeroMQ
{
/// <summary>
/// A socket that is capable of both sending and receiving messages to and from remote endpoints.
/// </summary>
public interface IDuplexSocket
: ISendSocket, IReceiveSocket
{
}
}
| apache-2.0 | C# | |
aea2f7b45accfceb8e518f7c2ddb3cf7560706b6 | Allow running gzip-ped script from URL | filipw/dotnet-script,filipw/dotnet-script | src/Dotnet.Script.Core/ScriptDownloader.cs | src/Dotnet.Script.Core/ScriptDownloader.cs | using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Threading.Tasks;
namespace Dotnet.Script.Core
{
public class ScriptDownloader
{
public async Task<string> Download(string uri)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(uri))
{
response.EnsureSuccessStatusCode();
using (HttpContent content = response.Content)
{
var mediaType = content.Headers.ContentType.MediaType?.ToLowerInvariant().Trim();
switch (mediaType)
{
case null:
case "":
case "text/plain":
return await content.ReadAsStringAsync();
case "application/gzip":
case "application/x-gzip":
using (var stream = await content.ReadAsStreamAsync())
using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzip))
return await reader.ReadToEndAsync();
default:
throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https");
}
}
}
}
}
}
}
| using System;
using System.IO;
using System.Net.Http;
using System.Net.Mime;
using System.Threading.Tasks;
namespace Dotnet.Script.Core
{
public class ScriptDownloader
{
public async Task<string> Download(string uri)
{
const string plainTextMediaType = "text/plain";
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(uri))
{
response.EnsureSuccessStatusCode();
using (HttpContent content = response.Content)
{
string mediaType = content.Headers.ContentType.MediaType;
if (string.IsNullOrWhiteSpace(mediaType) || mediaType.Equals(plainTextMediaType, StringComparison.InvariantCultureIgnoreCase))
{
return await content.ReadAsStringAsync();
}
throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https");
}
}
}
}
}
}
| mit | C# |
9be21972113ed10a3a31c659575291fb9e0341cc | Add channel lists. | fuyuno/Norma | Norma/Models/AbemaChannels.cs | Norma/Models/AbemaChannels.cs | namespace Norma.Models
{
internal enum AbemaChannels
{
/// <summary>
/// 1ch - Abema news/
/// </summary>
AbemaNews,
/// <summary>
/// 2ch - Abema SPECIAL
/// </summary>
AbemaSpecial,
/// <summary>
/// 3ch - SPECIAL PLUS
/// </summary>
SpecialPlus,
/// <summary>
/// 4ch - REALITY SHOW
/// </summary>
RealityShow,
/// <summary>
/// 5ch - MTV HITS
/// </summary>
MtvHits,
/// <summary>
/// 6ch - SPACE SHOWER MUSIC
/// </summary>
SpaceShowerMusic,
/// <summary>
/// 7ch - ドラマ CHANNEL
/// </summary>
DramaChannel,
/// <summary>
/// 8ch - Documentary
/// </summary>
Documentary,
/// <summary>
/// 9ch - バラエティ CHANNEL
/// </summary>
VarietyChannel,
/// <summary>
/// 10ch - ペット
/// </summary>
Pet,
/// <summary>
/// 11ch - CLUB CHANNEL
/// </summary>
ClubChannel,
/// <summary>
/// 12ch - WORLD SPORTS
/// </summary>
WorldSports,
/// <summary>
/// 13ch - ヨコノリ Surf Snow Skate
/// </summary>
YokonoriSports,
/// <summary>
/// 14ch - VICE
/// </summary>
Vice,
/// <summary>
/// 15ch - アニメ24
/// </summary>
Anime24,
/// <summary>
/// 16ch - 深夜アニメ
/// </summary>
MidnightAnime,
/// <summary>
/// 17ch - なつかしアニメ
/// </summary>
OldtimeAnime,
/// <summary>
/// 18ch - 家族アニメ
/// </summary>
FamilyAnime,
/// <summary>
/// 19ch - EDGE SPORT HD
/// </summary>
EdgeSportHd,
/// <summary>
/// 20ch - 釣り
/// </summary>
Fishing,
/// <summary>
/// 21ch - 麻雀
/// </summary>
Mahjong,
/// <summary>
/// 22ch - AbemaTV FRESH!
/// </summary>
AbemaTvFresh
}
} | mit | C# | |
1f781ef82088c69d0c76bec22d43c498f1e794bd | Add Q172 | txchen/localleet | csharp/Q172_FactorialTrailingZeroes.cs | csharp/Q172_FactorialTrailingZeroes.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// Given an integer n, return the number of trailing zeroes in n!.
//
// Note: Your solution should be in logarithmic time complexity.
// https://leetcode.com/problems/factorial-trailing-zeroes/
namespace LocalLeet
{
public class Q172
{
public int TrailingZeroes(int n)
{
int answer = 0;
int fives = n / 5 ;
while (fives > 0)
{
answer += fives;
fives /= 5;
}
return answer;
}
[Fact]
public void Q172_FactorialTrailingZeroes()
{
TestHelper.Run(input => TrailingZeroes(input.EntireInput.ToInt()).ToString());
}
}
}
| mit | C# | |
9541dd559b85d1b86ea525d319afd45f1856536d | Use rtvs::send_message directly instead of rtvs::browser. | karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS | src/Package/Impl/Repl/Session/RSessionEvaluationCommands.cs | src/Package/Impl/Repl/Session/RSessionEvaluationCommands.cs | using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.R.Host.Client;
using Microsoft.R.Support.Settings;
using Microsoft.VisualStudio.R.Package.RPackages.Mirrors;
namespace Microsoft.VisualStudio.R.Package.Repl.Session
{
public static class RSessionEvaluationCommands {
public static Task OptionsSetWidth(this IRSessionEvaluation evaluation, int width) {
return evaluation.EvaluateNonReentrantAsync($"options(width=as.integer({width}))\n");
}
public static Task SetWorkingDirectory(this IRSessionEvaluation evaluation, string path) {
return evaluation.EvaluateNonReentrantAsync($"setwd('{path.Replace('\\', '/')}')\n");
}
public static Task SetDefaultWorkingDirectory(this IRSessionEvaluation evaluation) {
return evaluation.EvaluateNonReentrantAsync($"setwd('~')\n");
}
public static Task<REvaluationResult> LoadWorkspace(this IRSessionEvaluation evaluation, string path) {
return evaluation.EvaluateNonReentrantAsync($"load('{path.Replace('\\', '/')}', .GlobalEnv)\n");
}
public static Task<REvaluationResult> SaveWorkspace(this IRSessionEvaluation evaluation, string path) {
return evaluation.EvaluateNonReentrantAsync($"save.image(file='{path.Replace('\\', '/')}')\n");
}
public static Task<REvaluationResult> SetVsGraphicsDevice(this IRSessionEvaluation evaluation) {
var script = @"
.rtvs.vsgd <- function() {
.External('C_vsgd', 5, 5)
}
options(device='.rtvs.vsgd')
";
return evaluation.EvaluateAsync(script);
}
public static Task<REvaluationResult> SetVsCranSelection(this IRSessionEvaluation evaluation, string mirrorUrl)
{
var script =
@" local({
r <- getOption('repos')
r['CRAN'] <- '" + mirrorUrl + @"'
options(repos = r)})";
return evaluation.EvaluateAsync(script);
}
public static Task<REvaluationResult> SetVsHelpRedirection(this IRSessionEvaluation evaluation) {
var script =
@"options(browser = function(url) {
.Call('rtvs::Call.send_message', 'Browser', rtvs:::toJSON(url))
})";
return evaluation.EvaluateAsync(script);
}
private static Task<REvaluationResult> EvaluateNonReentrantAsync(this IRSessionEvaluation evaluation, FormattableString commandText) {
return evaluation.EvaluateAsync(FormattableString.Invariant(commandText));
}
}
} | using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.R.Host.Client;
using Microsoft.R.Support.Settings;
using Microsoft.VisualStudio.R.Package.RPackages.Mirrors;
namespace Microsoft.VisualStudio.R.Package.Repl.Session
{
public static class RSessionEvaluationCommands {
public static Task OptionsSetWidth(this IRSessionEvaluation evaluation, int width) {
return evaluation.EvaluateNonReentrantAsync($"options(width=as.integer({width}))\n");
}
public static Task SetWorkingDirectory(this IRSessionEvaluation evaluation, string path) {
return evaluation.EvaluateNonReentrantAsync($"setwd('{path.Replace('\\', '/')}')\n");
}
public static Task SetDefaultWorkingDirectory(this IRSessionEvaluation evaluation) {
return evaluation.EvaluateNonReentrantAsync($"setwd('~')\n");
}
public static Task<REvaluationResult> LoadWorkspace(this IRSessionEvaluation evaluation, string path) {
return evaluation.EvaluateNonReentrantAsync($"load('{path.Replace('\\', '/')}', .GlobalEnv)\n");
}
public static Task<REvaluationResult> SaveWorkspace(this IRSessionEvaluation evaluation, string path) {
return evaluation.EvaluateNonReentrantAsync($"save.image(file='{path.Replace('\\', '/')}')\n");
}
public static Task<REvaluationResult> SetVsGraphicsDevice(this IRSessionEvaluation evaluation) {
var script = @"
.rtvs.vsgd <- function() {
.External('C_vsgd', 5, 5)
}
options(device='.rtvs.vsgd')
";
return evaluation.EvaluateAsync(script);
}
public static Task<REvaluationResult> SetVsCranSelection(this IRSessionEvaluation evaluation, string mirrorUrl)
{
var script =
@" local({
r <- getOption('repos')
r['CRAN'] <- '" + mirrorUrl + @"'
options(repos = r)})";
return evaluation.EvaluateAsync(script);
}
public static Task<REvaluationResult> SetVsHelpRedirection(this IRSessionEvaluation evaluation) {
var script =
@"options(browser = function(url) {
.Call('rtvs::Call.browser', url)
})";
return evaluation.EvaluateAsync(script);
}
private static Task<REvaluationResult> EvaluateNonReentrantAsync(this IRSessionEvaluation evaluation, FormattableString commandText) {
return evaluation.EvaluateAsync(FormattableString.Invariant(commandText));
}
}
} | mit | C# |
5bf8363dd5b709c8e6cbc3b6688a4d37b655811d | Add missed paren in comment. | nbarbettini/corefx,gabrielPeart/corefx,parjong/corefx,larsbj1988/corefx,anjumrizwi/corefx,lggomez/corefx,comdiv/corefx,mafiya69/corefx,gabrielPeart/corefx,Alcaro/corefx,billwert/corefx,vrassouli/corefx,JosephTremoulet/corefx,zmaruo/corefx,destinyclown/corefx,rubo/corefx,richlander/corefx,Petermarcu/corefx,s0ne0me/corefx,ellismg/corefx,marksmeltzer/corefx,marksmeltzer/corefx,nelsonsar/corefx,PatrickMcDonald/corefx,vijaykota/corefx,kyulee1/corefx,dotnet-bot/corefx,khdang/corefx,elijah6/corefx,mmitche/corefx,krytarowski/corefx,shrutigarg/corefx,jmhardison/corefx,ericstj/corefx,ravimeda/corefx,rjxby/corefx,cnbin/corefx,alphonsekurian/corefx,benjamin-bader/corefx,krytarowski/corefx,PatrickMcDonald/corefx,erpframework/corefx,oceanho/corefx,akivafr123/corefx,Petermarcu/corefx,chaitrakeshav/corefx,arronei/corefx,axelheer/corefx,dhoehna/corefx,zmaruo/corefx,dtrebbien/corefx,KrisLee/corefx,JosephTremoulet/corefx,rahku/corefx,YoupHulsebos/corefx,Jiayili1/corefx,wtgodbe/corefx,VPashkov/corefx,erpframework/corefx,benpye/corefx,stone-li/corefx,jhendrixMSFT/corefx,vs-team/corefx,shana/corefx,arronei/corefx,lydonchandra/corefx,lydonchandra/corefx,shiftkey-tester/corefx,ravimeda/corefx,stormleoxia/corefx,pgavlin/corefx,nbarbettini/corefx,twsouthwick/corefx,stormleoxia/corefx,benpye/corefx,shana/corefx,lydonchandra/corefx,ptoonen/corefx,vrassouli/corefx,rajansingh10/corefx,fernando-rodriguez/corefx,spoiledsport/corefx,tijoytom/corefx,nchikanov/corefx,jeremymeng/corefx,yizhang82/corefx,erpframework/corefx,vidhya-bv/corefx-sorting,mmitche/corefx,vidhya-bv/corefx-sorting,shmao/corefx,Priya91/corefx-1,scott156/corefx,mazong1123/corefx,ptoonen/corefx,alphonsekurian/corefx,zhangwenquan/corefx,heXelium/corefx,mafiya69/corefx,bpschoch/corefx,josguil/corefx,nchikanov/corefx,PatrickMcDonald/corefx,huanjie/corefx,benpye/corefx,bpschoch/corefx,dtrebbien/corefx,pallavit/corefx,krytarowski/corefx,ericstj/corefx,zhenlan/corefx,krk/corefx,MaggieTsang/corefx,zmaruo/corefx,mazong1123/corefx,jcme/corefx,benpye/corefx,mellinoe/corefx,mokchhya/corefx,cydhaselton/corefx,ptoonen/corefx,claudelee/corefx,shahid-pk/corefx,krk/corefx,rahku/corefx,ellismg/corefx,misterzik/corefx,jlin177/corefx,josguil/corefx,shmao/corefx,stone-li/corefx,stephenmichaelf/corefx,lggomez/corefx,CherryCxldn/corefx,the-dwyer/corefx,andyhebear/corefx,destinyclown/corefx,weltkante/corefx,rahku/corefx,Petermarcu/corefx,n1ghtmare/corefx,shmao/corefx,Alcaro/corefx,rjxby/corefx,richlander/corefx,axelheer/corefx,krk/corefx,stone-li/corefx,rajansingh10/corefx,stephenmichaelf/corefx,comdiv/corefx,Jiayili1/corefx,pallavit/corefx,seanshpark/corefx,Jiayili1/corefx,tijoytom/corefx,parjong/corefx,Yanjing123/corefx,gkhanna79/corefx,jcme/corefx,nbarbettini/corefx,jeremymeng/corefx,DnlHarvey/corefx,anjumrizwi/corefx,scott156/corefx,gregg-miskelly/corefx,andyhebear/corefx,fernando-rodriguez/corefx,janhenke/corefx,690486439/corefx,tstringer/corefx,marksmeltzer/corefx,marksmeltzer/corefx,Priya91/corefx-1,shimingsg/corefx,alexperovich/corefx,SGuyGe/corefx,twsouthwick/corefx,PatrickMcDonald/corefx,jlin177/corefx,kkurni/corefx,Petermarcu/corefx,shrutigarg/corefx,Jiayili1/corefx,ptoonen/corefx,zhenlan/corefx,seanshpark/corefx,alexperovich/corefx,gregg-miskelly/corefx,jhendrixMSFT/corefx,fgreinacher/corefx,stone-li/corefx,brett25/corefx,oceanho/corefx,ViktorHofer/corefx,DnlHarvey/corefx,marksmeltzer/corefx,gregg-miskelly/corefx,Ermiar/corefx,fffej/corefx,FiveTimesTheFun/corefx,elijah6/corefx,rahku/corefx,the-dwyer/corefx,cydhaselton/corefx,khdang/corefx,SGuyGe/corefx,shmao/corefx,akivafr123/corefx,jhendrixMSFT/corefx,adamralph/corefx,axelheer/corefx,ptoonen/corefx,manu-silicon/corefx,MaggieTsang/corefx,uhaciogullari/corefx,690486439/corefx,jhendrixMSFT/corefx,gregg-miskelly/corefx,shiftkey-tester/corefx,cydhaselton/corefx,andyhebear/corefx,rjxby/corefx,tstringer/corefx,cnbin/corefx,ellismg/corefx,gabrielPeart/corefx,jhendrixMSFT/corefx,alexperovich/corefx,bpschoch/corefx,Ermiar/corefx,yizhang82/corefx,vs-team/corefx,ericstj/corefx,cartermp/corefx,scott156/corefx,BrennanConroy/corefx,alexperovich/corefx,khdang/corefx,manu-silicon/corefx,zhangwenquan/corefx,FiveTimesTheFun/corefx,shmao/corefx,stone-li/corefx,n1ghtmare/corefx,billwert/corefx,rjxby/corefx,misterzik/corefx,xuweixuwei/corefx,alphonsekurian/corefx,Frank125/corefx,jhendrixMSFT/corefx,iamjasonp/corefx,seanshpark/corefx,CloudLens/corefx,SGuyGe/corefx,stephenmichaelf/corefx,wtgodbe/corefx,mmitche/corefx,parjong/corefx,adamralph/corefx,spoiledsport/corefx,benpye/corefx,lggomez/corefx,kyulee1/corefx,chenxizhang/corefx,Priya91/corefx-1,mazong1123/corefx,YoupHulsebos/corefx,Chrisboh/corefx,zhenlan/corefx,spoiledsport/corefx,stone-li/corefx,nbarbettini/corefx,parjong/corefx,anjumrizwi/corefx,EverlessDrop41/corefx,akivafr123/corefx,KrisLee/corefx,MaggieTsang/corefx,bitcrazed/corefx,mmitche/corefx,Chrisboh/corefx,akivafr123/corefx,dhoehna/corefx,pgavlin/corefx,matthubin/corefx,mokchhya/corefx,dsplaisted/corefx,bitcrazed/corefx,rjxby/corefx,xuweixuwei/corefx,rajansingh10/corefx,shimingsg/corefx,DnlHarvey/corefx,alexandrnikitin/corefx,thiagodin/corefx,kkurni/corefx,huanjie/corefx,vijaykota/corefx,Jiayili1/corefx,yizhang82/corefx,popolan1986/corefx,shmao/corefx,nchikanov/corefx,MaggieTsang/corefx,shimingsg/corefx,marksmeltzer/corefx,dhoehna/corefx,DnlHarvey/corefx,cartermp/corefx,janhenke/corefx,dotnet-bot/corefx,shiftkey-tester/corefx,EverlessDrop41/corefx,josguil/corefx,gkhanna79/corefx,jlin177/corefx,pallavit/corefx,weltkante/corefx,tijoytom/corefx,CloudLens/corefx,shimingsg/corefx,CherryCxldn/corefx,wtgodbe/corefx,DnlHarvey/corefx,Ermiar/corefx,cartermp/corefx,shimingsg/corefx,rahku/corefx,jlin177/corefx,zhenlan/corefx,rubo/corefx,rahku/corefx,wtgodbe/corefx,tijoytom/corefx,weltkante/corefx,iamjasonp/corefx,the-dwyer/corefx,twsouthwick/corefx,YoupHulsebos/corefx,vrassouli/corefx,richlander/corefx,wtgodbe/corefx,oceanho/corefx,ViktorHofer/corefx,YoupHulsebos/corefx,zhenlan/corefx,tstringer/corefx,tstringer/corefx,andyhebear/corefx,stephenmichaelf/corefx,mazong1123/corefx,alexandrnikitin/corefx,richlander/corefx,erpframework/corefx,chaitrakeshav/corefx,dotnet-bot/corefx,pallavit/corefx,VPashkov/corefx,fffej/corefx,xuweixuwei/corefx,Yanjing123/corefx,josguil/corefx,FiveTimesTheFun/corefx,viniciustaveira/corefx,s0ne0me/corefx,gabrielPeart/corefx,iamjasonp/corefx,ravimeda/corefx,twsouthwick/corefx,Ermiar/corefx,SGuyGe/corefx,mellinoe/corefx,YoupHulsebos/corefx,marksmeltzer/corefx,richlander/corefx,PatrickMcDonald/corefx,nbarbettini/corefx,nbarbettini/corefx,gkhanna79/corefx,Alcaro/corefx,khdang/corefx,n1ghtmare/corefx,pallavit/corefx,alexperovich/corefx,tstringer/corefx,Alcaro/corefx,chenkennt/corefx,CloudLens/corefx,rubo/corefx,vidhya-bv/corefx-sorting,krk/corefx,dtrebbien/corefx,krytarowski/corefx,jeremymeng/corefx,ViktorHofer/corefx,stormleoxia/corefx,jcme/corefx,alexperovich/corefx,vrassouli/corefx,mafiya69/corefx,tstringer/corefx,lggomez/corefx,MaggieTsang/corefx,alexandrnikitin/corefx,seanshpark/corefx,janhenke/corefx,s0ne0me/corefx,Frank125/corefx,ViktorHofer/corefx,Winsto/corefx,ravimeda/corefx,alphonsekurian/corefx,SGuyGe/corefx,chaitrakeshav/corefx,viniciustaveira/corefx,heXelium/corefx,lggomez/corefx,iamjasonp/corefx,mellinoe/corefx,mokchhya/corefx,heXelium/corefx,richlander/corefx,mafiya69/corefx,claudelee/corefx,YoupHulsebos/corefx,shana/corefx,Chrisboh/corefx,690486439/corefx,weltkante/corefx,alphonsekurian/corefx,mokchhya/corefx,ravimeda/corefx,billwert/corefx,ellismg/corefx,JosephTremoulet/corefx,ericstj/corefx,yizhang82/corefx,thiagodin/corefx,Chrisboh/corefx,ericstj/corefx,jcme/corefx,cartermp/corefx,alexandrnikitin/corefx,benjamin-bader/corefx,kkurni/corefx,destinyclown/corefx,shimingsg/corefx,shana/corefx,yizhang82/corefx,vs-team/corefx,elijah6/corefx,Petermarcu/corefx,DnlHarvey/corefx,mmitche/corefx,shiftkey-tester/corefx,gkhanna79/corefx,popolan1986/corefx,jmhardison/corefx,wtgodbe/corefx,gkhanna79/corefx,CherryCxldn/corefx,janhenke/corefx,parjong/corefx,cydhaselton/corefx,manu-silicon/corefx,Ermiar/corefx,690486439/corefx,Petermarcu/corefx,nelsonsar/corefx,stephenmichaelf/corefx,elijah6/corefx,dhoehna/corefx,huanjie/corefx,shahid-pk/corefx,twsouthwick/corefx,fernando-rodriguez/corefx,stone-li/corefx,larsbj1988/corefx,ViktorHofer/corefx,seanshpark/corefx,shahid-pk/corefx,JosephTremoulet/corefx,the-dwyer/corefx,KrisLee/corefx,CloudLens/corefx,dotnet-bot/corefx,josguil/corefx,krytarowski/corefx,zhenlan/corefx,alphonsekurian/corefx,shrutigarg/corefx,anjumrizwi/corefx,rjxby/corefx,cartermp/corefx,benjamin-bader/corefx,rubo/corefx,mazong1123/corefx,jhendrixMSFT/corefx,cnbin/corefx,n1ghtmare/corefx,lggomez/corefx,cydhaselton/corefx,KrisLee/corefx,mellinoe/corefx,zhangwenquan/corefx,jmhardison/corefx,krytarowski/corefx,weltkante/corefx,richlander/corefx,uhaciogullari/corefx,axelheer/corefx,scott156/corefx,adamralph/corefx,kkurni/corefx,Winsto/corefx,chenxizhang/corefx,rjxby/corefx,twsouthwick/corefx,weltkante/corefx,elijah6/corefx,parjong/corefx,thiagodin/corefx,dsplaisted/corefx,Yanjing123/corefx,ravimeda/corefx,BrennanConroy/corefx,rahku/corefx,dhoehna/corefx,kkurni/corefx,jeremymeng/corefx,manu-silicon/corefx,cydhaselton/corefx,krk/corefx,stephenmichaelf/corefx,the-dwyer/corefx,manu-silicon/corefx,dotnet-bot/corefx,brett25/corefx,dkorolev/corefx,nelsonsar/corefx,jmhardison/corefx,misterzik/corefx,JosephTremoulet/corefx,gkhanna79/corefx,mafiya69/corefx,JosephTremoulet/corefx,fffej/corefx,Jiayili1/corefx,viniciustaveira/corefx,benjamin-bader/corefx,iamjasonp/corefx,jlin177/corefx,Chrisboh/corefx,ViktorHofer/corefx,larsbj1988/corefx,jlin177/corefx,akivafr123/corefx,nchikanov/corefx,dkorolev/corefx,benjamin-bader/corefx,vidhya-bv/corefx-sorting,bitcrazed/corefx,krk/corefx,uhaciogullari/corefx,YoupHulsebos/corefx,ptoonen/corefx,shahid-pk/corefx,dkorolev/corefx,huanjie/corefx,dhoehna/corefx,VPashkov/corefx,dtrebbien/corefx,janhenke/corefx,wtgodbe/corefx,MaggieTsang/corefx,nchikanov/corefx,benpye/corefx,ptoonen/corefx,comdiv/corefx,chenxizhang/corefx,mokchhya/corefx,zmaruo/corefx,zhangwenquan/corefx,fgreinacher/corefx,iamjasonp/corefx,ravimeda/corefx,ericstj/corefx,dsplaisted/corefx,SGuyGe/corefx,Ermiar/corefx,arronei/corefx,matthubin/corefx,shrutigarg/corefx,nchikanov/corefx,alexandrnikitin/corefx,bpschoch/corefx,mazong1123/corefx,krk/corefx,weltkante/corefx,n1ghtmare/corefx,billwert/corefx,Frank125/corefx,popolan1986/corefx,Petermarcu/corefx,ViktorHofer/corefx,the-dwyer/corefx,shahid-pk/corefx,vijaykota/corefx,fgreinacher/corefx,jlin177/corefx,matthubin/corefx,khdang/corefx,cnbin/corefx,billwert/corefx,comdiv/corefx,chenkennt/corefx,heXelium/corefx,dhoehna/corefx,fffej/corefx,shmao/corefx,larsbj1988/corefx,rajansingh10/corefx,Frank125/corefx,kkurni/corefx,axelheer/corefx,MaggieTsang/corefx,jcme/corefx,brett25/corefx,manu-silicon/corefx,EverlessDrop41/corefx,lggomez/corefx,bitcrazed/corefx,dkorolev/corefx,vs-team/corefx,claudelee/corefx,yizhang82/corefx,alexperovich/corefx,iamjasonp/corefx,claudelee/corefx,Winsto/corefx,kyulee1/corefx,thiagodin/corefx,Yanjing123/corefx,seanshpark/corefx,cydhaselton/corefx,lydonchandra/corefx,tijoytom/corefx,Priya91/corefx-1,yizhang82/corefx,dotnet-bot/corefx,tijoytom/corefx,fgreinacher/corefx,billwert/corefx,elijah6/corefx,nchikanov/corefx,mmitche/corefx,benjamin-bader/corefx,chaitrakeshav/corefx,janhenke/corefx,Priya91/corefx-1,gkhanna79/corefx,Yanjing123/corefx,oceanho/corefx,dotnet-bot/corefx,shahid-pk/corefx,mmitche/corefx,jcme/corefx,mokchhya/corefx,viniciustaveira/corefx,Priya91/corefx-1,brett25/corefx,parjong/corefx,Jiayili1/corefx,matthubin/corefx,JosephTremoulet/corefx,alphonsekurian/corefx,krytarowski/corefx,tijoytom/corefx,VPashkov/corefx,ellismg/corefx,ericstj/corefx,bitcrazed/corefx,ellismg/corefx,pgavlin/corefx,khdang/corefx,elijah6/corefx,chenkennt/corefx,josguil/corefx,690486439/corefx,s0ne0me/corefx,cartermp/corefx,nelsonsar/corefx,kyulee1/corefx,the-dwyer/corefx,mazong1123/corefx,nbarbettini/corefx,manu-silicon/corefx,uhaciogullari/corefx,billwert/corefx,jeremymeng/corefx,zhenlan/corefx,BrennanConroy/corefx,pgavlin/corefx,Chrisboh/corefx,rubo/corefx,stephenmichaelf/corefx,CherryCxldn/corefx,mafiya69/corefx,stormleoxia/corefx,mellinoe/corefx,Ermiar/corefx,shimingsg/corefx,axelheer/corefx,twsouthwick/corefx,DnlHarvey/corefx,mellinoe/corefx,pallavit/corefx,vidhya-bv/corefx-sorting,seanshpark/corefx | src/System.Diagnostics.Process/tests/ProcessTest_ConsoleApp/ProcessTest_ConsoleApp.cs | src/System.Diagnostics.Process/tests/ProcessTest_ConsoleApp/ProcessTest_ConsoleApp.cs | using System;
using System.Threading;
namespace ProcessTest_ConsoleApp
{
class Program
{
static int Main(string[] args)
{
try
{
if (args.Length > 0)
{
if (args[0].Equals("infinite"))
{
// To avoid potential issues with orphaned processes (say, the test exits before
// exiting the process), we'll say "infinite" is actually 30 seconds.
Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop");
Thread.Sleep(30 * 1000);
}
if (args[0].Equals("error"))
{
Exception ex = new Exception("Intentional Exception thrown");
throw ex;
}
if (args[0].Equals("input"))
{
string str = Console.ReadLine();
}
}
else
{
Console.WriteLine("ProcessTest_ConsoleApp.exe started");
Console.WriteLine("ProcessTest_ConsoleApp.exe closed");
}
return 100;
}
catch (Exception toLog)
{
// We're testing STDERR streams, not the JIT debugger.
// This makes the process behave just like a crashing .NET app, but without the WER invocation
// nor the blocking dialog that comes with it, or the need to suppress that.
Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString()));
return 1;
}
}
}
}
| using System;
using System.Threading;
namespace ProcessTest_ConsoleApp
{
class Program
{
static int Main(string[] args)
{
try
{
if (args.Length > 0)
{
if (args[0].Equals("infinite"))
{
// To avoid potential issues with orphaned processes (say, the test exits before
// exiting the process, we'll say "infinite" is actually 30 seconds.
Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop");
Thread.Sleep(30 * 1000);
}
if (args[0].Equals("error"))
{
Exception ex = new Exception("Intentional Exception thrown");
throw ex;
}
if (args[0].Equals("input"))
{
string str = Console.ReadLine();
}
}
else
{
Console.WriteLine("ProcessTest_ConsoleApp.exe started");
Console.WriteLine("ProcessTest_ConsoleApp.exe closed");
}
return 100;
}
catch (Exception toLog)
{
// We're testing STDERR streams, not the JIT debugger.
// This makes the process behave just like a crashing .NET app, but without the WER invocation
// nor the blocking dialog that comes with it, or the need to suppress that.
Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString()));
return 1;
}
}
}
}
| mit | C# |
2c6d4329f33a7a52264ad43cfba1adf0c14d47f2 | Create AboutBox.cs | GetSomeBlocks/ServerStatus,GetSomeBlocks/Score_Soccer,GetSomeBlocks/ServerStatus,GetSomeBlocks/ServerStatus,GetSomeBlocks/ServerStatus,GetSomeBlocks/ServerStatus,GetSomeBlocks/Score_Soccer,GetSomeBlocks/ServerStatus,GetSomeBlocks/ServerStatus,GetSomeBlocks/Score_Soccer,GetSomeBlocks/Score_Soccer,GetSomeBlocks/Score_Soccer,GetSomeBlocks/Score_Soccer,GetSomeBlocks/Score_Soccer | GUI/AboutBox.cs | GUI/AboutBox.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace OpenHardwareMonitor.GUI {
public partial class AboutBox : Form {
public AboutBox() {
InitializeComponent();
this.Font = SystemFonts.MessageBoxFont;
this.label3.Text = "Version " +
System.Windows.Forms.Application.ProductVersion;
projectLinkLabel.Links.Remove(projectLinkLabel.Links[0]);
projectLinkLabel.Links.Add(0, projectLinkLabel.Text.Length,
"http://openhardwaremonitor.org");
licenseLinkLabel.Links.Remove(licenseLinkLabel.Links[0]);
licenseLinkLabel.Links.Add(0, licenseLinkLabel.Text.Length,
"License.html");
}
private void linkLabel_LinkClicked(object sender,
LinkLabelLinkClickedEventArgs e) {
try {
Process.Start(new ProcessStartInfo(e.Link.LinkData.ToString()));
} catch { }
}
}
}
| mit | C# | |
2a90e500d407f5454771e5c2b02a0bdd58f40fca | add first test for bulk | msbahrul/EventStore,msbahrul/EventStore,ianbattersby/EventStore,msbahrul/EventStore,ianbattersby/EventStore,msbahrul/EventStore,ianbattersby/EventStore,ianbattersby/EventStore,ianbattersby/EventStore,msbahrul/EventStore,msbahrul/EventStore | src/EventStore/EventStore.Core.Tests/TransactionLog/Chunks/when_reading_bulk_a_chunk.cs | src/EventStore/EventStore.Core.Tests/TransactionLog/Chunks/when_reading_bulk_a_chunk.cs | using EventStore.Core.TransactionLog.Chunks;
using NUnit.Framework;
namespace EventStore.Core.Tests.TransactionLog.Chunks
{
[TestFixture]
public class when_reading_bulk_a_chunk : SpecificationWithDirectory
{
[Test]
public void a_read_on_new_file_can_be_performed()
{
base.SetUp();
var chunk = TFChunk.CreateNew(GetFilePathFor("file1"), 2000, 0, 0);
using(var reader = chunk.AcquireReader())
{
var result = reader.ReadNextBytes(1024);
Assert.IsFalse(result.IsEOF);
}
chunk.MarkForDeletion();
chunk.WaitForDestroy(5000);
}
}
} | bsd-3-clause | C# | |
ae83f9d1f3a9aa50191c3cf9d3ef951d196e8999 | Set specs on all tiles at Awake() | jguarShark/Unity2D-Components,cmilr/Unity2D-Components | Tiles/TileSystemManager.cs | Tiles/TileSystemManager.cs | using UnityEngine;
using UnityEngine.Assertions;
public class TileSystemManager : BaseBehaviour
{
private Shader shader;
void Start()
{
shader = Shader.Find("Sprites/Diffuse");
Assert.IsNotNull(shader);
SetChunksToStatic();
DisableShadows();
}
void SetChunksToStatic()
{
foreach (Transform child in transform)
child.gameObject.isStatic = true;
}
void DisableShadows()
{
MeshRenderer[] allChildren = GetComponentsInChildren<MeshRenderer>();
Assert.IsNotNull(allChildren);
foreach (MeshRenderer child in allChildren)
{
child.sharedMaterial.shader = shader;
child.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
child.receiveShadows = false;
child.lightProbeUsage = 0;
child.reflectionProbeUsage = 0;
if (debug_TileMapDisabled)
child.enabled = false;
}
}
}
| mit | C# | |
10243e28fe87de261aeb7e30e9168ccdb3993298 | Create StopJoin.cs | alchemz/ARL_Training | CSharpDotNet_Programming/Thread/StopJoin.cs | CSharpDotNet_Programming/Thread/StopJoin.cs | using System;
using System.Threading;
namespace ThreadTutorial
{
public class StopJoin
{
public void Beta()
{
while (true) {
Console.WriteLine ("Beta is running in its own thread");
}
}
};
public class Simple
{
public static int Main()
{
Console.WriteLine ("Thread Start/Stop/Join Sample");
StopJoin oStop = new StopJoin ();
//create the thread object, passing in the Beta method
Thread oThread= new Thread(new ThreadStart(oStop.Beta));
//start the thread
oThread.Start();
//Spin for a while waiting for the started thread to become alive
while(!oThread.IsAlive);
//put the main thrad to sleep for 1 millisecond to allow oThread
Thread.Sleep(1);
//request that oThread be stopped
oThread.Abort();
//wait until oThread finishes,Join also has overloads that takes a ms
//interval ot a TimeSpan object
oThread.Join();
Console.WriteLine();
Console.WriteLine("Beta has finished");
try
{
Console.WriteLine("Try to restart the StopJoin.Beta thread");
oThread.Start();
}
catch(ThreadStateException)
{
Console.WriteLine ("ThreadStateException trying to restart StopJoin.Beta");
Console.WriteLine ("Excepted since aborted threads cannot be restarted.");
}
return 0;
}
}
}
| mit | C# | |
0f373acacb55be124e573144a8b112291ea82fdd | Add test scene | UselessToucan/osu,peppy/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu | osu.Game.Tests/Visual/Multiplayer/TestSceneTimeshiftResultsScreen.cs | osu.Game.Tests/Visual/Multiplayer/TestSceneTimeshiftResultsScreen.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 NUnit.Framework;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.Multiplayer;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Multi.Ranking;
using osu.Game.Tests.Beatmaps;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneTimeshiftResultsScreen : ScreenTestScene
{
[Test]
public void TestShowResults()
{
var score = new TestScoreInfo(new OsuRuleset().RulesetInfo);
var roomScores = new List<RoomScore>();
for (int i = 0; i < 10; i++)
{
roomScores.Add(new RoomScore
{
ID = i,
Accuracy = 0.9 - 0.01 * i,
EndedAt = DateTimeOffset.Now.Subtract(TimeSpan.FromHours(i)),
Passed = true,
Rank = ScoreRank.B,
MaxCombo = 999,
TotalScore = 999999 - i * 1000,
User = new User
{
Id = 2,
Username = $"peppy{i}",
CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg",
},
Statistics =
{
{ HitResult.Miss, 1 },
{ HitResult.Meh, 50 },
{ HitResult.Good, 100 },
{ HitResult.Great, 300 },
}
});
}
AddStep("bind request handler", () => ((DummyAPIAccess)API).HandleRequest = request =>
{
switch (request)
{
case GetRoomPlaylistScoresRequest r:
r.TriggerSuccess(roomScores);
break;
}
});
AddStep("load results", () =>
{
LoadScreen(new TimeshiftResultsScreen(score, 1, new PlaylistItem
{
Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo },
Ruleset = { Value = new OsuRuleset().RulesetInfo }
}));
});
AddWaitStep("wait for display", 10);
}
}
}
| mit | C# | |
1daacec6a2e275aa2a93c9635c9bd628d8826a1c | Add server modules phrases class | RapidScada/scada,RapidScada/scada,RapidScada/scada,RapidScada/scada | ScadaServer/ScadaServerCommon/ModPhrases.cs | ScadaServer/ScadaServerCommon/ModPhrases.cs | /*
* Copyright 2015 Mikhail Shiryaev
*
* 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.
*
*
* Product : Rapid SCADA
* Module : ScadaServerCommon
* Summary : The phrases used in server modules
*
* Author : Mikhail Shiryaev
* Created : 2015
* Modified : 2015
*/
#pragma warning disable 1591 // отключение warning CS1591: Missing XML comment for publicly visible type or member
namespace Scada.Server.Modules
{
/// <summary>
/// The phrases used in server modules
/// <para>Фразы, используемые серверными модулями</para>
/// </summary>
public static class ModPhrases
{
static ModPhrases()
{
SetToDefault();
InitOnLocalization();
}
// Словарь Scada.Server.Modules
public static string LoadCommSettingsError { get; private set; }
public static string SaveCommSettingsError { get; private set; }
public static string LoadModSettingsError { get; private set; }
public static string SaveModSettingsError { get; private set; }
// Фразы, устанавливаемые в зависимости от локализации, не загружая из словаря
public static string StartModule { get; private set; }
public static string StopModule { get; private set; }
public static string NormalModExecImpossible { get; private set; }
private static void SetToDefault()
{
LoadCommSettingsError = "Ошибка при загрузке настроек соединения с сервером";
SaveCommSettingsError = "Ошибка при сохранении настроек соединения с сервером";
LoadModSettingsError = "Ошибка при загрузке настроек модуля";
SaveModSettingsError = "Ошибка при сохранении настроек модуля";
}
private static void InitOnLocalization()
{
if (Localization.UseRussian)
{
StartModule = "Запуск работы модуля {0}";
StopModule = "Работа модуля {0} завершена";
NormalModExecImpossible = "Нормальная работа модуля невозможна";
}
else
{
StartModule = "Start {0} module";
StopModule = "Module {0} is stopped";
NormalModExecImpossible = "Normal module execution is impossible";
}
}
public static void InitFromDictionaries()
{
Localization.Dict dict;
if (Localization.Dictionaries.TryGetValue("Scada.Server", out dict))
{
LoadCommSettingsError = dict.GetPhrase("LoadCommSettingsError", LoadCommSettingsError);
SaveCommSettingsError = dict.GetPhrase("SaveCommSettingsError", SaveCommSettingsError);
LoadModSettingsError = dict.GetPhrase("LoadModSettingsError", LoadModSettingsError);
SaveModSettingsError = dict.GetPhrase("SaveModSettingsError", SaveModSettingsError);
}
}
}
}
| apache-2.0 | C# | |
0b0c83b1c0add640878e80fd74e6666da3b8c2a6 | add custom deserializer | ceee/PocketSharp | PocketSharp/JsonDeserializer.cs | PocketSharp/JsonDeserializer.cs | using RestSharp;
using RestSharp.Deserializers;
using ServiceStack.Text;
namespace PocketSharp
{
public class JsonDeserializer : IDeserializer
{
public const string JsonContentType = "application/json";
/// <summary>
/// Deserializes the specified response.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="response">The response.</param>
/// <returns></returns>
public T Deserialize<T>(IRestResponse response)
{
var x = JsonSerializer.DeserializeFromString<T>(response.Content);
return x;
}
public string DateFormat { get; set; }
public string Namespace { get; set; }
public string RootElement { get; set; }
public string ContentType
{
get { return JsonContentType; }
}
}
}
| mit | C# | |
b55a04ee92a21704a0d7a1cfe53bb8ab6a8d2f87 | Create Problem40.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem40.cs | Problems/Problem40.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProjectEuler
{
class Problem40
{
private int upper = -1;
public Problem40(int u)
{
upper = u;
}
public int Run()
{
int res = 1;
int i = 0;
int num = 1;
string numS = "1";
while (i < upper)
{
if (numS.Length == 0)
{
num++;
numS = num.ToString();
}
int top = int.Parse(numS[0].ToString());
numS = numS.Substring(1);
i++;
if (i == 1 || i == 10 || i == 100 || i == 1000 || i == 10000 || i == 100000 || i == 1000000)
{
Console.WriteLine(" " + top.ToString());
res *= top;
}
}
return res;
}
}
}
| mit | C# | |
d0bde4a3619a6b6f3fa698f9ee9ab6b9e386728d | Copy CriticalFinalizerSources from CoreCLR | botaberg/corert,krytarowski/corert,botaberg/corert,shrah/corert,shrah/corert,tijoytom/corert,sandreenko/corert,botaberg/corert,sandreenko/corert,gregkalapos/corert,krytarowski/corert,tijoytom/corert,tijoytom/corert,gregkalapos/corert,yizhang82/corert,shrah/corert,shrah/corert,gregkalapos/corert,krytarowski/corert,krytarowski/corert,yizhang82/corert,sandreenko/corert,gregkalapos/corert,yizhang82/corert,sandreenko/corert,botaberg/corert,yizhang82/corert,tijoytom/corert | src/System.Private.CoreLib/src/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs | src/System.Private.CoreLib/src/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
/*============================================================
**
**
**
** Deriving from this class will cause any finalizer you define to be critical
** (i.e. the finalizer is guaranteed to run, won't be aborted by the host and is
** run after the finalizers of other objects collected at the same time).
**
** You must possess UnmanagedCode permission in order to derive from this class.
**
**
===========================================================*/
using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;
namespace System.Runtime.ConstrainedExecution
{
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class CriticalFinalizerObject
{
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalFinalizerObject()
{
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~CriticalFinalizerObject()
{
}
}
}
| mit | C# | |
7875300fce4d1cde5600c07ccfbc041ef1419859 | Add missing view file | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerCommitments/Acknowlegement.cshtml | src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerCommitments/Acknowlegement.cshtml |
<div class="grid-row">
<div class="column-two-thirds">
<div class="govuk-box-highlight">
<h1 class="heading-xlarge" id="changeHeadline">
Sent to provider
</h1>
<p id="changeRefNumber">
Your reference number is <br>
<strong class="heading-medium">98HGS3F</strong>
</p>
</div>
<h2 class="heading-medium">What happens next?</h2>
<p id="changeMainCopy">The employer will log on to their account and see the changes you’ve made. They’ll then either approve them or send the cohort back to you to make changes.</p>
</div>
<div class="column-one-third">
</div>
</div> | mit | C# | |
e5799a215d1ee66a049ed9ede7f7b280853e55cf | Add CasBool32 | whampson/bft-spec,whampson/cascara | Src/WHampson.Cascara/Types/CasBool32.cs | Src/WHampson.Cascara/Types/CasBool32.cs | #region License
/* Copyright (c) 2017 Wes Hampson
*
* 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.
*/
#endregion
using System;
using System.Runtime.InteropServices;
namespace WHampson.Cascara.Types
{
[StructLayout(LayoutKind.Sequential)]
public struct CasBool32 : ICascaraType,
IComparable, IComparable<CasBool32>, IEquatable<CasBool32>
{
private const int Size = 4;
private CasInt32 m_value;
private CasBool32(bool value)
{
m_value = (value) ? 1 : 0;
}
private bool BoolValue
{
get { return (int) m_value != 0; }
}
public int CompareTo(CasBool32 other)
{
if (BoolValue == other.BoolValue)
{
return 0;
}
else if (BoolValue == false)
{
return -1;
}
return 1;
}
public bool Equals(CasBool32 other)
{
return BoolValue == other.BoolValue;
}
int IComparable.CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is CasBool32))
{
string fmt = "Object is not an instance of {0}.";
string msg = string.Format(fmt, GetType().Name);
throw new ArgumentException(msg, "obj");
}
return CompareTo((CasBool32) obj);
}
byte[] ICascaraType.GetBytes()
{
return ((ICascaraType) m_value).GetBytes();
}
int ICascaraType.GetSize()
{
return Size;
}
public override bool Equals(object obj)
{
if (!(obj is CasBool32))
{
return false;
}
return Equals((CasBool32) obj);
}
public override int GetHashCode()
{
return (BoolValue) ? 1 : 0;
}
public override string ToString()
{
return BoolValue.ToString();
}
public static implicit operator CasBool32(bool value)
{
return new CasBool32(value);
}
public static explicit operator bool(CasBool32 value)
{
return value.BoolValue;
}
}
}
| mit | C# | |
15f3438231853f3702ea23732497fefe27558e93 | Create HtmlSanitizerOptions.cs | mganss/HtmlSanitizer | src/HtmlSanitizer/HtmlSanitizerOptions.cs | src/HtmlSanitizer/HtmlSanitizerOptions.cs | using System;
using System.Collections.Generic;
namespace Ganss.XSS
{
public class HtmlSanitizerOptions
{
public ICollection<string> AllowedTags { get; set; } = new HashSet<string>();
public ICollection<string> AllowedAttributes { get; set; } = new HashSet<string>();
public ICollection<string> AllowedCssProperties { get; set; } = new HashSet<string>();
public ICollection<string> AllowedAtRules { get; set; } = new HashSet<string>();
public ICollection<string> AllowedSchemes { get; set; } = new HashSet<string>();
public ICollection<string> UriAttributes { get; set; } = new HashSet<string>();
}
}
| mit | C# | |
5da70cbf9d763c8fa361ef5d3e93604a4f503bba | Add MetaConverter | riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy | src/DotvvmAcademy.Meta/MetaConverter.cs | src/DotvvmAcademy.Meta/MetaConverter.cs | using DotvvmAcademy.Meta.Syntax;
using Microsoft.CodeAnalysis;
using System.Collections.Generic;
using System.Reflection;
namespace DotvvmAcademy.Meta
{
public class MetaConverter
{
public NameNode ToMeta(ISymbol symbol)
{
var visitor = new MetaSymbolVisitor();
return visitor.Visit(symbol);
}
public NameNode ToMeta(MemberInfo info)
{
var visitor = new MetaMemberInfoVisitor();
return visitor.Visit(info);
}
public IEnumerable<MemberInfo> ToReflection(NameNode node, IEnumerable<Assembly> assemblies)
{
var visitor = new ReflectionNameNodeVisitor(assemblies);
return visitor.Visit(node);
}
public IEnumerable<MemberInfo> ToReflection(ISymbol symbol, IEnumerable<Assembly> assemblies)
{
var visitor = new ReflectionSymbolVisitor(assemblies);
return visitor.Visit(symbol);
}
public IEnumerable<ISymbol> ToRoslyn(NameNode node, Compilation compilation)
{
var visitor = new RoslynNameNodeVisitor(compilation);
return visitor.Visit(node);
}
public IEnumerable<ISymbol> ToRoslyn(MemberInfo info, Compilation compilation)
{
var visitor = new RoslynMemberInfoVisitor(compilation);
return visitor.Visit(info);
}
}
} | apache-2.0 | C# | |
a50e9a0270045384fff07123ddf34a330597c685 | Create ChallengeResponseFailedEvent.cs | skrusty/AsterNET,AsterNET/AsterNET | Asterisk.2013/Asterisk.NET/Manager/Event/ChallengeResponseFailedEvent.cs | Asterisk.2013/Asterisk.NET/Manager/Event/ChallengeResponseFailedEvent.cs | namespace AsterNET.Manager.Event
{
/// <summary>
/// Raised when a request's attempt to authenticate has been challenged, and the request failed the authentication challenge.<br />
/// </summary>
public class ChallengeResponseFailedEvent : ManagerEvent
{
public ChallengeResponseFailedEvent(ManagerConnection source)
: base(source)
{
}
public string Status { get; set; }
}
}
| mit | C# | |
869ac24ae8e29cf4a101e68c798fdc636fe1b656 | Add test for F.Last | farity/farity | Farity.Tests/LastTests.cs | Farity.Tests/LastTests.cs | using Xunit;
using System.Linq;
namespace Farity.Tests
{
public class LastTests
{
[Fact]
public void LastReturnsLastElement()
{
var data = new[] { 1, 2, 3, 4, 5 };
var expected = 5;
var actual = F.Last(data);
Assert.Equal(expected, actual);
}
}
}
| mit | C# | |
b242f89bc0ba8e4752aeeeadb95eab64d6295183 | Create RequestHeaderTests.cs | PKRoma/RestSharp,restsharp/RestSharp | RestSharp.Tests/RequestHeaderTests.cs | RestSharp.Tests/RequestHeaderTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
namespace RestSharp.Tests
{
public class RequestHeaderTests
{
[Test]
public void AddHeaders_SameCaseDuplicatesExist_ThrowsException()
{
ICollection<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Accept", "application/json"),
new KeyValuePair<string, string>("Accept-Language", "en-us,en;q=0.5"),
new KeyValuePair<string, string>("Keep-Alive", "300"),
new KeyValuePair<string, string>("Accept", "application/json")
};
RestRequest request = new RestRequest();
ArgumentException exception = Assert.Throws<ArgumentException>(() => request.AddHeaders(headers));
Assert.AreEqual("Duplicate header names exist: ACCEPT", exception.Message);
}
}
}
| apache-2.0 | C# | |
eeb5f3d5191f87f20e9582caabab5792ab69bf2e | Add basic test scene | peppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,ppy/osu | osu.Game.Tests/Visual/Gameplay/TestScenePerformancePointsCounter.cs | osu.Game.Tests/Visual/Gameplay/TestScenePerformancePointsCounter.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.Diagnostics;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestScenePerformancePointsCounter : OsuTestScene
{
[Cached]
private GameplayState gameplayState;
[Cached]
private ScoreProcessor scoreProcessor;
private int iteration;
public TestScenePerformancePointsCounter()
{
var ruleset = CreateRuleset();
Debug.Assert(ruleset != null);
var beatmap = CreateWorkingBeatmap(ruleset.RulesetInfo)
.GetPlayableBeatmap(ruleset.RulesetInfo);
gameplayState = new GameplayState(beatmap, ruleset);
scoreProcessor = new ScoreProcessor();
}
protected override Ruleset CreateRuleset() => new OsuRuleset();
[SetUpSteps]
public void SetUpSteps()
{
AddStep("Create counter", () =>
{
Child = new PerformancePointsCounter
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Scale = new Vector2(5),
};
});
AddRepeatStep("Add judgement", () =>
{
var scoreInfo = gameplayState.Score.ScoreInfo;
scoreInfo.MaxCombo = iteration * 1000;
scoreInfo.Accuracy = 1;
scoreInfo.Statistics[HitResult.Great] = iteration * 1000;
scoreProcessor.ApplyResult(new OsuJudgementResult(new HitObject
{
StartTime = iteration * 10000,
}, new OsuJudgement())
{
Type = HitResult.Perfect,
});
iteration++;
}, 10);
AddStep("Revert judgement", () =>
{
scoreProcessor.RevertResult(new JudgementResult(new HitObject(), new OsuJudgement()));
});
}
}
}
| mit | C# | |
02c2c72c0d91b14ccc0a157c313a3dd4349a7809 | add a defaultprogram | jmrnilsson/efpad,jmrnilsson/efpad,jmrnilsson/efpad,jmrnilsson/efpad | c_scaffold/Program.cs | c_scaffold/Program.cs | using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Data.Entity;
namespace c_scaffold
{
public class Program
{
public static void Main()
{
using (var db = new blogContext())
{
var start = DateTime.UtcNow;
var items =
(
from p in db.Post
select new {p.Blog.Url, p.Title, p.Content}
).ToList();
var duration = DateTime.UtcNow - start;
foreach(var item in items)
{
Console.WriteLine("{0} - {1} - {2}", item.Url, item.Title, item.Content);
}
Console.WriteLine();
Console.WriteLine("{0} records read in {1} ms ", items.Count(), duration.TotalMilliseconds);
Console.WriteLine("Total of {0} ms per record", duration.TotalMilliseconds / items.Count());
}
}
}
} | mit | C# | |
8e8c9886836b6307860badbbbd7fd9493d073634 | Add Activation class | kawatan/Milk | Megalopolis/Layers/Activation.cs | Megalopolis/Layers/Activation.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Megalopolis.ActivationFunctions;
namespace Megalopolis
{
namespace Layers
{
public class Activation : Layer
{
private double[][] internalOutputs = null;
private IActivationFunction activationFunction = null;
public IActivationFunction ActivationFunction
{
get
{
return this.activationFunction;
}
}
public Activation(Layer layer, IActivationFunction activationFunction) : base(layer, layer.Outputs)
{
this.activationFunction = activationFunction;
}
public override Batch<double[]> Forward(Batch<double[]> inputs, bool isTraining)
{
var parallelOptions = new ParallelOptions();
this.internalOutputs = new double[inputs.Size][];
parallelOptions.MaxDegreeOfParallelism = 2 * Environment.ProcessorCount;
Parallel.ForEach<double[], List<Tuple<long, double[]>>>(inputs, parallelOptions, () => new List<Tuple<long, double[]>>(), (vector, state, index, local) =>
{
var activations = new double[this.outputs];
for (int i = 0; i < this.outputs; i++)
{
activations[i] = this.activationFunction.Function(vector[i]);
}
local.Add(Tuple.Create<long, double[]>(index, activations));
return local;
}, (local) =>
{
lock (this.internalOutputs)
{
local.ForEach(x =>
{
this.internalOutputs[x.Item1] = x.Item2;
});
}
});
return new Batch<double[]>(this.internalOutputs);
}
public override Batch<double[]> Backward(Batch<double[]> deltas)
{
var parallelOptions = new ParallelOptions();
var data = new double[deltas.Size][];
var tuple = Tuple.Create<double[][], double[][]>(new double[deltas.Size][], new double[deltas.Size][]);
parallelOptions.MaxDegreeOfParallelism = 2 * Environment.ProcessorCount;
Parallel.ForEach<double[], List<Tuple<long, double[]>>>(deltas, parallelOptions, () => new List<Tuple<long, double[]>>(), (vector1, state, index, local) =>
{
var vector2 = new double[this.outputs];
for (int i = 0; i < this.outputs; i++)
{
vector2[i] = this.activationFunction.Derivative(this.internalOutputs[index][i]) * vector1[i];
}
local.Add(Tuple.Create<long, double[]>(index, vector2));
return local;
}, (local) =>
{
lock (data)
{
local.ForEach(x =>
{
data[x.Item1] = x.Item2;
});
}
});
return new Batch<double[]>(data);
}
}
}
}
| apache-2.0 | C# | |
a1fcf4869bfdc1fd4f0b535f2da12a5c145e4cb9 | Create AssemblyInfo.cs | daniela1991/hack4europecontest | AssemblyInfo.cs | AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Cdiscount.OpenApi.ProxyClient")]
[assembly: AssemblyDescription("A thinwrapper on top of the Cdiscount Open API. Allows to search for products, retrieve information and manage a cdiscount shopping cart.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniela Marc")]
[assembly: AssemblyProduct("Cdiscount.OpenApi.ProxyClient")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# | |
2d6528960b57047f77cd6e4c1fdb0064beac8f9a | add mapnote class | kidchenko/windows-phone | MapNotesApp/MapNotesApp/DataModel/MapNote.cs | MapNotesApp/MapNotesApp/DataModel/MapNote.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapNotesApp.DataModel
{
public class MapNote
{
public string Title { get; set; }
public string Note { get; set; }
public DateTime Created { get; set; }
public double Longitude { get; set; }
public double Latitude { get; set; }
}
}
| mit | C# | |
0ca7ed8bd797f646b836fba7dc1e1dd9553a3776 | Fix BugsnagUserManager typo. | eatskolnikov/mobile,peeedge/mobile,masterrr/mobile,eatskolnikov/mobile,peeedge/mobile,eatskolnikov/mobile,masterrr/mobile,ZhangLeiCharles/mobile,ZhangLeiCharles/mobile | Phoebe/Net/BugsnagUserManager.cs | Phoebe/Net/BugsnagUserManager.cs | using System;
using Toggl.Phoebe;
using Toggl.Phoebe.Bugsnag;
using Toggl.Phoebe.Data;
using Toggl.Phoebe.Data.Models;
using Toggl.Phoebe.Net;
using XPlatUtils;
namespace Toggl.Joey.Net
{
public class BugsnagUserManager
{
#pragma warning disable 0414
private readonly Subscription<AuthChangedMessage> subscriptionAuthChanged;
private readonly Subscription<ModelChangedMessage> subscriptionModelChanged;
#pragma warning restore 0414
private UserModel currentUser;
public BugsnagUserManager ()
{
var bus = ServiceContainer.Resolve<MessageBus> ();
subscriptionAuthChanged = bus.Subscribe<AuthChangedMessage> (OnAuthChangedMessage);
subscriptionModelChanged = bus.Subscribe<ModelChangedMessage> (OnModelChangedMessage);
currentUser = ServiceContainer.Resolve<AuthManager> ().User;
OnUserChanged ();
}
private void OnAuthChangedMessage (AuthChangedMessage msg)
{
currentUser = ServiceContainer.Resolve<AuthManager> ().User;
OnUserChanged ();
}
private void OnModelChangedMessage (ModelChangedMessage msg)
{
if (currentUser == null || msg.Model != currentUser)
return;
if (msg.PropertyName == UserModel.PropertyRemoteId
|| msg.PropertyName == UserModel.PropertyEmail
|| msg.PropertyName == UserModel.PropertyName) {
OnUserChanged ();
}
}
private void OnUserChanged ()
{
var bugsnag = ServiceContainer.Resolve<BugsnagClient> ();
if (currentUser == null) {
bugsnag.SetUser (null, null, null);
} else {
string id = currentUser.RemoteId.HasValue ? currentUser.RemoteId.ToString () : null;
bugsnag.SetUser (id, currentUser.Email, currentUser.Name);
}
}
}
}
| using System;
using Toggl.Phoebe;
using Toggl.Phoebe.Bugsnag;
using Toggl.Phoebe.Data;
using Toggl.Phoebe.Data.Models;
using Toggl.Phoebe.Net;
using XPlatUtils;
namespace Toggl.Joey.Net
{
public class BugsnagUserManager
{
#pragma warning disable 0414
private readonly Subscription<AuthChangedMessage> subscriptionAuthChanged;
private readonly Subscription<ModelChangedMessage> subscriptionModelChanged;
#pragma warning restore 0414
private UserModel currentUser;
public BugsnagUserManager ()
{
var bus = ServiceContainer.Resolve<MessageBus> ();
subscriptionAuthChanged = bus.Subscribe<AuthChangedMessage> (OnAuthChangedMessage);
subscriptionAuthChanged = bus.Subscribe<ModelChangedMessage> (OnModelChangedMessage);
currentUser = ServiceContainer.Resolve<AuthManager> ().User;
OnUserChanged ();
}
private void OnAuthChangedMessage (AuthChangedMessage msg)
{
currentUser = ServiceContainer.Resolve<AuthManager> ().User;
OnUserChanged ();
}
private void OnModelChangedMessage (ModelChangedMessage msg)
{
if (currentUser == null || msg.Model != currentUser)
return;
if (msg.PropertyName == UserModel.PropertyRemoteId
|| msg.PropertyName == UserModel.PropertyEmail
|| msg.PropertyName == UserModel.PropertyName) {
OnUserChanged ();
}
}
private void OnUserChanged ()
{
var bugsnag = ServiceContainer.Resolve<BugsnagClient> ();
if (currentUser == null) {
bugsnag.SetUser (null, null, null);
} else {
string id = currentUser.RemoteId.HasValue ? currentUser.RemoteId.ToString () : null;
bugsnag.SetUser (id, currentUser.Email, currentUser.Name);
}
}
}
}
| bsd-3-clause | C# |
12656f3057834db1edfa206cbfbd2e7f8fc6bc25 | Add MapTile object mockup | freemanovec/Hexy | Scripts/MapGenerating/MapTile.cs | Scripts/MapGenerating/MapTile.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapTile {
public Vector2 positionGrid;
public Vector2 positionWorld;
public GameObject associatedGOBase;
public GameObject associatedGOLogic;
public GameObject associatedGOOverlay;
public float tileValue;
public MapTile(float tileValue, Vector2 posGrid, GameObject associatedGOBase, GameObject associatedGOLogic, GameObject associatedGOOverlay)
{
AssociateInitializationVars(tileValue, posGrid, associatedGOBase, associatedGOLogic, associatedGOOverlay);
}
public MapTile(float tileValue, Vector2 posGrid, GameObject associatedGOBase)
{
AssociateInitializationVars(tileValue, posGrid, associatedGOBase, null, null);
}
public MapTile(float tileValue, Vector2 posGrid)
{
AssociateInitializationVars(tileValue, posGrid, null, null, null);
}
private void AssociateInitializationVars(float tileValue, Vector2 posGrid, GameObject associatedGOBase, GameObject associatedGOLogic, GameObject associatedGOOverlay)
{
this.tileValue = tileValue;
positionGrid = posGrid;
this.associatedGOBase = associatedGOBase;
this.associatedGOLogic = associatedGOLogic;
this.associatedGOOverlay = associatedGOOverlay;
}
}
| mit | C# | |
59f27ccd5c0d8d378c97ce76f79840ce5cc737ac | Add Q226 | txchen/localleet | csharp/Q226_InvertBinaryTree.cs | csharp/Q226_InvertBinaryTree.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// Invert a binary tree.
//
// 4
// / \
// 2 7
// / \ / \
// 1 3 6 9
// to
// 4
// / \
// 7 2
// / \ / \
// 9 6 3 1
// https://leetcode.com/problems/invert-binary-tree/
namespace LocalLeet
{
public class Q226
{
public BinaryTree InvertTree(BinaryTree root)
{
if (root != null)
{
BinaryTree tmp = root.Left;
root.Left = root.Right;
root.Right = tmp;
InvertTree(root.Left);
InvertTree(root.Right);
}
return root;
}
[Fact]
public void Q226_InvertBinaryTree()
{
TestHelper.Run(input => InvertTree(input.EntireInput.ToBinaryTree2()).SerializeBinaryTree2());
}
}
}
| mit | C# | |
fc7ed3a9cd570d6829991f2e812dbe2bd4f64471 | Add TLS token binding feature | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Http.Interfaces/ITlsTokenBindingFeature.cs | src/Microsoft.AspNet.Http.Interfaces/ITlsTokenBindingFeature.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Framework.Runtime;
namespace Microsoft.AspNet.Http.Interfaces
{
/// <summary>
/// Provides information regarding TLS token binding parameters.
/// </summary>
/// <remarks>
/// TLS token bindings help mitigate the risk of impersonation by an attacker in the
/// event an authenticated client's bearer tokens are somehow exfiltrated from the
/// client's machine. See https://datatracker.ietf.org/doc/draft-popov-token-binding/
/// for more information.
/// </remarks>
[AssemblyNeutral]
public interface ITlsTokenBindingFeature
{
/// <summary>
/// Gets the 'provided' token binding identifier associated with the request.
/// </summary>
/// <returns>The token binding identifier, or null if the client did not
/// supply a 'provided' token binding or valid proof of possession of the
/// associated private key. The caller should treat this identifier as an
/// opaque blob and should not try to parse it.</returns>
byte[] GetProvidedTokenBindingId();
/// <summary>
/// Gets the 'referred' token binding identifier associated with the request.
/// </summary>
/// <returns>The token binding identifier, or null if the client did not
/// supply a 'referred' token binding or valid proof of possession of the
/// associated private key. The caller should treat this identifier as an
/// opaque blob and should not try to parse it.</returns>
byte[] GetReferredTokenBindingId();
}
}
| apache-2.0 | C# | |
00721d799c415f9caf6e78f49b291ae2a490c511 | Add missing file 1/2 | Albeoris/Memoria,Albeoris/Memoria,Albeoris/Memoria,Albeoris/Memoria | Assembly-CSharp/Memoria/Configuration/Access/Mod.cs | Assembly-CSharp/Memoria/Configuration/Access/Mod.cs | using System;
namespace Memoria
{
public sealed partial class Configuration
{
public static class Mod
{
public static String[] FolderNames => Instance._mod.FolderNames;
}
}
} | mit | C# | |
3fb5c2a35a77af6c4e232ee342cd716b0170648a | Add 'ThrowsWithMessage' | whampson/cascara,whampson/bft-spec | Cascara.Tests/Src/AssertExtension.cs | Cascara.Tests/Src/AssertExtension.cs | using System;
using Xunit;
namespace Cascara.Tests
{
public class AssertExtension : Assert
{
public static T ThrowsWithMessage<T>(Func<object> testCode, string message)
where T : Exception
{
var ex = Assert.Throws<T>(testCode);
Assert.Equal(ex.Message, message);
return ex;
}
}
}
| mit | C# | |
4a47f8c4d97753e71d58db3db7642492bd59ea41 | Create skeleton for Evaluator class with visit methods | escamilla/squirrel | squirrel/Evaluator.cs | squirrel/Evaluator.cs | using System;
using System.Collections.Generic;
using System.Reflection;
namespace squirrel
{
public class Evaluator : Visitor
{
private readonly AstNode _root;
public Evaluator(AstNode root)
{
_root = root;
}
public AstNode Evaluate()
{
return Visit(_root, new Environment());
}
protected AstNode VisitInteger(AstNode node, Environment env)
{
return node;
}
protected AstNode VisitSymbol(AstNode node, Environment env)
{
return node;
}
protected AstNode VisitSymbolicExpression(AstNode node, Environment env)
{
if (node.Children.Count < 2)
{
throw new ArgumentException("symbolic expression must contain a symbol and at least one argument");
}
var visitedChildren = new List<AstNode>();
foreach (var child in node.Children)
{
var visitedChild = Visit(child, env);
if (visitedChild.Type == NodeType.Error)
{
return visitedChild;
}
visitedChildren.Add(visitedChild);
}
var head = visitedChildren.Head();
if (head.Type != NodeType.Symbol)
{
throw new ArgumentException("first item in symbolic expression must be a symbol");
}
var tail = visitedChildren.Tail();
throw new NotImplementedException("evaluation of symbolic expressions is not implemented yet");
}
protected AstNode VisitQuotedExpression(AstNode node, Environment env)
{
return node;
}
}
}
| mit | C# | |
7cc8564123a0e6626c42d958f3960978d467c560 | Create GetAllStatsQueryHandler.cs | NinjaVault/NinjaHive,NinjaVault/NinjaHive | NinjaHive.BusinessLayer/QueryHandlers/GetAllStatsQueryHandler.cs | NinjaHive.BusinessLayer/QueryHandlers/GetAllStatsQueryHandler.cs | using System.Linq;
using NinjaHive.Contract.DTOs;
using NinjaHive.Contract.Queries;
using NinjaHive.Core;
using NinjaHive.Domain;
namespace NinjaHive.BusinessLayer.QueryHandlers
{
public class GetAllStatsQueryHandler
: IQueryHandler<GetAllStatsQuery, StatInfo[]>
{
private readonly IRepository<StatInfoEntity> statsRepository;
public GetAllStatsQueryHandler(IRepository<StatInfoEntity> statsRepository)
{
this.statsRepository = statsRepository;
}
public StatInfo[] Handle(GetAllStatsQuery query)
{
var stats =
from stat in this.statsRepository.Entities
select new StatInfo
{
Id = stat.Id,
Health = stat.Health,
Magic = stat.Magic,
Attack = stat.Attack,
Defense = stat.Defense,
Hunger = stat.Hunger,
Stamina = stat.Stamina,
Resistance = stat.Resistance
};
return stats.ToArray();
}
}
}
| apache-2.0 | C# | |
487a9ac41ba73e90af5bb80dfbc663e7ae177198 | Add Q229 | txchen/localleet | csharp/Q229_MajorityElementII.cs | csharp/Q229_MajorityElementII.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
// Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
// https://leetcode.com/problems/majority-element-ii/
namespace LocalLeet
{
public class Q229
{
public IList<int> MajorityElement(int[] nums)
{
// at most, there are 2 nums in result
int candidate1 = 0, candidate2 = 0, count1 = 0, count2 = 0;
foreach (int n in nums)
{
if (count1 == 0 || n == candidate1)
{
count1++;
candidate1 = n;
}
else if (count2 == 0 || n == candidate2)
{
count2++;
candidate2 = n;
}
else {
count1--;
count2--;
}
}
count1 = count2 = 0;
foreach (int n in nums)
{
if (n == candidate1)
{
count1++;
}
else if (n == candidate2)
{
count2++;
}
}
var result = new List<int>();
if (count1 > nums.Length / 3)
{
result.Add(candidate1);
}
if (count2 > nums.Length / 3)
{
result.Add(candidate2);
}
return result;
}
[Fact]
public void Q229_MajorityElementII()
{
TestHelper.Run(input => TestHelper.Serialize(MajorityElement(input.EntireInput.ToIntArray())));
}
}
}
| mit | C# | |
aaccc876d468106b30d985b3f22a71bde0a15d0f | add ISqlExceptionHumanizer interface abstraction for producing user friendly exceptions from sql exceptions like FK, PK etc. | volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity | src/Serenity.Net.Services/RequestHandlers/Helpers/ISqlExceptionHumanizer.cs | src/Serenity.Net.Services/RequestHandlers/Helpers/ISqlExceptionHumanizer.cs | using System;
namespace Serenity.Data
{
public interface ISqlExceptionHumanizer
{
void Humanize(Exception exception, IRow row);
}
} | mit | C# | |
c38189b1e3c3141ae257f1c4fd69f127646f7348 | Add AddWebForms service | hishamco/WebForms,hishamco/WebForms | src/My.AspNetCore.WebForms/WebFormsServiceCollectionExtensions.cs | src/My.AspNetCore.WebForms/WebFormsServiceCollectionExtensions.cs | using My.AspNetCore.WebForms.Infrastructure;
using System;
namespace Microsoft.Extensions.DependencyInjection
{
public static class WebFormsServiceCollectionExtensions
{
public static IServiceCollection AddWebForms(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.AddOptions();
services.AddSingleton<IPageFactory, PageFactory>();
return services;
}
}
}
| mit | C# | |
cbfb670fedf899009a4538730dda3d1d9424a4cd | Update for version 0.9.0 | deckar01/libsodium-net,bitbeans/libsodium-net,adamcaudill/libsodium-net,bitbeans/libsodium-net,adamcaudill/libsodium-net,BurningEnlightenment/libsodium-net,deckar01/libsodium-net,BurningEnlightenment/libsodium-net,tabrath/libsodium-core,fraga/libsodium-net,fraga/libsodium-net | libsodium-net/Properties/AssemblyInfo.cs | libsodium-net/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("libsodium-net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Adam Caudill")]
[assembly: AssemblyProduct("libsodium-net")]
[assembly: AssemblyCopyright("Copyright © Adam Caudill 2013 - 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("bac54bf6-5a39-4ab5-90f1-746a9d6b06f4")]
// 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.9.0.0")]
[assembly: AssemblyFileVersion("0.9.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("libsodium-net")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Adam Caudill")]
[assembly: AssemblyProduct("libsodium-net")]
[assembly: AssemblyCopyright("Copyright © Adam Caudill 2013 - 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("bac54bf6-5a39-4ab5-90f1-746a9d6b06f4")]
// 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.8.0.0")]
[assembly: AssemblyFileVersion("0.8.0.0")]
| mit | C# |
aa72ca7af5e1cafb209b051723c28678fddc8943 | Prepare JetBrains.Annotations samples #16 - added sample of [SourceTemplate] | synergy-software/synergy.contracts,synergy-software/synergy.contracts | Synergy.Contracts.Samples/Annotations/SourceTemplateAttributeSample.cs | Synergy.Contracts.Samples/Annotations/SourceTemplateAttributeSample.cs | using System;
using System.Collections.Generic;
using JetBrains.Annotations;
namespace Synergy.Contracts.Samples.Annotations
{
public static class SourceTemplateAttributeSample
{
[SourceTemplate]
public static void forEach<T>(this IEnumerable<T> xs)
{
foreach (T x in xs)
{
//$ $END$
}
}
[SourceTemplate]
public static void newGuid(this object obj, [Macro(Expression = "guid()", Editable = -1)] string newguid)
{
Console.WriteLine("$newguid$");
}
private static void test()
{
var enumerable = new List<string>();
//enumerable.forEach
//enumerable.newGuid
string s = null;
//s.fi
}
}
} | mit | C# | |
4183905054850bfadd79665f67c44ea4fb8e6c32 | Create GameManager.cs | Moci1/ColorBox | GameManager.cs | GameManager.cs | using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace ColorBox
{
public class GameManager
{
public List<SpriteBase> Sprites { get; private set; }
public SpriteBase Current { get; private set; }
public event EventHandler ValidTransform;
public GameManager(params SpriteBase[] sprites)
{
Sprites = new List<SpriteBase>();
Sprites.AddRange(sprites);
Current = Sprites.Last();
}
public bool HandleTransforms(SpriteBase sb)
{
for (int i = 0; i < Sprites.Count; i++) {
bool kjl = !sb.Equals(Sprites[i]);
Vector3 v1 = sb.Location - sb.Origin, v2 = Sprites[i].Location - sb.Origin;
if (!sb.Equals(Sprites[i]) &&
Pixels.IntersectPixels(sb.TransformMatrix, (int)sb.Size.X, (int)sb.Size.Y, sb.ColorArray,
Sprites[i].TransformMatrix, (int)Sprites[i].Size.X, (int)Sprites[i].Size.Y, Sprites[i].ColorArray)) {
// Colors.IntersectPixels(new Rectangle((int)v1.X, (int)v1.Y, (int)sb.Size.X, (int)sb.Size.Y), sb.ColorArray,
// new Rectangle((int)v2.X, (int)v2.Y, (int)Sprites[i].Size.X, (int)Sprites[i].Size.Y), Sprites[i].ColorArray)) {
return false;
}
}
Current = sb;
if (ValidTransform != null)
ValidTransform(this, EventArgs.Empty);
return true;
}
}
}
| mit | C# | |
ab46fe0e9ee0f384baf61865305f3686db9e0e5c | Fix test on mono | satsuper/FAKE,ArturDorochowicz/FAKE,ArturDorochowicz/FAKE,modulexcite/FAKE,tpetricek/FAKE,neoeinstein/FAKE,satsuper/FAKE,MichalDepta/FAKE,NaseUkolyCZ/FAKE,Kazark/FAKE,beeker/FAKE,RMCKirby/FAKE,daniel-chambers/FAKE,RMCKirby/FAKE,molinch/FAKE,rflechner/FAKE,ovu/FAKE,pacificIT/FAKE,pacificIT/FAKE,yonglehou/FAKE,featuresnap/FAKE,RMCKirby/FAKE,MiloszKrajewski/FAKE,Kazark/FAKE,featuresnap/FAKE,brianary/FAKE,wooga/FAKE,ctaggart/FAKE,Kazark/FAKE,MiloszKrajewski/FAKE,molinch/FAKE,pmcvtm/FAKE,JonCanning/FAKE,gareth-evans/FAKE,daniel-chambers/FAKE,yonglehou/FAKE,xavierzwirtz/FAKE,tpetricek/FAKE,mat-mcloughlin/FAKE,ilkerde/FAKE,warnergodfrey/FAKE,brianary/FAKE,yonglehou/FAKE,beeker/FAKE,ovu/FAKE,RMCKirby/FAKE,mglodack/FAKE,warnergodfrey/FAKE,wooga/FAKE,MichalDepta/FAKE,ctaggart/FAKE,satsuper/FAKE,philipcpresley/FAKE,pmcvtm/FAKE,MichalDepta/FAKE,dlsteuer/FAKE,dmorgan3405/FAKE,pmcvtm/FAKE,rflechner/FAKE,molinch/FAKE,philipcpresley/FAKE,xavierzwirtz/FAKE,MiloszKrajewski/FAKE,dmorgan3405/FAKE,brianary/FAKE,neoeinstein/FAKE,dmorgan3405/FAKE,haithemaraissia/FAKE,haithemaraissia/FAKE,neoeinstein/FAKE,philipcpresley/FAKE,tpetricek/FAKE,jayp33/FAKE,MiloszKrajewski/FAKE,darrelmiller/FAKE,NaseUkolyCZ/FAKE,featuresnap/FAKE,mfalda/FAKE,warnergodfrey/FAKE,naveensrinivasan/FAKE,naveensrinivasan/FAKE,darrelmiller/FAKE,pacificIT/FAKE,modulexcite/FAKE,hitesh97/FAKE,jayp33/FAKE,JonCanning/FAKE,dlsteuer/FAKE,ovu/FAKE,neoeinstein/FAKE,JonCanning/FAKE,ovu/FAKE,mglodack/FAKE,wooga/FAKE,dlsteuer/FAKE,leflings/FAKE,gareth-evans/FAKE,JonCanning/FAKE,ArturDorochowicz/FAKE,mfalda/FAKE,beeker/FAKE,beeker/FAKE,ctaggart/FAKE,darrelmiller/FAKE,pacificIT/FAKE,modulexcite/FAKE,leflings/FAKE,warnergodfrey/FAKE,hitesh97/FAKE,mfalda/FAKE,dlsteuer/FAKE,xavierzwirtz/FAKE,molinch/FAKE,tpetricek/FAKE,jayp33/FAKE,haithemaraissia/FAKE,mglodack/FAKE,hitesh97/FAKE,daniel-chambers/FAKE,daniel-chambers/FAKE,wooga/FAKE,gareth-evans/FAKE,mat-mcloughlin/FAKE,ilkerde/FAKE,ilkerde/FAKE,NaseUkolyCZ/FAKE,hitesh97/FAKE,gareth-evans/FAKE,ctaggart/FAKE,leflings/FAKE,featuresnap/FAKE,mfalda/FAKE,rflechner/FAKE,ArturDorochowicz/FAKE,leflings/FAKE,ilkerde/FAKE,pmcvtm/FAKE,dmorgan3405/FAKE,mat-mcloughlin/FAKE,satsuper/FAKE,rflechner/FAKE,darrelmiller/FAKE,yonglehou/FAKE,naveensrinivasan/FAKE,MichalDepta/FAKE,mat-mcloughlin/FAKE,modulexcite/FAKE,haithemaraissia/FAKE,jayp33/FAKE,Kazark/FAKE,naveensrinivasan/FAKE,mglodack/FAKE,NaseUkolyCZ/FAKE,brianary/FAKE,philipcpresley/FAKE,xavierzwirtz/FAKE | src/test/Test.FAKECore/Globbing/TestSample7/CountersRegressionSpecs.cs | src/test/Test.FAKECore/Globbing/TestSample7/CountersRegressionSpecs.cs | using System.IO;
using System.Linq;
using Fake;
using Machine.Specifications;
using Test.FAKECore.FileHandling;
namespace Test.FAKECore.Globbing.TestSample7
{
public class when_extracting_zip : BaseFunctions
{
protected static readonly string TempDir = FileSystemHelper.FullName("temptest");
protected static string[] Files;
Establish context = () =>
{
FileHelper.CleanDir(TempDir);
ZipHelper.Unzip(TempDir, "Globbing/TestSample7/Sample7.zip");
};
public static string FullPath(string pattern)
{
return TempDir + pattern;
}
}
public class when_scanning_for_all_files : when_extracting_zip
{
Because of = () => Files = FileSystem.Include(FullPath("/counters/*.*")).ToArray();
It should_find_the_first_file =
() => Files[0].ShouldEndWith(string.Format("temptest{0}counters{0}COUNTERS.mdf", Path.DirectorySeparatorChar));
It should_find_the_second_file =
() => Files[1].ShouldEndWith(string.Format("temptest{0}counters{0}COUNTERS_log.ldf", Path.DirectorySeparatorChar));
It should_find_the_file_with_absolute_path =
() => Files[0].ShouldStartWith(TempDir);
It should_match_2_files = () => Files.Length.ShouldEqual(2);
}
public class when_scanning_for_all_files_using_backslashes : when_extracting_zip
{
Because of = () => Files = FileSystem.Include(FullPath("\\counters\\*.*").Replace("/","\\")).ToArray();
It should_find_the_first_file =
() => Files[0].ShouldEndWith(string.Format("temptest{0}counters{0}COUNTERS.mdf",Path.DirectorySeparatorChar));
It should_find_the_second_file =
() => Files[1].ShouldEndWith(string.Format("temptest{0}counters{0}COUNTERS_log.ldf", Path.DirectorySeparatorChar));
It should_find_the_file_with_absolute_path =
() => Files[0].ShouldStartWith(TempDir);
It should_match_2_files = () => Files.Length.ShouldEqual(2);
}
}
| using System.IO;
using System.Linq;
using Fake;
using Machine.Specifications;
using Test.FAKECore.FileHandling;
namespace Test.FAKECore.Globbing.TestSample7
{
public class when_extracting_zip : BaseFunctions
{
protected static readonly string TempDir = FileSystemHelper.FullName("temptest");
protected static string[] Files;
Establish context = () =>
{
FileHelper.CleanDir(TempDir);
ZipHelper.Unzip(TempDir, "Globbing/TestSample7/Sample7.zip");
};
public static string FullPath(string pattern)
{
return TempDir + pattern;
}
}
public class when_scanning_for_all_files : when_extracting_zip
{
Because of = () => Files = FileSystem.Include(FullPath("/counters/*.*")).ToArray();
It should_find_the_first_file =
() => Files[0].ShouldEndWith("temptest\\counters\\COUNTERS.mdf");
It should_find_the_second_file =
() => Files[1].ShouldEndWith("temptest\\counters\\COUNTERS_log.ldf");
It should_find_the_file_with_absolute_path =
() => Files[0].ShouldStartWith(TempDir);
It should_match_2_files = () => Files.Length.ShouldEqual(2);
}
public class when_scanning_for_all_files_using_backslashes : when_extracting_zip
{
Because of = () => Files = FileSystem.Include(FullPath("\\counters\\*.*").Replace("/","\\")).ToArray();
It should_find_the_first_file =
() => Files[0].ShouldEndWith("temptest\\counters\\COUNTERS.mdf");
It should_find_the_second_file =
() => Files[1].ShouldEndWith("temptest\\counters\\COUNTERS_log.ldf");
It should_find_the_file_with_absolute_path =
() => Files[0].ShouldStartWith(TempDir);
It should_match_2_files = () => Files.Length.ShouldEqual(2);
}
}
| apache-2.0 | C# |
41e76fce5533346b59809a20c2088d96943b0210 | Create LiveQueueService.cs | siuccwd/IOER,siuccwd/IOER,siuccwd/IOER | Services/Isle.BizServices/LiveQueueService.cs | Services/Isle.BizServices/LiveQueueService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;
using System.Collections.Concurrent;
namespace Isle.BizServices
{
public class LiveQueueService
{
/// <summary>
/// Get the cache's global LiveQueueItems, or if they have expired, create a new one, insert them into the cache, and return them.
/// </summary>
/// <returns></returns>
public static ConcurrentBag<LiveQueueItem> GetCacheItems()
{
var cache = MemoryCache.Default;
var items = cache[ "LiveQueueItems" ] as ConcurrentBag<LiveQueueItem>;
if ( items == null )
{
items = new ConcurrentBag<LiveQueueItem>();
var policy = new CacheItemPolicy() { SlidingExpiration = new TimeSpan( 1, 0, 0 ) };
var cacheItem = new CacheItem( "LiveQueueItems", items );
cache.Add( cacheItem, policy );
}
return items;
}
//
/// <summary>
/// Add an item to the cache and return the random GUID assigned to it
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string AddItem( LiveQueueItem input )
{
var items = GetCacheItems();
var randomID = Guid.NewGuid().ToString();
input.MyCacheId = randomID;
items.Add( input );
return randomID;
}
//
public static string AddItem( object content, string owner, string status, LiveQueueItem.ContentPurpose purpose )
{
var item = new LiveQueueItem()
{
Content = content,
Owner = owner,
IsInProgress = false,
Status = status,
Purpose = purpose
};
return AddItem( item );
}
//
/// <summary>
/// Remove an item from the cache and return it
/// </summary>
/// <param name="targetCacheId"></param>
/// <param name="ignoreIsInProgress"></param>
/// <param name="itemWasFound"></param>
/// <param name="itemWasRemoved"></param>
public static LiveQueueItem TakeItem( string targetCacheID, bool ignoreIsInProgress, ref bool itemWasFound, ref bool itemWasRemoved )
{
//Get cache items
var items = GetCacheItems();
//Set defaults
itemWasFound = false;
itemWasRemoved = false;
//Find target item by GUID
var toRemove = items.Where( m => m.MyCacheId == targetCacheID ).FirstOrDefault();
//if found...
if ( toRemove != null )
{
itemWasFound = true;
//If the item is not in use (or if we don't care), remove it
if ( ignoreIsInProgress || !toRemove.IsInProgress )
{
var holder = new LiveQueueItem();
items.TryTake( out holder );
if ( holder != null )
{
itemWasRemoved = true;
return holder;
}
}
}
return null;
}
//
public static LiveQueueItem TakeItem( string targetCacheID, bool ignoreIsInProgress )
{
var found = false;
var removed = false;
return TakeItem( targetCacheID, ignoreIsInProgress, ref found, ref removed );
}
}
//
public class LiveQueueItem
{
public enum ContentPurpose
{
GENERAL_PURPOSE,
IMAGE_UPLOAD,
FILE_UPLOAD,
FILE_SIDELOAD_GOOGLEDRIVE,
THUMBNAIL,
RESOURCE_PUBLISH,
RESOURCE_REINDEX
};
public Type ContentType
{
get { return Content.GetType(); }
}
public string MyCacheId { get; set; }
public string Status { get; set; }
public bool IsInProgress { get; set; }
public string Owner { get; set; }
public object Content { get; set; }
public ContentPurpose Purpose { get; set; }
}
//
}
| apache-2.0 | C# | |
b6dc620dd9835fddeff924f2ca5ba025c824f156 | Create SwitchGroup.cs | xxmon/unity | SwitchGroup.cs | SwitchGroup.cs | using UnityEngine;
using System.Collections;
public class SwitchGroup : MonoBehaviour {
public GameObject[] switches;
public GameObject triggerTarget;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnValidate()
{
for(int i=0; i < switches.Length; i++)
{
if (switches [i] == null) {
Debug.LogError ("Missing switch.");
return;
}
SwitchObject obj = switches [i].GetComponent<SwitchObject>();
if (obj == null) {
Debug.LogError ("Missing switch.");
return;
}
}
}
bool IsDesiredState()
{
for(int i=0; i < switches.Length; i++)
{
if (switches [i] == null) {
Debug.LogError ("Missing switch.");
return false;
}
SwitchObject obj = switches [i].GetComponent<SwitchObject>();
if (obj == null) {
Debug.LogError ("Missing switch.");
return false;
}
if (obj.desiredState != obj.isOn) {
return false;
}
}
if(triggerTarget != null)
{
triggerTarget.SendMessage ("DoActivateTrigger");
}
Debug.Log("IsDesiredState");
return true;
}
}
| mit | C# | |
74d6e2e115d120f9f0972e0d503b05984b05f11a | Add items for database persistence | lukecahill/NutritionTracker | food_tracker/NutritionItem.cs | food_tracker/NutritionItem.cs | namespace food_tracker {
public class NutritionItem {
public string name { get; set; }
public double calories { get; set; }
public double carbohydrates { get; set; }
public double sugars { get; set; }
public double fats { get; set; }
public double saturatedFats { get; set; }
public double protein { get; set; }
public double salt { get; set; }
public double fibre { get; set; }
public NutritionItem(string name, double calories, double carbohydrates, double sugars, double fats, double satFat, double protein, double salt, double fibre) {
this.name = name;
this.calories = calories;
this.carbohydrates = carbohydrates;
this.sugars = sugars;
this.fats = fats;
this.saturatedFats = satFat;
this.protein = protein;
this.salt = salt;
this.fibre = fibre;
}
}
}
| mit | C# | |
501f6cc02f84706e48b568d8f3d415b50587f644 | split key utile to own file | jsturtevant/ace-jump,mgutekunst/ace-jump | AceJump/KeyUtility.cs | AceJump/KeyUtility.cs | namespace AceJump
{
using System.Windows.Input;
public class KeyUtility
{
private static bool IsShiftKey()
{
return Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
}
public static string GetKey(Key key)
{
var keyConverter = new KeyConverter();
// converts it to string representation. IE. Key.E = "E" and Key.OemComma = "OemComma"
string character = keyConverter.ConvertToString(key);
if (character != null && character.Length == 1)
{
if (char.IsLetter(character, 0))
{
return character;
}
if (char.IsNumber(character, 0) && !IsShiftKey())
{
return character;
}
if (char.IsNumber(character, 0) && IsShiftKey())
{
switch (key)
{
// http://msdn.microsoft.com/en-us/library/system.windows.forms.keys(v=vs.110).aspx
case Key.D1:
return "!";
case Key.D2:
return "@";
case Key.D3:
return "#";
case Key.D4:
return "$";
case Key.D5:
return "%";
case Key.D6:
return "^";
case Key.D7:
return "&";
case Key.D8:
return "*";
case Key.D9:
return "(";
case Key.D0:
return ")";
}
}
}
switch (key)
{
// http://msdn.microsoft.com/en-us/library/system.windows.forms.keys(v=vs.110).aspx
case Key.Oem4: return IsShiftKey() ? "{" : "[";
case Key.Oem6: return IsShiftKey() ? "}" : "]";
case Key.Oem5: return IsShiftKey() ? "|" : @"\";
case Key.OemMinus: return IsShiftKey() ? "_" : "-";
case Key.OemPlus: return IsShiftKey() ? "+" : "=";
case Key.OemQuestion: return IsShiftKey() ? "?" : "/";
case Key.OemSemicolon: return IsShiftKey() ? ":" : ";";
case Key.Oem7: return IsShiftKey() ? "'" : "\"";
case Key.OemPeriod: return IsShiftKey() ? ">" : ".";
case Key.OemComma: return IsShiftKey() ? "<" : ",";
}
return string.Empty;
}
}
} | mit | C# | |
afde405bb98bfa5630ca6a5f745b9f579a3d144b | Add a abstract server class. Watch out for the todos. | 0x2aff/WoWCore | Common/Network/Server.cs | Common/Network/Server.cs | /*
* WoWCore - World of Warcraft 1.12 Server
* Copyright (C) 2017 exceptionptr
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Net;
using System.Net.Sockets;
namespace WoWCore.Common.Network
{
public abstract class Server
{
private string _listenerIp;
private TcpListener _listener;
private Func<string, bool> _clientConnected;
private Func<string, bool> _clientDisconnected;
private Func<string, byte[], bool> _messageReceived;
/// <summary>
/// Initialize the TCP server.
/// </summary>
/// <param name="listenerIp"></param>
/// <param name="listenerPort"></param>
/// <param name="clientConnected"></param>
/// <param name="clientDisconnected"></param>
/// <param name="messageReceived"></param>
protected Server(string listenerIp, int listenerPort, Func<string, bool> clientConnected, Func<string, bool> clientDisconnected,
Func<string, byte[], bool> messageReceived)
{
IPAddress listenerIpAddress;
if (listenerPort < 1) throw new ArgumentOutOfRangeException(nameof(listenerPort));
_clientConnected = clientConnected;
_clientDisconnected = clientDisconnected;
_messageReceived = messageReceived ?? throw new ArgumentNullException(nameof(messageReceived));
if (string.IsNullOrEmpty(listenerIp))
{
listenerIpAddress = IPAddress.Any;
_listenerIp = listenerIpAddress.ToString();
}
else
{
listenerIpAddress = IPAddress.Parse(listenerIp);
_listenerIp = listenerIp;
}
_listener = new TcpListener(listenerIpAddress, listenerPort);
}
// TODO: Task AcceptConnections(), Task DataReceiver(), MessageReadAsync(), MessageWriteAsync etc.
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.