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 |
|---|---|---|---|---|---|---|---|---|
89d09d99db4c9331eb5a57d71ae720807dcebd74 | Remove http stream test | hey-red/Mime | test/MimeTests/GuessMime.cs | test/MimeTests/GuessMime.cs | using HeyRed.Mime;
using System.IO;
using System.Net.Http;
using Xunit;
namespace MimeTests
{
public class GuessMime
{
public GuessMime() =>
MimeGuesser.MagicFilePath = ResourceUtils.GetMagicFilePath;
[Fact]
public void GuessMimeFromFilePath()
{
string expected = "image/jpeg";
string actual = MimeGuesser.GuessMimeType(ResourceUtils.GetFileFixture);
Assert.Equal(expected, actual);
}
[Fact]
public void GuessMimeFromBuffer()
{
byte[] buffer = File.ReadAllBytes(ResourceUtils.GetFileFixture);
string expected = "image/jpeg";
string actual = MimeGuesser.GuessMimeType(buffer);
Assert.Equal(expected, actual);
}
[Fact]
public void GuessMimeFromStream()
{
using (var stream = File.OpenRead(ResourceUtils.GetFileFixture))
{
string expected = "image/jpeg";
string actual = MimeGuesser.GuessMimeType(stream);
Assert.Equal(expected, actual);
}
}
[Fact]
public void GuessMimeFromFileInfo()
{
string expected = "image/jpeg";
var fi = new FileInfo(ResourceUtils.GetFileFixture);
string actual = fi.GuessMimeType();
Assert.Equal(expected, actual);
}
}
}
| using HeyRed.Mime;
using System.IO;
using System.Net.Http;
using Xunit;
namespace MimeTests
{
public class GuessMime
{
public GuessMime() =>
MimeGuesser.MagicFilePath = ResourceUtils.GetMagicFilePath;
[Fact]
public void GuessMimeFromFilePath()
{
string expected = "image/jpeg";
string actual = MimeGuesser.GuessMimeType(ResourceUtils.GetFileFixture);
Assert.Equal(expected, actual);
}
[Fact]
public void GuessMimeFromBuffer()
{
byte[] buffer = File.ReadAllBytes(ResourceUtils.GetFileFixture);
string expected = "image/jpeg";
string actual = MimeGuesser.GuessMimeType(buffer);
Assert.Equal(expected, actual);
}
[Fact]
public void GuessMimeFromStream()
{
using (var stream = File.OpenRead(ResourceUtils.GetFileFixture))
{
string expected = "image/jpeg";
string actual = MimeGuesser.GuessMimeType(stream);
Assert.Equal(expected, actual);
}
}
[Fact]
public void GuessMimeFromFileInfo()
{
string expected = "image/jpeg";
var fi = new FileInfo(ResourceUtils.GetFileFixture);
string actual = fi.GuessMimeType();
Assert.Equal(expected, actual);
}
[Fact]
public async void GuessMimeFromHttpStream()
{
using (var client = new HttpClient())
{
var uri = "https://www.google.ru/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
using (var stream = await client.GetStreamAsync(uri))
{
string expected = "image/png";
string actual = MimeGuesser.GuessMimeType(stream);
Assert.Equal(expected, actual);
}
}
}
}
}
| mit | C# |
a026d93b41e758203609e4f508322f8d39e3c2b5 | Update GameManager.cs | Magneseus/3x-eh | Assets/scripts/GameManager.cs | Assets/scripts/GameManager.cs |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
// Maybe we want this to be a reference to a Map?
public List<City> ListOfCities;
public int DurationOfTurn = 7;
private int CurrentTurnNumber;
private int DaysTranspired;
// Initialization
// Use this for initialization
void Start () {
CurrentTurnNumber = 0;
DaysTranspired = 0;
}
void EndTurnUpdate()
{
// Here we will update everything (basically just updating the cities)
foreach (City c in ListOfCities)
{
c.TurnUpdate(DurationOfTurn);
}
CurrentTurnNumber += 1;
DaysTranspired += DurationOfTurn;
Debug.Log("Turn ended, " + DurationOfTurn + " days passed.");
}
//Updated per frame, use for UI.
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
EndTurnUpdate();
}
}
//////////// Single Instance Assertion Stuff
private static bool _isInstantiated = false;
private void Awake()
{
// IF THIS FAILS, we've instantiated another GameManager somewhere!!
Debug.Assert(!_isInstantiated);
_isInstantiated = true;
}
private void OnDestroy()
{
_isInstantiated = false;
}
///// End of Single Instance Assertion Stuff
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| mit | C# |
7089d545bbf7c2dcd3aa949c1762de28883d28d4 | add missing copyright message | furesoft/roslyn,bbarry/roslyn,jcouv/roslyn,ericfe-ms/roslyn,jeremymeng/roslyn,pdelvo/roslyn,swaroop-sridhar/roslyn,mirhagk/roslyn,reaction1989/roslyn,dpoeschl/roslyn,bartdesmet/roslyn,akrisiun/roslyn,doconnell565/roslyn,swaroop-sridhar/roslyn,supriyantomaftuh/roslyn,natidea/roslyn,bkoelman/roslyn,stjeong/roslyn,michalhosala/roslyn,aanshibudhiraja/Roslyn,sharadagrawal/Roslyn,devharis/roslyn,jbhensley/roslyn,stjeong/roslyn,KamalRathnayake/roslyn,thomaslevesque/roslyn,garryforreg/roslyn,jgglg/roslyn,khyperia/roslyn,jrharmon/roslyn,KirillOsenkov/roslyn,CaptainHayashi/roslyn,supriyantomaftuh/roslyn,orthoxerox/roslyn,nemec/roslyn,srivatsn/roslyn,tannergooding/roslyn,sharadagrawal/Roslyn,oberxon/roslyn,amcasey/roslyn,mattwar/roslyn,jeffanders/roslyn,paladique/roslyn,krishnarajbb/roslyn,tmeschter/roslyn,FICTURE7/roslyn,khellang/roslyn,akrisiun/roslyn,mirhagk/roslyn,jmarolf/roslyn,zooba/roslyn,Maxwe11/roslyn,AArnott/roslyn,MattWindsor91/roslyn,magicbing/roslyn,Pvlerick/roslyn,sharwell/roslyn,reaction1989/roslyn,mseamari/Stuff,jroggeman/roslyn,tang7526/roslyn,EricArndt/roslyn,MihaMarkic/roslyn-prank,MihaMarkic/roslyn-prank,panopticoncentral/roslyn,managed-commons/roslyn,v-codeel/roslyn,cston/roslyn,brettfo/roslyn,managed-commons/roslyn,tvand7093/roslyn,DinoV/roslyn,yeaicc/roslyn,mattscheffer/roslyn,akoeplinger/roslyn,orthoxerox/roslyn,jrharmon/roslyn,CyrusNajmabadi/roslyn,wschae/roslyn,jasonmalinowski/roslyn,mattscheffer/roslyn,Inverness/roslyn,jgglg/roslyn,MatthieuMEZIL/roslyn,lisong521/roslyn,VShangxiao/roslyn,shyamnamboodiripad/roslyn,jaredpar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jeremymeng/roslyn,paladique/roslyn,akrisiun/roslyn,moozzyk/roslyn,VPashkov/roslyn,natidea/roslyn,ManishJayaswal/roslyn,brettfo/roslyn,tsdl2013/roslyn,zmaruo/roslyn,dotnet/roslyn,YOTOV-LIMITED/roslyn,wschae/roslyn,KevinRansom/roslyn,rgani/roslyn,zmaruo/roslyn,srivatsn/roslyn,cybernet14/roslyn,enginekit/roslyn,AlekseyTs/roslyn,akoeplinger/roslyn,TyOverby/roslyn,zmaruo/roslyn,jaredpar/roslyn,OmarTawfik/roslyn,KevinRansom/roslyn,MattWindsor91/roslyn,natidea/roslyn,rchande/roslyn,huoxudong125/roslyn,ericfe-ms/roslyn,Giten2004/roslyn,VitalyTVA/roslyn,REALTOBIZ/roslyn,RipCurrent/roslyn,ilyes14/roslyn,HellBrick/roslyn,lorcanmooney/roslyn,KiloBravoLima/roslyn,aanshibudhiraja/Roslyn,genlu/roslyn,kelltrick/roslyn,ilyes14/roslyn,Hosch250/roslyn,tannergooding/roslyn,AnthonyDGreen/roslyn,kelltrick/roslyn,mseamari/Stuff,evilc0des/roslyn,v-codeel/roslyn,dsplaisted/roslyn,Shiney/roslyn,drognanar/roslyn,jkotas/roslyn,chenxizhang/roslyn,3F/roslyn,REALTOBIZ/roslyn,jcouv/roslyn,budcribar/roslyn,AnthonyDGreen/roslyn,heejaechang/roslyn,ManishJayaswal/roslyn,jamesqo/roslyn,gafter/roslyn,zooba/roslyn,jramsay/roslyn,droyad/roslyn,amcasey/roslyn,krishnarajbb/roslyn,AmadeusW/roslyn,jonatassaraiva/roslyn,robinsedlaczek/roslyn,a-ctor/roslyn,managed-commons/roslyn,OmniSharp/roslyn,AlexisArce/roslyn,davkean/roslyn,khyperia/roslyn,SeriaWei/roslyn,physhi/roslyn,doconnell565/roslyn,cston/roslyn,natgla/roslyn,aelij/roslyn,marksantos/roslyn,KamalRathnayake/roslyn,balajikris/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,cston/roslyn,grianggrai/roslyn,sharadagrawal/TestProject2,BugraC/roslyn,agocke/roslyn,KashishArora/Roslyn,SeriaWei/roslyn,MattWindsor91/roslyn,chenxizhang/roslyn,srivatsn/roslyn,eriawan/roslyn,oberxon/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,agocke/roslyn,ilyes14/roslyn,genlu/roslyn,jbhensley/roslyn,jramsay/roslyn,HellBrick/roslyn,stebet/roslyn,Pvlerick/roslyn,v-codeel/roslyn,poizan42/roslyn,DustinCampbell/roslyn,DinoV/roslyn,grianggrai/roslyn,AArnott/roslyn,vslsnap/roslyn,jmarolf/roslyn,robinsedlaczek/roslyn,enginekit/roslyn,enginekit/roslyn,jonatassaraiva/roslyn,3F/roslyn,garryforreg/roslyn,tmat/roslyn,a-ctor/roslyn,DustinCampbell/roslyn,droyad/roslyn,HellBrick/roslyn,MavenRain/roslyn,wvdd007/roslyn,KashishArora/Roslyn,budcribar/roslyn,russpowers/roslyn,dotnet/roslyn,TyOverby/roslyn,genlu/roslyn,tvand7093/roslyn,Giten2004/roslyn,VPashkov/roslyn,jonatassaraiva/roslyn,taylorjonl/roslyn,KirillOsenkov/roslyn,khellang/roslyn,kelltrick/roslyn,jrharmon/roslyn,leppie/roslyn,Maxwe11/roslyn,nagyistoce/roslyn,kuhlenh/roslyn,EricArndt/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,bkoelman/roslyn,yjfxfjch/roslyn,3F/roslyn,stephentoub/roslyn,huoxudong125/roslyn,davkean/roslyn,khyperia/roslyn,jamesqo/roslyn,mavasani/roslyn,AlexisArce/roslyn,xoofx/roslyn,weltkante/roslyn,kienct89/roslyn,sharadagrawal/TestProject2,antonssonj/roslyn,jkotas/roslyn,mmitche/roslyn,moozzyk/roslyn,Giftednewt/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,OmniSharp/roslyn,yjfxfjch/roslyn,mattwar/roslyn,vcsjones/roslyn,JakeGinnivan/roslyn,Pvlerick/roslyn,sharadagrawal/TestProject2,AlexisArce/roslyn,tmeschter/roslyn,leppie/roslyn,ErikSchierboom/roslyn,jeremymeng/roslyn,supriyantomaftuh/roslyn,ValentinRueda/roslyn,devharis/roslyn,Shiney/roslyn,FICTURE7/roslyn,jasonmalinowski/roslyn,aanshibudhiraja/Roslyn,jamesqo/roslyn,Giftednewt/roslyn,DanielRosenwasser/roslyn,jeffanders/roslyn,magicbing/roslyn,dpoeschl/roslyn,grianggrai/roslyn,dpen2000/roslyn,physhi/roslyn,moozzyk/roslyn,Hosch250/roslyn,drognanar/roslyn,jmarolf/roslyn,orthoxerox/roslyn,amcasey/roslyn,tmat/roslyn,evilc0des/roslyn,EricArndt/roslyn,DanielRosenwasser/roslyn,bartdesmet/roslyn,natgla/roslyn,evilc0des/roslyn,antonssonj/roslyn,rgani/roslyn,kienct89/roslyn,REALTOBIZ/roslyn,nguerrera/roslyn,jaredpar/roslyn,wschae/roslyn,stephentoub/roslyn,1234-/roslyn,basoundr/roslyn,mattscheffer/roslyn,DanielRosenwasser/roslyn,AmadeusW/roslyn,YOTOV-LIMITED/roslyn,MavenRain/roslyn,tvand7093/roslyn,JakeGinnivan/roslyn,robinsedlaczek/roslyn,ericfe-ms/roslyn,taylorjonl/roslyn,wvdd007/roslyn,dovzhikova/roslyn,thomaslevesque/roslyn,vslsnap/roslyn,VShangxiao/roslyn,abock/roslyn,brettfo/roslyn,ManishJayaswal/roslyn,antonssonj/roslyn,devharis/roslyn,leppie/roslyn,mseamari/Stuff,dpen2000/roslyn,a-ctor/roslyn,oocx/roslyn,ljw1004/roslyn,ljw1004/roslyn,jhendrixMSFT/roslyn,cybernet14/roslyn,KiloBravoLima/roslyn,furesoft/roslyn,dsplaisted/roslyn,wvdd007/roslyn,sharwell/roslyn,MichalStrehovsky/roslyn,tsdl2013/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,jhendrixMSFT/roslyn,VShangxiao/roslyn,FICTURE7/roslyn,AArnott/roslyn,stebet/roslyn,Maxwe11/roslyn,CaptainHayashi/roslyn,danielcweber/roslyn,tang7526/roslyn,natgla/roslyn,GuilhermeSa/roslyn,AlekseyTs/roslyn,jroggeman/roslyn,dsplaisted/roslyn,ahmedshuhel/roslyn,sharadagrawal/Roslyn,xoofx/roslyn,mgoertz-msft/roslyn,jgglg/roslyn,marksantos/roslyn,yeaicc/roslyn,furesoft/roslyn,lorcanmooney/roslyn,aelij/roslyn,khellang/roslyn,KevinH-MS/roslyn,kuhlenh/roslyn,JakeGinnivan/roslyn,michalhosala/roslyn,vcsjones/roslyn,CyrusNajmabadi/roslyn,akoeplinger/roslyn,hanu412/roslyn,droyad/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,jbhensley/roslyn,ahmedshuhel/roslyn,jroggeman/roslyn,ValentinRueda/roslyn,nemec/roslyn,stebet/roslyn,gafter/roslyn,KashishArora/Roslyn,marksantos/roslyn,BugraC/roslyn,KevinH-MS/roslyn,bbarry/roslyn,diryboy/roslyn,jramsay/roslyn,KamalRathnayake/roslyn,tang7526/roslyn,poizan42/roslyn,oberxon/roslyn,paulvanbrenk/roslyn,basoundr/roslyn,paulvanbrenk/roslyn,stjeong/roslyn,magicbing/roslyn,ahmedshuhel/roslyn,krishnarajbb/roslyn,bartdesmet/roslyn,MattWindsor91/roslyn,AmadeusW/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,tmeschter/roslyn,BugraC/roslyn,VPashkov/roslyn,OmarTawfik/roslyn,VSadov/roslyn,antiufo/roslyn,physhi/roslyn,mavasani/roslyn,jeffanders/roslyn,poizan42/roslyn,rchande/roslyn,nagyistoce/roslyn,dpen2000/roslyn,Giftednewt/roslyn,shyamnamboodiripad/roslyn,oocx/roslyn,dovzhikova/roslyn,mmitche/roslyn,huoxudong125/roslyn,russpowers/roslyn,VitalyTVA/roslyn,AnthonyDGreen/roslyn,zooba/roslyn,yeaicc/roslyn,doconnell565/roslyn,thomaslevesque/roslyn,KiloBravoLima/roslyn,jhendrixMSFT/roslyn,heejaechang/roslyn,eriawan/roslyn,mirhagk/roslyn,vslsnap/roslyn,kuhlenh/roslyn,MatthieuMEZIL/roslyn,RipCurrent/roslyn,OmniSharp/roslyn,GuilhermeSa/roslyn,dpoeschl/roslyn,taylorjonl/roslyn,paulvanbrenk/roslyn,Hosch250/roslyn,Shiney/roslyn,pdelvo/roslyn,Giten2004/roslyn,tmat/roslyn,chenxizhang/roslyn,Inverness/roslyn,KevinH-MS/roslyn,vcsjones/roslyn,MatthieuMEZIL/roslyn,ValentinRueda/roslyn,mavasani/roslyn,RipCurrent/roslyn,weltkante/roslyn,antiufo/roslyn,OmarTawfik/roslyn,budcribar/roslyn,garryforreg/roslyn,panopticoncentral/roslyn,kienct89/roslyn,KevinRansom/roslyn,nemec/roslyn,abock/roslyn,jcouv/roslyn,rchande/roslyn,AlekseyTs/roslyn,VSadov/roslyn,nagyistoce/roslyn,cybernet14/roslyn,lisong521/roslyn,MavenRain/roslyn,xasx/roslyn,1234-/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,SeriaWei/roslyn,yjfxfjch/roslyn,balajikris/roslyn,danielcweber/roslyn,diryboy/roslyn,lisong521/roslyn,VitalyTVA/roslyn,pjmagee/roslyn,antiufo/roslyn,mmitche/roslyn,xoofx/roslyn,pjmagee/roslyn,pjmagee/roslyn,abock/roslyn,1234-/roslyn,ManishJayaswal/roslyn,agocke/roslyn,pdelvo/roslyn,dovzhikova/roslyn,MihaMarkic/roslyn-prank,CyrusNajmabadi/roslyn,Inverness/roslyn,dotnet/roslyn,weltkante/roslyn,basoundr/roslyn,hanu412/roslyn,TyOverby/roslyn,oocx/roslyn,tsdl2013/roslyn,davkean/roslyn,ljw1004/roslyn,jasonmalinowski/roslyn,jkotas/roslyn,balajikris/roslyn,drognanar/roslyn,swaroop-sridhar/roslyn,mattwar/roslyn,bbarry/roslyn,ErikSchierboom/roslyn,DinoV/roslyn,YOTOV-LIMITED/roslyn,GuilhermeSa/roslyn,reaction1989/roslyn,gafter/roslyn,hanu412/roslyn,VSadov/roslyn,DustinCampbell/roslyn,paladique/roslyn,xasx/roslyn,rgani/roslyn,michalhosala/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,danielcweber/roslyn,nguerrera/roslyn,lorcanmooney/roslyn,aelij/roslyn,sharwell/roslyn,MichalStrehovsky/roslyn,xasx/roslyn,stephentoub/roslyn,russpowers/roslyn | src/EditorFeatures/Test/CodeAnalysisResources.cs | src/EditorFeatures/Test/CodeAnalysisResources.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Resources;
namespace Microsoft.CodeAnalysis
{
// This class exists as a way to load resources from the Microsoft.CodeAnalysis.CodeAnalysisResources class from
// the Microsoft.CodeAnalysis assembly. Microsoft.CodeAnalysis.CodeAnalysisResources is internal but we can't add
// InternalsVisibleTo(this-assembly) because there are numerous shared (linked) files common to both
// Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.Workspaces and that gives us major issues with duplicate
// internal types that suddenly become visible (e.g., SpecializedCollections) and that leads down a rabbit hole
// of requiring assembly aliasing that would make many tests in this project unreadable. The descision was made to
// manually load the few resources we need from the CodeAnalysis assembly at the cost of Find All References and
// Rename not working as expected.
internal static class CodeAnalysisResources
{
public static string InMemoryAssembly => GetString("InMemoryAssembly");
private static ResourceManager _codeAnalysisResourceManager;
private static string GetString(string resourceName)
{
if (_codeAnalysisResourceManager == null)
{
_codeAnalysisResourceManager = new ResourceManager("Microsoft.CodeAnalysis.CodeAnalysisResources", typeof(Compilation).Assembly);
}
return _codeAnalysisResourceManager.GetString(resourceName);
}
}
}
| using System.Resources;
namespace Microsoft.CodeAnalysis
{
// This class exists as a way to load resources from the Microsoft.CodeAnalysis.CodeAnalysisResources class from
// the Microsoft.CodeAnalysis assembly. Microsoft.CodeAnalysis.CodeAnalysisResources is internal but we can't add
// InternalsVisibleTo(this-assembly) because there are numerous shared (linked) files common to both
// Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.Workspaces and that gives us major issues with duplicate
// internal types that suddenly become visible (e.g., SpecializedCollections) and that leads down a rabbit hole
// of requiring assembly aliasing that would make many tests in this project unreadable. The descision was made to
// manually load the few resources we need from the CodeAnalysis assembly at the cost of Find All References and
// Rename not working as expected.
internal static class CodeAnalysisResources
{
public static string InMemoryAssembly => GetString("InMemoryAssembly");
private static ResourceManager _codeAnalysisResourceManager;
private static string GetString(string resourceName)
{
if (_codeAnalysisResourceManager == null)
{
_codeAnalysisResourceManager = new ResourceManager("Microsoft.CodeAnalysis.CodeAnalysisResources", typeof(Compilation).Assembly);
}
return _codeAnalysisResourceManager.GetString(resourceName);
}
}
}
| apache-2.0 | C# |
cc61c53579ea9714abfc881565a89c7c9882dc9b | Refactor virtual judge user table schema | JoyOI/OnlineJudge,JoyOI/OnlineJudge,JoyOI/OnlineJudge,JoyOI/OnlineJudge | src/JoyOI.OnlineJudge.Models/VirtualJudgeUser.cs | src/JoyOI.OnlineJudge.Models/VirtualJudgeUser.cs | using System;
using System.ComponentModel.DataAnnotations;
namespace JoyOI.OnlineJudge.Models
{
public class VirtualJudgeUser
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the username.
/// </summary>
/// <value>The username.</value>
[MaxLength(32)]
public string Username { get; set; }
/// <summary>
/// Gets or sets the password.
/// </summary>
/// <value>The password.</value>
[MaxLength(64)]
public string Password { get; set; }
/// <summary>
/// Gets or sets the locker id.
/// </summary>
/// <value>The locker id.</value>
public Guid? LockerId { get; set; }
/// <summary>
/// Gets or sets the source.
/// </summary>
/// <value>The source of this user.</value>
public ProblemSource Source { get; set; }
}
}
| using System;
using System.ComponentModel.DataAnnotations;
namespace JoyOI.OnlineJudge.Models
{
public class VirtualJudgeUser
{
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
public Guid Id { get; set; }
/// <summary>
/// Gets or sets the username.
/// </summary>
/// <value>The username.</value>
[MaxLength(32)]
public string Username { get; set; }
/// <summary>
/// Gets or sets the password.
/// </summary>
/// <value>The password.</value>
[MaxLength(64)]
public string Password { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:JoyOI.OnlineJudge.Models.VirtualJudgeUser"/> is in use.
/// </summary>
/// <value><c>true</c> if is in use; otherwise, <c>false</c>.</value>
public bool IsInUse { get; set; }
/// <summary>
/// Gets or sets the source.
/// </summary>
/// <value>The source of this user.</value>
public ProblemSource Source { get; set; }
}
}
| mit | C# |
30cff58da2c68a7e06525a69df5da95a1588ca49 | Remove duplicate memory barrier | AdaptiveConsulting/Aeron.NET,AdaptiveConsulting/Aeron.NET | src/Adaptive.Aeron/LogBuffer/HeaderWriter.cs | src/Adaptive.Aeron/LogBuffer/HeaderWriter.cs | using System.Threading;
using Adaptive.Aeron.Protocol;
using Adaptive.Agrona;
using Adaptive.Agrona.Concurrent;
namespace Adaptive.Aeron.LogBuffer
{
/// <summary>
/// Utility for applying a header to a message in a term buffer.
///
/// This class is designed to be thread safe to be used across multiple producers and makes the header
/// visible in the correct order for consumers.
/// </summary>
public class HeaderWriter
{
private readonly long _versionFlagsType;
private readonly long _sessionId;
private readonly long _streamId;
public HeaderWriter()
{
}
public HeaderWriter(IDirectBuffer defaultHeader)
{
_versionFlagsType = (long)defaultHeader.GetInt(HeaderFlyweight.VERSION_FIELD_OFFSET) << 32;
_sessionId = (long)defaultHeader.GetInt(DataHeaderFlyweight.SESSION_ID_FIELD_OFFSET) << 32;
_streamId = defaultHeader.GetInt(DataHeaderFlyweight.STREAM_ID_FIELD_OFFSET) & 0xFFFFFFFFL;
}
/// <summary>
/// Write a header to the term buffer in <seealso cref="ByteOrder.LittleEndian"/> format using the minimum instructions.
/// </summary>
/// <param name="termBuffer"> to be written to. </param>
/// <param name="offset"> at which the header should be written. </param>
/// <param name="length"> of the fragment including the header. </param>
/// <param name="termId"> of the current term buffer. </param>
public virtual void Write(IAtomicBuffer termBuffer, int offset, int length, int termId)
{
var lengthVersionFlagsType = _versionFlagsType | (-length & 0xFFFFFFFFL);
var termOffsetSessionId = _sessionId | (uint)offset;
var streamAndTermIds = _streamId | ((long)termId << 32);
termBuffer.PutLongOrdered(offset + HeaderFlyweight.FRAME_LENGTH_FIELD_OFFSET, lengthVersionFlagsType);
// PutLongOrdered use Volatile.Write that already generates an implicit memory barrier
// no need for Thread.MemoryBarrier();
termBuffer.PutLong(offset + DataHeaderFlyweight.TERM_OFFSET_FIELD_OFFSET, termOffsetSessionId);
termBuffer.PutLong(offset + DataHeaderFlyweight.STREAM_ID_FIELD_OFFSET, streamAndTermIds);
}
}
} | using System.Threading;
using Adaptive.Aeron.Protocol;
using Adaptive.Agrona;
using Adaptive.Agrona.Concurrent;
namespace Adaptive.Aeron.LogBuffer
{
/// <summary>
/// Utility for applying a header to a message in a term buffer.
///
/// This class is designed to be thread safe to be used across multiple producers and makes the header
/// visible in the correct order for consumers.
/// </summary>
public class HeaderWriter
{
private readonly long _versionFlagsType;
private readonly long _sessionId;
private readonly long _streamId;
public HeaderWriter()
{
}
public HeaderWriter(IDirectBuffer defaultHeader)
{
_versionFlagsType = (long)defaultHeader.GetInt(HeaderFlyweight.VERSION_FIELD_OFFSET) << 32;
_sessionId = (long)defaultHeader.GetInt(DataHeaderFlyweight.SESSION_ID_FIELD_OFFSET) << 32;
_streamId = defaultHeader.GetInt(DataHeaderFlyweight.STREAM_ID_FIELD_OFFSET) & 0xFFFFFFFFL;
}
/// <summary>
/// Write a header to the term buffer in <seealso cref="ByteOrder.LittleEndian"/> format using the minimum instructions.
/// </summary>
/// <param name="termBuffer"> to be written to. </param>
/// <param name="offset"> at which the header should be written. </param>
/// <param name="length"> of the fragment including the header. </param>
/// <param name="termId"> of the current term buffer. </param>
public virtual void Write(IAtomicBuffer termBuffer, int offset, int length, int termId)
{
var lengthVersionFlagsType = _versionFlagsType | (-length & 0xFFFFFFFFL);
var termOffsetSessionId = _sessionId | (uint)offset;
var streamAndTermIds = _streamId | ((long)termId << 32);
//TODO why not just putlongvolatile?
termBuffer.PutLongOrdered(offset + HeaderFlyweight.FRAME_LENGTH_FIELD_OFFSET, lengthVersionFlagsType);
Thread.MemoryBarrier();
termBuffer.PutLong(offset + DataHeaderFlyweight.TERM_OFFSET_FIELD_OFFSET, termOffsetSessionId);
termBuffer.PutLong(offset + DataHeaderFlyweight.STREAM_ID_FIELD_OFFSET, streamAndTermIds);
}
}
} | apache-2.0 | C# |
f99c3cdbfaaf3eaa73e59f54bcd67d204739218b | update running program code | RedSpiderMkV/LANMachines | src/LANMachines/LanMachinesRunner/Program.cs | src/LANMachines/LanMachinesRunner/Program.cs | using System;
using System.Collections.Generic;
using LanDiscovery;
namespace LanMachines
{
internal class Program
{
internal static void Main(string[] args)
{
LanDiscoveryManager lanDiscovery = new LanDiscoveryManager();
List<string> lanMachines = lanDiscovery.GetNetworkMachines();
printStringList(lanMachines);
Console.WriteLine("LAN ping complete");
Console.ReadKey();
} // end method
private static void printStringList(List<string> stringList)
{
foreach (string s in stringList)
{
Console.WriteLine(s);
} // end foreach
} // end method
} // end class
} // end namespace
| using System;
using System.Collections.Generic;
using LanDiscovery;
namespace LanMachines
{
class Program
{
internal static void Main(string[] args)
{
LanDiscoveryManager lanDiscovery = new LanDiscoveryManager();
List<string> lanMachines = lanDiscovery.GetNetworkMachines();
foreach (string lanIp in lanMachines)
{
Console.WriteLine(lanIp);
}
Console.WriteLine("LAN ping complete");
Console.ReadKey();
} // end method
} // end class
} // end namespace
| mit | C# |
cf079690e528cadd4387402ca2a050d388604796 | Use LargeTextureStore for online retrievals | UselessToucan/osu,EVAST9919/osu,DrabWeb/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,naoey/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,naoey/osu,naoey/osu,peppy/osu,ZLima12/osu,johnneijzen/osu,EVAST9919/osu,UselessToucan/osu,ZLima12/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu | osu.Game/Beatmaps/Drawables/BeatmapSetCover.cs | osu.Game/Beatmaps/Drawables/BeatmapSetCover.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Beatmaps.Drawables
{
public class BeatmapSetCover : Sprite
{
private readonly BeatmapSetInfo set;
private readonly BeatmapSetCoverType type;
public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover)
{
if (set == null)
throw new ArgumentNullException(nameof(set));
this.set = set;
this.type = type;
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
string resource = null;
switch (type)
{
case BeatmapSetCoverType.Cover:
resource = set.OnlineInfo.Covers.Cover;
break;
case BeatmapSetCoverType.Card:
resource = set.OnlineInfo.Covers.Card;
break;
case BeatmapSetCoverType.List:
resource = set.OnlineInfo.Covers.List;
break;
}
if (resource != null)
Texture = textures.Get(resource);
}
}
public enum BeatmapSetCoverType
{
Cover,
Card,
List,
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Beatmaps.Drawables
{
public class BeatmapSetCover : Sprite
{
private readonly BeatmapSetInfo set;
private readonly BeatmapSetCoverType type;
public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover)
{
if (set == null)
throw new ArgumentNullException(nameof(set));
this.set = set;
this.type = type;
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
string resource = null;
switch (type)
{
case BeatmapSetCoverType.Cover:
resource = set.OnlineInfo.Covers.Cover;
break;
case BeatmapSetCoverType.Card:
resource = set.OnlineInfo.Covers.Card;
break;
case BeatmapSetCoverType.List:
resource = set.OnlineInfo.Covers.List;
break;
}
if (resource != null)
Texture = textures.Get(resource);
}
}
public enum BeatmapSetCoverType
{
Cover,
Card,
List,
}
}
| mit | C# |
37053608f1544f0a6a294b6695cbac323730931c | Use registered types for Out of Band handlers in packet handling type finder | ethanmoffat/EndlessClient | EOLib/Net/Handlers/PacketHandlingTypeFinder.cs | EOLib/Net/Handlers/PacketHandlingTypeFinder.cs | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
using System.Linq;
namespace EOLib.Net.Handlers
{
public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder
{
private readonly List<FamilyActionPair> _inBandPackets;
private readonly List<FamilyActionPair> _outOfBandPackets;
public PacketHandlingTypeFinder(IEnumerable<IPacketHandler> outOfBandHandlers)
{
_inBandPackets = new List<FamilyActionPair>
{
new FamilyActionPair(PacketFamily.Init, PacketAction.Init),
new FamilyActionPair(PacketFamily.Account, PacketAction.Reply),
new FamilyActionPair(PacketFamily.Character, PacketAction.Reply),
new FamilyActionPair(PacketFamily.Login, PacketAction.Reply)
};
_outOfBandPackets = outOfBandHandlers.Select(x => new FamilyActionPair(x.Family, x.Action)).ToList();
}
public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action)
{
var fap = new FamilyActionPair(family, action);
if (_inBandPackets.Contains(fap))
return PacketHandlingType.InBand;
if (_outOfBandPackets.Contains(fap))
return PacketHandlingType.OutOfBand;
return PacketHandlingType.NotHandled;
}
}
} | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
namespace EOLib.Net.Handlers
{
public class PacketHandlingTypeFinder : IPacketHandlingTypeFinder
{
private readonly List<FamilyActionPair> _inBandPackets;
private readonly List<FamilyActionPair> _outOfBandPackets;
public PacketHandlingTypeFinder()
{
_inBandPackets = new List<FamilyActionPair>
{
new FamilyActionPair(PacketFamily.Init, PacketAction.Init),
new FamilyActionPair(PacketFamily.Account, PacketAction.Reply),
new FamilyActionPair(PacketFamily.Character, PacketAction.Reply),
new FamilyActionPair(PacketFamily.Login, PacketAction.Reply)
};
_outOfBandPackets = new List<FamilyActionPair>
{
new FamilyActionPair(PacketFamily.Connection, PacketAction.Player)
};
}
public PacketHandlingType FindHandlingType(PacketFamily family, PacketAction action)
{
var fap = new FamilyActionPair(family, action);
if (_inBandPackets.Contains(fap))
return PacketHandlingType.InBand;
if (_outOfBandPackets.Contains(fap))
return PacketHandlingType.OutOfBand;
return PacketHandlingType.NotHandled;
}
}
} | mit | C# |
1ce50db88ec5bf59f92bf92696d43ba645863542 | test fix | stanac/LiteApi,stanac/LiteApi,stanac/LiteApi | LiteApi/LiteApi.Tests/LiteApiMiddleareTests.cs | LiteApi/LiteApi.Tests/LiteApiMiddleareTests.cs | using System;
using System.Threading.Tasks;
using Xunit;
namespace LiteApi.Tests
{
public class LiteApiMiddleareTests
{
[Fact]
public async Task LiteApiMiddleareTests_Registered_CanBeInvoked()
{
var servicesMock = new Moq.Mock<IServiceProvider>();
servicesMock.Setup(x => x.GetService(typeof(IServiceProvider))).Returns(servicesMock.Object);
var middleware = new LiteApiMiddleware(null, LiteApiOptions.Default, servicesMock.Object);
var httpCtx = new Fakes.FakeHttpContext();
httpCtx.Request.Method = "GET";
httpCtx.Request.Path = "/";
await middleware.Invoke(httpCtx);
// expect exception on next registration
TestExtensions.AssertExpectedException<Exception>(() =>
new LiteApiMiddleware(null, LiteApiOptions.Default, null),
"Middleware can be registered twice");
}
}
}
| using System;
using System.Threading.Tasks;
using Xunit;
namespace LiteApi.Tests
{
public class LiteApiMiddleareTests
{
[Fact]
public async Task LiteApiMiddleareTests_Registered_CanBeInvoked()
{
var middleware = new LiteApiMiddleware(null, LiteApiOptions.Default, (new Moq.Mock<IServiceProvider>()).Object);
var httpCtx = new Fakes.FakeHttpContext();
httpCtx.Request.Method = "GET";
httpCtx.Request.Path = "/";
await middleware.Invoke(httpCtx);
// expect exception on next registration
TestExtensions.AssertExpectedException<Exception>(() =>
new LiteApiMiddleware(null, LiteApiOptions.Default, null),
"Middleware can be registered twice");
}
}
}
| mit | C# |
0b3a6a754bb9ac140d8c41af416fe14c16976345 | Fix bug where ther are no recipieints in To/Cc line | mrpeterson27/mail2bug,vitru/mail2bug,Spurrya/mail2bug | Mail2Bug/Email/EWS/RecipientsMailboxManager.cs | Mail2Bug/Email/EWS/RecipientsMailboxManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Mail2Bug.Email.EWS
{
/// <summary>
/// This imiplementation of IMailboxManager monitors the inbox of an exchange user, and retrieves
/// only messages that have a specific alias in the 'To' or 'CC' lines
/// It can be initialized with a list of displayNames, in which case, if any of the displayNames are in the 'To'
/// or 'CC' lines, the message will be retrieved
/// </summary>
public class RecipientsMailboxManager : IMailboxManager
{
private readonly IMessagePostProcessor _postProcessor;
private readonly RecipientsMailboxManagerRouter _router;
private readonly int _clientId;
public RecipientsMailboxManager(RecipientsMailboxManagerRouter router, IEnumerable<string> recipients, IMessagePostProcessor postProcessor)
{
_router = router;
_postProcessor = postProcessor;
_clientId = _router.RegisterMailbox(m => ShouldConsiderMessage(m, recipients.ToArray()));
}
public IEnumerable<IIncomingEmailMessage> ReadMessages()
{
return _router.GetMessages(_clientId);
}
public void OnProcessingFinished(IIncomingEmailMessage message, bool successful)
{
_postProcessor.Process((EWSIncomingMessage)message, successful);
}
private static bool ShouldConsiderMessage(IIncomingEmailMessage message, string[] recipients)
{
if (message == null)
{
return false;
}
// If no recipients were mentioned, it means process all incoming emails
if (!recipients.Any())
{
return true;
}
// If the recipient is in either the To or CC lines, then this message should be considered
return recipients.Any(recipient =>
EmailAddressesMatch(message.ToAddresses, recipient) ||
EmailAddressesMatch(message.ToNames, recipient) ||
EmailAddressesMatch(message.CcAddresses, recipient) ||
EmailAddressesMatch(message.CcNames, recipient));
}
private static bool EmailAddressesMatch(IEnumerable<string> emailAddresses, string recipient)
{
return emailAddresses != null &&
emailAddresses.Any(address =>
address != null && address.Equals(recipient, StringComparison.InvariantCultureIgnoreCase));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Mail2Bug.Email.EWS
{
/// <summary>
/// This imiplementation of IMailboxManager monitors the inbox of an exchange user, and retrieves
/// only messages that have a specific alias in the 'To' or 'CC' lines
/// It can be initialized with a list of displayNames, in which case, if any of the displayNames are in the 'To'
/// or 'CC' lines, the message will be retrieved
/// </summary>
public class RecipientsMailboxManager : IMailboxManager
{
private readonly IMessagePostProcessor _postProcessor;
private readonly RecipientsMailboxManagerRouter _router;
private readonly int _clientId;
public RecipientsMailboxManager(RecipientsMailboxManagerRouter router, IEnumerable<string> recipients, IMessagePostProcessor postProcessor)
{
_router = router;
_postProcessor = postProcessor;
_clientId = _router.RegisterMailbox(m => ShouldConsiderMessage(m, recipients.ToArray()));
}
public IEnumerable<IIncomingEmailMessage> ReadMessages()
{
return _router.GetMessages(_clientId);
}
public void OnProcessingFinished(IIncomingEmailMessage message, bool successful)
{
_postProcessor.Process((EWSIncomingMessage)message, successful);
}
private static bool ShouldConsiderMessage(IIncomingEmailMessage message, string[] recipients)
{
if (message == null)
{
return false;
}
// If no recipients were mentioned, it means process all incoming emails
if (!recipients.Any())
{
return true;
}
// If the recipient is in either the To or CC lines, then this message should be considered
return recipients.Any(recipient =>
EmailAddressesMatch(message.ToAddresses, recipient) ||
EmailAddressesMatch(message.ToNames, recipient) ||
EmailAddressesMatch(message.CcAddresses, recipient) ||
EmailAddressesMatch(message.CcNames, recipient));
}
private static bool EmailAddressesMatch(IEnumerable<string> emailAddresses, string recipient)
{
return emailAddresses != null &&
emailAddresses.Any(address =>
address.Equals(recipient, StringComparison.InvariantCultureIgnoreCase));
}
}
}
| mit | C# |
29b03145c95baf3210c828a689409f7c4158ba41 | work around for NUnit GUI runner problem | ShaKaRee/concordion-net,ShaKaRee/concordion-net,ShaKaRee/concordion-net,concordion/concordion-net,concordion/concordion-net,concordion/concordion-net | Concordion.Spec/Concordion/Configuration/BaseInputDirectoryTest.cs | Concordion.Spec/Concordion/Configuration/BaseInputDirectoryTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Concordion.Integration;
using Concordion.Internal;
using System.IO;
namespace Concordion.Spec.Concordion.Configuration
{
[ConcordionTest]
public class BaseInputDirectoryTest
{
private static bool m_InTestRun = false;
public bool DirectoryBasedExecuted(string baseInputDirectory)
{
if (m_InTestRun) return true;
m_InTestRun = true;
//work around for bug of NUnit GUI runner
baseInputDirectory = baseInputDirectory +
Path.DirectorySeparatorChar +
".." +
Path.DirectorySeparatorChar +
this.GetType().Assembly.GetName().Name;
var specificationConfig = new SpecificationConfig().Load(this.GetType());
specificationConfig.BaseInputDirectory = baseInputDirectory;
var fixtureRunner = new FixtureRunner(specificationConfig);
var testResult = fixtureRunner.Run(this);
m_InTestRun = false;
foreach (var failureDetail in testResult.FailureDetails) {
Console.WriteLine(failureDetail.Message);
Console.WriteLine(failureDetail.StackTrace);
}
foreach (var errorDetail in testResult.ErrorDetails)
{
Console.WriteLine(errorDetail.Message);
Console.WriteLine(errorDetail.StackTrace);
Console.WriteLine(errorDetail.Exception);
}
return !testResult.HasFailures && !testResult.HasExceptions;
}
public bool EmbeddedExecuted()
{
if (m_InTestRun) return true;
m_InTestRun = true;
var specificationConfig = new SpecificationConfig().Load(this.GetType());
specificationConfig.BaseInputDirectory = null;
var fixtureRunner = new FixtureRunner(specificationConfig);
var testResult = fixtureRunner.Run(this);
m_InTestRun = false;
return !testResult.HasFailures && !testResult.HasExceptions;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Concordion.Integration;
using Concordion.Internal;
namespace Concordion.Spec.Concordion.Configuration
{
[ConcordionTest]
public class BaseInputDirectoryTest
{
private static bool m_InTestRun = false;
public bool DirectoryBasedExecuted(string baseInputDirectory)
{
if (m_InTestRun) return true;
m_InTestRun = true;
var specificationConfig = new SpecificationConfig().Load(this.GetType());
specificationConfig.BaseInputDirectory = baseInputDirectory;
var fixtureRunner = new FixtureRunner(specificationConfig);
var testResult = fixtureRunner.Run(this);
m_InTestRun = false;
return !testResult.HasFailures && !testResult.HasExceptions;
}
public bool EmbeddedExecuted()
{
if (m_InTestRun) return true;
m_InTestRun = true;
var specificationConfig = new SpecificationConfig().Load(this.GetType());
specificationConfig.BaseInputDirectory = null;
var fixtureRunner = new FixtureRunner(specificationConfig);
var testResult = fixtureRunner.Run(this);
m_InTestRun = false;
return !testResult.HasFailures && !testResult.HasExceptions;
}
}
}
| apache-2.0 | C# |
084e7fc2d8bd4f9dd169395bb33ed0fff65ff520 | Fix latest chain properties, simplify WordCount property and make it deduce the order from the passed initial chain. | IvionSauce/MeidoBot | Chainey/SentenceConstruct.cs | Chainey/SentenceConstruct.cs | using System;
using System.Collections.Generic;
namespace Chainey
{
internal class SentenceConstruct
{
internal int WordCount { get; private set; }
internal string Sentence
{
get
{
var sen = new List<string>(Backwards);
sen.RemoveRange(0, order);
sen.Reverse();
sen.AddRange(Forwards);
return string.Join(" ", sen);
}
}
internal string LatestForwardChain
{
get
{
var chain = new string[order];
int start = Forwards.Count - order;
Forwards.CopyTo(start, chain, 0, order);
return string.Join(" ", Forwards, start, order);
}
}
internal string LatestBackwardChain
{
get
{
var chain = new string[order];
int start = Backwards.Count - order;
Backwards.CopyTo(start, chain, 0, order);
return string.Join(" ", Backwards, start, order);
}
}
List<string> Forwards;
List<string> Backwards;
readonly int order;
internal SentenceConstruct(string initialChain)
{
string[] split = initialChain.Split(' ');
Forwards = new List<string>(split);
Backwards = new List<string>(split);
Backwards.Reverse();
WordCount = split.Length;
order = split.Length;
}
internal void Append(string word)
{
Forwards.Add(word);
WordCount++;
}
internal void Prepend(string word)
{
Backwards.Add(word);
WordCount++;
}
}
} | using System;
using System.Collections.Generic;
namespace Chainey
{
internal class SentenceConstruct
{
internal int WordCount
{
get { return Forwards.Count + Backwards.Count - order; }
}
internal string Sentence
{
get
{
var sen = new List<string>(Backwards);
sen.RemoveRange(0, order);
sen.Reverse();
sen.AddRange(Forwards);
return string.Join(" ", sen);
}
}
internal string LatestForwardChain
{
get
{
int start = Forwards.Count - order;
return string.Join(" ", Forwards, start, order);
}
}
internal string LatestBackwardChain
{
get
{
int start = Backwards.Count - order;
return string.Join(" ", Backwards, start, order);
}
}
List<string> Forwards;
List<string> Backwards;
readonly int order;
internal SentenceConstruct(string initialChain, int order)
{
string[] split = initialChain.Split(' ');
Forwards = new List<string>(split);
Backwards = new List<string>(split);
Backwards.Reverse();
this.order = order;
}
internal void Append(string word)
{
Forwards.Add(word);
}
internal void Prepend(string word)
{
Backwards.Add(word);
}
}
} | bsd-2-clause | C# |
597f3ee243aa7d6bbeff4ca991bec61f2cf8f29f | Update Nuget version of package to 1.1.0.10-rc | KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet | src/keypay-dotnet/Properties/AssemblyInfo.cs | src/keypay-dotnet/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KeyPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("KeyPay")]
[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("93365e33-3b92-4ea6-ab42-ffecbc504138")]
// 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: AssemblyInformationalVersion("1.1.0.10-rc2")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("KeyPay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("KeyPay")]
[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("93365e33-3b92-4ea6-ab42-ffecbc504138")]
// 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: AssemblyInformationalVersion("1.1.0.10-rc")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
221cdf1c003652b67f58b86ddfe811e775c6caeb | fix code factor issues. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/MainViewModel.cs | WalletWasabi.Fluent/ViewModels/MainViewModel.cs | using Avalonia.Threading;
using NBitcoin;
using NBitcoin.Protocol;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;
using WalletWasabi.Gui.ViewModels;
using Global = WalletWasabi.Gui.Global;
namespace WalletWasabi.Fluent.ViewModels
{
public class MainViewModel : ViewModelBase, IScreen
{
private Global _global;
private StatusBarViewModel _statusBar;
private string _title = "Wasabi Wallet";
public MainViewModel(Global global)
{
_global = global;
Network = global.Network;
StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments);
Dispatcher.UIThread.Post(async () =>
{
await Task.Delay(5000);
Router.Navigate.Execute(new HomeViewModel(this));
});
}
public static MainViewModel Instance { get; internal set; }
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; }
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public Network Network { get; }
public StatusBarViewModel StatusBar
{
get { return _statusBar; }
set { this.RaiseAndSetIfChanged(ref _statusBar, value); }
}
public string Title
{
get => _title;
internal set => this.RaiseAndSetIfChanged(ref _title, value);
}
public void Initialize()
{
// Temporary to keep things running without VM modifications.
MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false);
StatusBar.Initialize(_global.Nodes.ConnectedNodes);
if (Network != Network.Main)
{
Title += $" - {Network}";
}
}
}
}
| using Avalonia.Threading;
using NBitcoin;
using NBitcoin.Protocol;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;
using WalletWasabi.Gui.ViewModels;
using Global = WalletWasabi.Gui.Global;
namespace WalletWasabi.Fluent.ViewModels
{
public class MainViewModel : ViewModelBase, IScreen
{
private Global _global;
private StatusBarViewModel _statusBar;
private string _title = "Wasabi Wallet";
public static MainViewModel Instance { get; internal set; }
public MainViewModel(Global global)
{
_global = global;
Network = global.Network;
StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments);
Dispatcher.UIThread.Post(async () =>
{
await Task.Delay(5000);
Router.Navigate.Execute(new HomeViewModel(this));
});
}
public void Initialize()
{
/// Temporary to keep things running without VM modifications.
MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false);
StatusBar.Initialize(_global.Nodes.ConnectedNodes);
if (Network != Network.Main)
{
Title += $" - {Network}";
}
}
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; }
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public Network Network { get; }
public StatusBarViewModel StatusBar
{
get { return _statusBar; }
set { this.RaiseAndSetIfChanged(ref _statusBar, value); }
}
public string Title
{
get => _title;
internal set => this.RaiseAndSetIfChanged(ref _title, value);
}
}
}
| mit | C# |
dd94ed971803948c33a87ccce4469db0da3c9f6c | remove leftover | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/ViewModels/MainViewModel.cs | WalletWasabi.Fluent/ViewModels/MainViewModel.cs | #nullable enable
using NBitcoin;
using ReactiveUI;
using System.Reactive;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Fluent.ViewModels.Dialog;
using System;
using Global = WalletWasabi.Gui.Global;
namespace WalletWasabi.Fluent.ViewModels
{
public class MainViewModel : ViewModelBase, IScreen, IDialogHost
{
private Global _global;
private StatusBarViewModel _statusBar;
private string _title = "Wasabi Wallet";
private DialogViewModelBase? _currentDialog;
private NavBarViewModel _navBar;
public MainViewModel(Global global)
{
_global = global;
Network = global.Network;
StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments);
NavBar = new NavBarViewModel(this, Router, global.WalletManager, global.UiConfig);
}
public static MainViewModel Instance { get; internal set; }
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; }
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public Network Network { get; }
public DialogViewModelBase? CurrentDialog
{
get => _currentDialog;
set => this.RaiseAndSetIfChanged(ref _currentDialog, value);
}
public NavBarViewModel NavBar
{
get => _navBar;
set => this.RaiseAndSetIfChanged(ref _navBar, value);
}
public StatusBarViewModel StatusBar
{
get => _statusBar;
set => this.RaiseAndSetIfChanged(ref _statusBar, value);
}
public string Title
{
get => _title;
internal set => this.RaiseAndSetIfChanged(ref _title, value);
}
public void Initialize()
{
// Temporary to keep things running without VM modifications.
MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false);
StatusBar.Initialize(_global.Nodes.ConnectedNodes);
if (Network != Network.Main)
{
Title += $" - {Network}";
}
}
}
}
| #nullable enable
using NBitcoin;
using ReactiveUI;
using System.Reactive;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Fluent.ViewModels.Dialog;
using System;
using Global = WalletWasabi.Gui.Global;
namespace WalletWasabi.Fluent.ViewModels
{
public class MainViewModel : ViewModelBase, IScreen, IDialogHost
{
private Global _global;
private StatusBarViewModel _statusBar;
private string _title = "Wasabi Wallet";
private DialogViewModelBase? _currentDialog;
private NavBarViewModel _navBar;
public MainViewModel(Global global)
{
_global = global;
Network = global.Network;
StatusBar = new StatusBarViewModel(global.DataDir, global.Network, global.Config, global.HostedServices, global.BitcoinStore.SmartHeaderChain, global.Synchronizer, global.LegalDocuments);
NavBar = new NavBarViewModel(this, Router, global.WalletManager, global.UiConfig);
}
private Action<bool> DialogStateListener { get; set; }
public static MainViewModel Instance { get; internal set; }
public RoutingState Router { get; } = new RoutingState();
public ReactiveCommand<Unit, IRoutableViewModel> GoNext { get; }
public ReactiveCommand<Unit, Unit> GoBack => Router.NavigateBack;
public Network Network { get; }
public DialogViewModelBase? CurrentDialog
{
get => _currentDialog;
set => this.RaiseAndSetIfChanged(ref _currentDialog, value);
}
public NavBarViewModel NavBar
{
get => _navBar;
set => this.RaiseAndSetIfChanged(ref _navBar, value);
}
public StatusBarViewModel StatusBar
{
get => _statusBar;
set => this.RaiseAndSetIfChanged(ref _statusBar, value);
}
public string Title
{
get => _title;
internal set => this.RaiseAndSetIfChanged(ref _title, value);
}
public void Initialize()
{
// Temporary to keep things running without VM modifications.
MainWindowViewModel.Instance = new MainWindowViewModel(_global.Network, _global.UiConfig, _global.WalletManager, null, null, false);
StatusBar.Initialize(_global.Nodes.ConnectedNodes);
if (Network != Network.Main)
{
Title += $" - {Network}";
}
}
}
}
| mit | C# |
9dbbc383e3abc0d93c8ceb0dab0c4f0b85b1b324 | switch to hitting 6080 for test | agrc/deq-enviro,agrc/deq-enviro,agrc/deq-enviro,agrc/deq-enviro | api/Search.Api/Services/QuerySoeServiceAsync.cs | api/Search.Api/Services/QuerySoeServiceAsync.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using Containers;
using Newtonsoft.Json.Linq;
using Search.Api.Formatters;
using Search.Api.Properties;
namespace Search.Api.Services {
public class QuerySoeServiceAsync : IQuerySoeService {
private string _url = "/arcgis/rest/services/DEQEnviro/MapService/MapServer/exts/DeqSearchSoe/Search";
/// <summary>
/// Queries the soe with specified values form value encoded.
/// </summary>
/// <param name="formValues">The form values.</param>
/// <param name="secure">
/// if set to <c>true</c> [secure].
/// </param>
/// <returns></returns>
public async Task<ResponseContainer<Dictionary<int, JObject>>> Query(
IEnumerable<KeyValuePair<string, string>> formValues, bool secure)
{
using (var client = new HttpClient())
{
var baseUrl = "http://test.mapserv.utah.gov:6080";
#if DEBUG
baseUrl = "http://localhost";
#endif
#if RELEASE
baseUrl = "http://mapserv.utah.gov";
#endif
client.BaseAddress = new Uri(baseUrl);
var content = new MultipartFormDataContent();
foreach (var pair in formValues)
{
content.Add(new StringContent(pair.Value), pair.Key);
}
if (secure)
{
_url = "/arcgis/rest/services/DEQEnviro/Secure/MapServer/exts/DeqSearchSoe/Search";
}
var response = await client.PostAsync(_url, content);
return await response.Content.ReadAsAsync<ResponseContainer<Dictionary<int, JObject>>>(
new[]
{
new TextPlainResponseFormatter()
});
}
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using Containers;
using Newtonsoft.Json.Linq;
using Search.Api.Formatters;
using Search.Api.Properties;
namespace Search.Api.Services {
public class QuerySoeServiceAsync : IQuerySoeService {
private string _url = "/arcgis/rest/services/DEQEnviro/MapService/MapServer/exts/DeqSearchSoe/Search";
/// <summary>
/// Queries the soe with specified values form value encoded.
/// </summary>
/// <param name="formValues">The form values.</param>
/// <param name="secure">
/// if set to <c>true</c> [secure].
/// </param>
/// <returns></returns>
public async Task<ResponseContainer<Dictionary<int, JObject>>> Query(
IEnumerable<KeyValuePair<string, string>> formValues, bool secure)
{
using (var client = new HttpClient())
{
var baseUrl = "http://test.mapserv.utah.gov";
#if DEBUG
baseUrl = "http://localhost";
#endif
#if RELEASE
baseUrl = "http://mapserv.utah.gov";
#endif
client.BaseAddress = new Uri(baseUrl);
var content = new MultipartFormDataContent();
foreach (var pair in formValues)
{
content.Add(new StringContent(pair.Value), pair.Key);
}
if (secure)
{
_url = "/arcgis/rest/services/DEQEnviro/Secure/MapServer/exts/DeqSearchSoe/Search";
}
var response = await client.PostAsync(_url, content);
return await response.Content.ReadAsAsync<ResponseContainer<Dictionary<int, JObject>>>(
new[]
{
new TextPlainResponseFormatter()
});
}
}
}
} | mit | C# |
780e0ba51a884cf63a3277e0e4442a17959a3459 | Fix CloudflareSolver | InfiniteSoul/Azuria | Azuria/Utilities/Net/CloudflareSolver.cs | Azuria/Utilities/Net/CloudflareSolver.cs | using System;
using System.Text.RegularExpressions;
using Azuria.Utilities.ErrorHandling;
using JetBrains.Annotations;
namespace Azuria.Utilities.Net
{
internal static class CloudflareSolver
{
#region
internal static ProxerResult<string> Solve([NotNull] string response, [NotNull] Uri originalUri)
{
try
{
GroupCollection lWierdEquasion =
new Regex(@"(var s, t, o, p[\S\s]+?};)[\S\s]+?(zyrziLd[\S\s]+?)a\.value = parseInt[\S\s]+?;").Match(
response).Groups;
string lScript = "var " + lWierdEquasion[1] + lWierdEquasion[2];
int lCloudflareAnswer = Convert.ToInt32(JsEval.Eval(lScript)) + originalUri.Host.Length;
string lChallengeId = new Regex("name=\"jschl_vc\" value=\"(\\w+)\"").Match(response).Groups[1].Value;
string lChallengePass = new Regex("name=\"pass\" value=\"(.+?)\"").Match(response).Groups[1].Value;
if (string.IsNullOrEmpty(lChallengeId.Trim()) || string.IsNullOrEmpty(lChallengePass.Trim()) ||
lCloudflareAnswer == int.MinValue)
return new ProxerResult<string>(new Exception[0]);
return
new ProxerResult<string>(
$"jschl_vc={lChallengeId}&pass={lChallengePass}&jschl_answer={lCloudflareAnswer}");
}
catch
{
return new ProxerResult<string>(new Exception[0]);
}
}
#endregion
}
} | using System;
using System.Text.RegularExpressions;
using Azuria.Utilities.ErrorHandling;
using JetBrains.Annotations;
namespace Azuria.Utilities.Net
{
internal static class CloudflareSolver
{
#region
internal static ProxerResult<string> Solve([NotNull] string response, [NotNull] Uri originalUri)
{
try
{
string lWierdVarMatch = new Regex("var\\s*?t,r,a,f,\\s?(\\S+?;)").Match(response).Groups[1].Value;
string lWierdVar = lWierdVarMatch.Split('=')[0];
string lWierdEquasion =
new Regex($"({lWierdVar}\\S+?);a.value = parseInt").Match(response).Groups[1].Value;
string lScript = "var " + lWierdVarMatch + lWierdEquasion;
int lCloudflareAnswer = Convert.ToInt32(JsEval.Eval(lScript)) + originalUri.Host.Length;
string lChallengeId = new Regex("name=\"jschl_vc\" value=\"(\\w+)\"").Match(response).Groups[1].Value;
string lChallengePass = new Regex("name=\"pass\" value=\"(.+?)\"").Match(response).Groups[1].Value;
if (string.IsNullOrEmpty(lChallengeId.Trim()) || string.IsNullOrEmpty(lChallengePass.Trim()) ||
lCloudflareAnswer == int.MinValue)
return new ProxerResult<string>(new Exception[0]);
return
new ProxerResult<string>(
$"jschl_vc={lChallengeId}&pass={lChallengePass}&jschl_answer={lCloudflareAnswer}");
}
catch
{
return new ProxerResult<string>(new Exception[0]);
}
}
#endregion
}
} | mit | C# |
5db837d4d8879d131046f725c5a8abcb182fa7cb | fix build | GregTrevellick/OpenInApp.Launcher,GregTrevellick/OpenInApp.Launcher,GregTrevellick/OpenInApp.Launcher | src/OpenInApp.Common/Helpers/AllAppsHelper.cs | src/OpenInApp.Common/Helpers/AllAppsHelper.cs | using System.Collections.Generic;
using System.Text;
namespace OpenInApp.Common.Helpers
{
public class AllAppsHelper
{
/// <summary>
/// Checks if a specified artefact exists on disc.
/// </summary>
/// <param name="fullExecutableFileName">Full name of the artefact.</param>
/// <returns></returns>
public static bool DoesActualPathToExeExist(string fullExecutableFileName)
{
return ArtefactsHelper.DoArtefactsExist(new List<string> { fullExecutableFileName });
}
/// <summary>
/// Gets the typical file extensions as a CSV string.
/// </summary>
/// <param name="defaultExts">The default exts.</param>
/// <returns></returns>
public static string GetDefaultTypicalFileExtensionsAsCsv(IEnumerable<string> defaultExts)
{
var stringBuilder = new StringBuilder();
foreach (var defaultExt in defaultExts)
{
stringBuilder.Append(defaultExt).Append(',');
}
return stringBuilder.ToString().TrimEnd(',');
}
}
}
| using System.Collections.Generic;
using System.Text;
namespace OpenInApp.Common.Helpers
{
public class AllAppsHelper
{
/// <summary>
/// Checks if a specified artefact exists on disc.
/// </summary>
/// <param name="fullExecutableFileName">Full name of the artefact.</param>
/// <returns></returns>
public static bool DoesActualPathToExeExist(string fullExecutableFileName)
{
return CommonFileHelper.DoArtefactsExist(new List<string> { fullExecutableFileName });
}
/// <summary>
/// Gets the typical file extensions as a CSV string.
/// </summary>
/// <param name="defaultExts">The default exts.</param>
/// <returns></returns>
public static string GetDefaultTypicalFileExtensionsAsCsv(IEnumerable<string> defaultExts)
{
var stringBuilder = new StringBuilder();
foreach (var defaultExt in defaultExts)
{
stringBuilder.Append(defaultExt).Append(',');
}
return stringBuilder.ToString().TrimEnd(',');
}
}
}
| mit | C# |
9728f26455b64f29f440503d01dbe7efd8bb298c | fix typo error for brokerList for autofac ioc | IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework | Src/iFramework.Plugins/IFramework.MessageQueue.ConfluentKafka/Config/FrameworkConfigurationExtension.cs | Src/iFramework.Plugins/IFramework.MessageQueue.ConfluentKafka/Config/FrameworkConfigurationExtension.cs | using IFramework.Config;
using IFramework.IoC;
namespace IFramework.MessageQueue.ConfluentKafka.Config
{
public static class FrameworkConfigurationExtension
{
private static int _backOffIncrement = 30;
public static Configuration UseConfluentKafka(this Configuration configuration,
string brokerlist,
int backOffIncrement = 30)
{
IoCFactory.Instance.CurrentContainer
.RegisterType<IMessageQueueClient, ConfluentKafkaClient>(Lifetime.Singleton,
new ConstructInjection(new ParameterInjection("brokerList", brokerlist)));
_backOffIncrement = backOffIncrement;
return configuration;
}
public static int GetBackOffIncrement(this Configuration configuration)
{
return _backOffIncrement;
}
}
} | using IFramework.Config;
using IFramework.IoC;
namespace IFramework.MessageQueue.ConfluentKafka.Config
{
public static class FrameworkConfigurationExtension
{
private static int _backOffIncrement = 30;
public static Configuration UseConfluentKafka(this Configuration configuration,
string brokerlist,
int backOffIncrement = 30)
{
IoCFactory.Instance.CurrentContainer
.RegisterType<IMessageQueueClient, ConfluentKafkaClient>(Lifetime.Singleton,
new ConstructInjection(new ParameterInjection("brokerlist", brokerlist)));
_backOffIncrement = backOffIncrement;
return configuration;
}
public static int GetBackOffIncrement(this Configuration configuration)
{
return _backOffIncrement;
}
}
} | mit | C# |
0fa6c9fd4e6d81a1c250963896db47ff8ba86a93 | Throw exception if not all compressed data could be read | SixLabors/Fonts | src/SixLabors.Fonts/Tables/WoffTableHeader.cs | src/SixLabors.Fonts/Tables/WoffTableHeader.cs | // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System.IO;
namespace SixLabors.Fonts.Tables
{
internal sealed class WoffTableHeader : TableHeader
{
public WoffTableHeader(string tag, uint offset, uint compressedLength, uint origLength, uint checkSum)
: base(tag, checkSum, offset, origLength)
=> this.CompressedLength = compressedLength;
public uint CompressedLength { get; }
public override BigEndianBinaryReader CreateReader(Stream stream)
{
// Stream is not compressed.
if (this.Length == this.CompressedLength)
{
return base.CreateReader(stream);
}
// Read all data from the compressed stream.
stream.Seek(this.Offset, SeekOrigin.Begin);
using var compressedStream = new IO.ZlibInflateStream(stream);
byte[] uncompressedBytes = new byte[this.Length];
int bytesRead = compressedStream.Read(uncompressedBytes, 0, uncompressedBytes.Length);
if (bytesRead < this.Length)
{
throw new InvalidFontFileException($"Could not read compressed data! Expected bytes: {this.Length}, bytes read: {bytesRead}");
}
var memoryStream = new MemoryStream(uncompressedBytes);
return new BigEndianBinaryReader(memoryStream, false);
}
// WOFF TableDirectoryEntry
// UInt32 | tag | 4-byte sfnt table identifier.
// UInt32 | offset | Offset to the data, from beginning of WOFF file.
// UInt32 | compLength | Length of the compressed data, excluding padding.
// UInt32 | origLength | Length of the uncompressed table, excluding padding.
// UInt32 | origChecksum | Checksum of the uncompressed table.
public static new WoffTableHeader Read(BigEndianBinaryReader reader) =>
new WoffTableHeader(reader.ReadTag(),
reader.ReadUInt32(),
reader.ReadUInt32(),
reader.ReadUInt32(),
reader.ReadUInt32());
}
}
| // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System.IO;
namespace SixLabors.Fonts.Tables
{
internal sealed class WoffTableHeader : TableHeader
{
public WoffTableHeader(string tag, uint offset, uint compressedLength, uint origLength, uint checkSum)
: base(tag, checkSum, offset, origLength)
=> this.CompressedLength = compressedLength;
public uint CompressedLength { get; }
public override BigEndianBinaryReader CreateReader(Stream stream)
{
// Stream is not compressed.
if (this.Length == this.CompressedLength)
{
return base.CreateReader(stream);
}
// Read all data from the compressed stream.
stream.Seek(this.Offset, SeekOrigin.Begin);
using var compressedStream = new IO.ZlibInflateStream(stream);
byte[] uncompressedBytes = new byte[this.Length];
compressedStream.Read(uncompressedBytes, 0, uncompressedBytes.Length);
var memoryStream = new MemoryStream(uncompressedBytes);
return new BigEndianBinaryReader(memoryStream, false);
}
// WOFF TableDirectoryEntry
// UInt32 | tag | 4-byte sfnt table identifier.
// UInt32 | offset | Offset to the data, from beginning of WOFF file.
// UInt32 | compLength | Length of the compressed data, excluding padding.
// UInt32 | origLength | Length of the uncompressed table, excluding padding.
// UInt32 | origChecksum | Checksum of the uncompressed table.
public static new WoffTableHeader Read(BigEndianBinaryReader reader) =>
new WoffTableHeader(reader.ReadTag(),
reader.ReadUInt32(),
reader.ReadUInt32(),
reader.ReadUInt32(),
reader.ReadUInt32());
}
}
| apache-2.0 | C# |
71ffba9258edfd987d6f53da2577c4a1122060d5 | fix EnumerableEx | RyotaMurohoshi/unity_snippets | unity/Assets/Scripts/Common/EnumerableEx.cs | unity/Assets/Scripts/Common/EnumerableEx.cs | using System.Collections.Generic;
namespace System.Linq
{
public static class EnumerableEx
{
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (resultSelector == null) throw new ArgumentNullException("resultSelector");
return ZipImpl(first, second, resultSelector);
}
private static IEnumerable<TResult> ZipImpl<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector)
{
using (var e1 = first.GetEnumerator())
using (var e2 = second.GetEnumerator())
while (e1.MoveNext() && e2.MoveNext())
{
yield return resultSelector(e1.Current, e2.Current);
}
}
}
} | using System.Collections.Generic;
namespace System.Linq
{
public static class EnumerableEx
{
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (resultSelector == null) throw new ArgumentNullException("resultSelector");
return ZipImpl(first, second, resultSelector);
}
private static IEnumerable<TResult> ZipImpl<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector)
{
using (var e1 = first.GetEnumerator())
using (var e2 = second.GetEnumerator())
while (e1.MoveNext() && e2.MoveNext())
{
yield return resultSelector(e1.Current, e2.Current);
}
}
- }
} | mit | C# |
f16f2790b3d929d6eff06daf95253e0ad741cf97 | Use readImei(Context) method | adjust/unity_sdk,adjust/unity_sdk,adjust/unity_sdk | Assets/AdjustImei/Android/AdjustImeiAndroid.cs | Assets/AdjustImei/Android/AdjustImeiAndroid.cs | using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace com.adjust.sdk.imei
{
#if UNITY_ANDROID
public class AdjustImeiAndroid
{
private static AndroidJavaClass ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
private static AndroidJavaObject ajoCurrentActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
public static void ReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
}
ajcAdjustImei.CallStatic("readImei", ajoCurrentActivity);
}
public static void DoNotReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
}
ajcAdjustImei.CallStatic("doNotReadImei");
}
}
#endif
}
| using System;
using System.Runtime.InteropServices;
using UnityEngine;
namespace com.adjust.sdk.imei
{
#if UNITY_ANDROID
public class AdjustImeiAndroid
{
private static AndroidJavaClass ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
public static void ReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
}
ajcAdjustImei.CallStatic("readImei");
}
public static void DoNotReadImei()
{
if (ajcAdjustImei == null)
{
ajcAdjustImei = new AndroidJavaClass("com.adjust.sdk.imei.AdjustImei");
}
ajcAdjustImei.CallStatic("doNotReadImei");
}
}
#endif
}
| mit | C# |
87f63ecf36a922274b52edc7882a69bcd1809afc | Fix VertexProperty.ToString(). | ExRam/ExRam.Gremlinq | ExRam.Gremlinq.Core/Elements/VertexProperty.cs | ExRam.Gremlinq.Core/Elements/VertexProperty.cs | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using LanguageExt;
using NullGuard;
namespace ExRam.Gremlinq.Core.GraphElements
{
public class VertexProperty<TValue, TMeta> : Property<TValue>, IVertexProperty
{
public VertexProperty(TValue value)
{
Value = value;
}
protected VertexProperty()
{
}
public static implicit operator VertexProperty<TValue, TMeta>(TValue value) => new VertexProperty<TValue, TMeta>(value);
public static implicit operator VertexProperty<TValue, TMeta>(TValue[] value) => throw new NotSupportedException();
public override string ToString()
{
return $"vp[{Label}->{GetValue()}]";
}
internal override IDictionary<string, object> GetMetaProperties() => Properties?.Serialize().ToDictionary(x => x.Item1.Name, x => x.Item2) ?? (IDictionary<string, object>)ImmutableDictionary<string, object>.Empty;
[AllowNull] public object Id { get; set; }
[AllowNull] public string Label { get; set; }
[AllowNull] public TMeta Properties { get; set; }
}
public class VertexProperty<TValue> : VertexProperty<TValue, IDictionary<string, object>>
{
protected VertexProperty()
{
Properties = new Dictionary<string, object>();
}
public VertexProperty(TValue value) : this()
{
Value = value;
}
public static implicit operator VertexProperty<TValue>(TValue value) => new VertexProperty<TValue>(value);
public static implicit operator VertexProperty<TValue>(TValue[] value) => throw new NotSupportedException();
internal override IDictionary<string, object> GetMetaProperties() => Properties;
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using LanguageExt;
using NullGuard;
namespace ExRam.Gremlinq.Core.GraphElements
{
public class VertexProperty<TValue, TMeta> : Property<TValue>, IVertexProperty
{
public VertexProperty(TValue value)
{
Value = value;
}
protected VertexProperty()
{
}
public static implicit operator VertexProperty<TValue, TMeta>(TValue value) => new VertexProperty<TValue, TMeta>(value);
public static implicit operator VertexProperty<TValue, TMeta>(TValue[] value) => throw new NotSupportedException();
public override string ToString()
{
return $"vp[{Key}->{GetValue()}]";
}
internal override IDictionary<string, object> GetMetaProperties() => Properties?.Serialize().ToDictionary(x => x.Item1.Name, x => x.Item2) ?? (IDictionary<string, object>)ImmutableDictionary<string, object>.Empty;
[AllowNull] public object Id { get; set; }
[AllowNull] public string Label { get; set; }
[AllowNull] public TMeta Properties { get; set; }
}
public class VertexProperty<TValue> : VertexProperty<TValue, IDictionary<string, object>>
{
protected VertexProperty()
{
Properties = new Dictionary<string, object>();
}
public VertexProperty(TValue value) : this()
{
Value = value;
}
public static implicit operator VertexProperty<TValue>(TValue value) => new VertexProperty<TValue>(value);
public static implicit operator VertexProperty<TValue>(TValue[] value) => throw new NotSupportedException();
internal override IDictionary<string, object> GetMetaProperties() => Properties;
}
}
| mit | C# |
5e15987fbf399f3c2900d384eb23dce3370531e7 | Update LoadSpecificSheets.cs | aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Articles/LoadSpecificSheets.cs | Examples/CSharp/Articles/LoadSpecificSheets.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class LoadSpecificSheets
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Define a new Workbook.
Workbook workbook;
//Set the load data option with selected sheet(s).
LoadDataOption dataOption = new LoadDataOption();
dataOption.SheetNames = new string[] { "Sheet2" };
//Load the workbook with the spcified worksheet only.
LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx);
loadOptions.LoadDataOptions = dataOption;
loadOptions.LoadDataAndFormatting = true;
//Creat the workbook.
workbook = new Workbook(dataDir+ "TestData.xlsx", loadOptions);
//Perform your desired task.
//Save the workbook.
workbook.Save(dataDir+ "outputFile.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class LoadSpecificSheets
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Define a new Workbook.
Workbook workbook;
//Set the load data option with selected sheet(s).
LoadDataOption dataOption = new LoadDataOption();
dataOption.SheetNames = new string[] { "Sheet2" };
//Load the workbook with the spcified worksheet only.
LoadOptions loadOptions = new LoadOptions(LoadFormat.Xlsx);
loadOptions.LoadDataOptions = dataOption;
loadOptions.LoadDataAndFormatting = true;
//Creat the workbook.
workbook = new Workbook(dataDir+ "TestData.xlsx", loadOptions);
//Perform your desired task.
//Save the workbook.
workbook.Save(dataDir+ "outputFile.out.xlsx");
}
}
} | mit | C# |
32cc1d99aaa4c844657cc9199d8b7b6223cda738 | Refactor - UserMessage instead of attribute | wachulski/nunit-migrator | nunit.migrator/CodeActions/AssertUserMessageDecorator.cs | nunit.migrator/CodeActions/AssertUserMessageDecorator.cs | using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Migrator.Model;
namespace NUnit.Migrator.CodeActions
{
internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator
{
private readonly string _userMessage;
public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator,
ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator)
{
if (attribute == null)
throw new ArgumentNullException(nameof(attribute));
_userMessage = attribute.UserMessage;
}
public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType)
{
var body = base.Create(method, assertedType);
if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation))
return body;
var userMessageArgument = SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
SyntaxFactory.ParseToken($"\"{_userMessage}\"")));
var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument);
return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList);
}
private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation)
{
invocation = null;
if (block.Statements.Count == 0)
return false;
invocation = (block.Statements.First() as ExpressionStatementSyntax)?
.Expression as InvocationExpressionSyntax;
return invocation != null;
}
}
} | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Migrator.Model;
namespace NUnit.Migrator.CodeActions
{
internal class AssertUserMessageDecorator : AssertExceptionBlockDecorator
{
private readonly ExceptionExpectancyAtAttributeLevel _attribute;
public AssertUserMessageDecorator(IAssertExceptionBlockCreator blockCreator,
ExceptionExpectancyAtAttributeLevel attribute) : base(blockCreator)
{
_attribute = attribute;
}
public override BlockSyntax Create(MethodDeclarationSyntax method, TypeSyntax assertedType)
{
var body = base.Create(method, assertedType);
if (!TryFindAssertThrowsInvocation(body, out InvocationExpressionSyntax invocation))
return body;
var userMessageArgument = SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression,
SyntaxFactory.ParseToken($"\"{_attribute.UserMessage}\""))); // TODO: no need for full attribute, msg only
var decoratedInvocationArgumentList = invocation.ArgumentList.AddArguments(userMessageArgument);
return body.ReplaceNode(invocation.ArgumentList, decoratedInvocationArgumentList);
}
private static bool TryFindAssertThrowsInvocation(BlockSyntax block, out InvocationExpressionSyntax invocation)
{
invocation = null;
if (block.Statements.Count == 0)
return false;
invocation = (block.Statements.First() as ExpressionStatementSyntax)?
.Expression as InvocationExpressionSyntax;
return invocation != null;
}
}
} | mit | C# |
f62bc87317d54ff7e67a754885c091b154f0be04 | Remove unused test | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/test/src/CSharp/Daemon/Stages/PerformanceHighlightings/PerformanceStageTests.cs | resharper/resharper-unity/test/src/CSharp/Daemon/Stages/PerformanceHighlightings/PerformanceStageTests.cs | using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.Highlightings;
using JetBrains.ReSharper.Psi;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.PerformanceHighlightings
{
[TestUnity]
public class PerformanceStageTest : UnityGlobalHighlightingsStageTestBase
{
protected override string RelativeTestDataRoot => @"CSharp\Daemon\Stages\PerformanceCriticalCodeAnalysis\";
[Test] public void SimpleTest() { DoNamedTest(); }
[Test] public void SimpleTest2() { DoNamedTest(); }
[Test] public void CommonTest() { DoNamedTest(); }
[Test]public void CoroutineTest() { DoNamedTest(); }
[Test] public void UnityObjectEqTest() { DoNamedTest(); }
[Test] public void IndirectCostlyTest() { DoNamedTest(); }
[Test] public void InefficientCameraMainUsageWarningTest() {DoNamedTest();}
[Test]public void InvokeAndSendMessageTest() {DoNamedTest();}
[Test] public void DisabledWarningTest() {DoNamedTest();}
[Test] public void LambdasTest() {DoNamedTest();}
[Test] public void LocalFunctionsTest() {DoNamedTest();}
[Test] public void CommentRootsTest() { DoNamedTest(); }
[Test] public void EditorClassesTest() {DoNamedTest();}
protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile file, IContextBoundSettingsStore settingsStore)
{
return highlighting is UnityPerformanceHighlightingBase;
}
}
}
| using JetBrains.Application.Settings;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.Highlightings;
using JetBrains.ReSharper.Psi;
using NUnit.Framework;
namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.PerformanceHighlightings
{
[TestUnity]
public class PerformanceStageTest : UnityGlobalHighlightingsStageTestBase
{
protected override string RelativeTestDataRoot => @"CSharp\Daemon\Stages\PerformanceCriticalCodeAnalysis\";
[Test] public void SimpleTest() { DoNamedTest(); }
[Test] public void SimpleTest2() { DoNamedTest(); }
[Test] public void CommonTest() { DoNamedTest(); }
[Test]public void CoroutineTest() { DoNamedTest(); }
[Test] public void UnityObjectEqTest() { DoNamedTest(); }
[Test] public void IndirectCostlyTest() { DoNamedTest(); }
[Test] public void InefficientCameraMainUsageWarningTest() {DoNamedTest();}
[Test]public void InvokeAndSendMessageTest() {DoNamedTest();}
[Test] public void DisabledWarningTest() {DoNamedTest();}
[Test] public void LambdasTest() {DoNamedTest();}
[Test] public void LocalFunctionsTest() {DoNamedTest();}
[Test] public void CommentRootsTest() { DoNamedTest(); }
[Test] public void AttributesTest() {DoNamedTest();}
[Test] public void EditorClassesTest() {DoNamedTest();}
protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile file, IContextBoundSettingsStore settingsStore)
{
return highlighting is UnityPerformanceHighlightingBase;
}
}
}
| apache-2.0 | C# |
33a805ffb6d6b547f610fd07cc7c3d9fd3978200 | test more levels with xml config | kalotay/tech-academy-logging | Logging/Logging/XmlConfigurationTests.cs | Logging/Logging/XmlConfigurationTests.cs | using System.Linq;
using NUnit.Framework;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
namespace Logging
{
[TestFixture]
public class XmlConfigurationTests
{
private const string MemoryAppenderName = "MemoryAppender";
private static readonly ILog Log = LogManager.GetLogger(typeof(XmlConfigurationTests));
private MemoryAppender _memoryAppender;
[TestFixtureSetUp]
public void BootstrapLogging()
{
XmlConfigurator.Configure();
var repository = LogManager.GetRepository();
var appenders = repository.GetAppenders();
foreach (var appender in appenders.Where(appender => appender.Name == MemoryAppenderName))
{
Assert.That(_memoryAppender, Is.Null, "Multiple appender with same name");
_memoryAppender = (MemoryAppender)appender;
}
Assert.That(_memoryAppender, Is.Not.Null, "Cannot find memory appender");
}
[Test]
public void LogsFatal()
{
Assert.That(Log.IsFatalEnabled, "Fatal level disabled");
Log.Fatal("Fatal");
var events = _memoryAppender.GetEvents();
var fatalEvents = events.Where(e => e.Level == Level.Fatal);
Assert.That(fatalEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Fatal"));
}
[Test]
public void LogsError()
{
Assert.That(Log.IsErrorEnabled, "Error level disabled");
Log.Error("Error");
var events = _memoryAppender.GetEvents();
var errorEvents = events.Where(e => e.Level == Level.Error);
Assert.That(errorEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Error"));
}
[Test]
public void LogsWarn()
{
Assert.That(Log.IsWarnEnabled, "Warn level disabled");
Log.Warn("Warn");
var events = _memoryAppender.GetEvents();
var warnEvents = events.Where(e => e.Level == Level.Warn);
Assert.That(warnEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Warn"));
}
[Test]
public void LogsInfo()
{
Assert.That(Log.IsInfoEnabled, "Info level disabled");
Log.Info("Info");
var events = _memoryAppender.GetEvents();
var infoEvents = events.Where(e => e.Level == Level.Info);
Assert.That(infoEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Info"));
}
[Test]
public void LogsDebug()
{
Assert.That(Log.IsDebugEnabled, "Debug level disabled");
Log.Debug("Debug");
var events = _memoryAppender.GetEvents();
var debugEvents = events.Where(e => e.Level == Level.Debug);
Assert.That(debugEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Debug"));
}
}
} | using System.Linq;
using NUnit.Framework;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
namespace Logging
{
[TestFixture]
public class XmlConfigurationTests
{
private const string MemoryAppenderName = "MemoryAppender";
private static readonly ILog Log = LogManager.GetLogger(typeof(XmlConfigurationTests));
private MemoryAppender _memoryAppender;
[TestFixtureSetUp]
public void BootstrapLogging()
{
XmlConfigurator.Configure();
var repository = LogManager.GetRepository();
var appenders = repository.GetAppenders();
foreach (var appender in appenders.Where(appender => appender.Name == MemoryAppenderName))
{
Assert.That(_memoryAppender, Is.Null, "Multiple appender with same name");
_memoryAppender = (MemoryAppender)appender;
}
Assert.That(_memoryAppender, Is.Not.Null, "Cannot find memory appender");
}
[Test]
public void LogsFatal()
{
Assert.That(Log.IsFatalEnabled, "Fatal level disabled");
Log.Fatal("Fatal");
var events = _memoryAppender.GetEvents();
var fatalEvents = events.Where(e => e.Level == Level.Fatal);
Assert.That(fatalEvents.Select(e => e.MessageObject), Has.Some.EqualTo("Fatal"));
}
}
} | mit | C# |
8057202fe1cd718c20225dc8065d33f5391eedbd | Remove caching of invoked expressions as it is hard to do and adds little benefit | ccoton/MFlow,ccoton/MFlow,ccoton/MFlow | MFlow.Core/Internal/ExpressionBuilder.cs | MFlow.Core/Internal/ExpressionBuilder.cs |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;
namespace MFlow.Core.Internal
{
/// <summary>
/// An expression builder
/// </summary>
class ExpressionBuilder<T> : IExpressionBuilder<T>
{
static IDictionary<object, object> _expressions= new Dictionary<object, object>();
static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>();
/// <summary>
/// Compiles the expression
/// </summary>
public Func<T, C> Compile<C>(Expression<Func<T, C>> expression)
{
if(_expressions.ContainsKey(expression))
return (Func<T, C>)_expressions[expression];
var compiled = expression.Compile();
_expressions.Add(expression, compiled);
return compiled;
}
/// <summary>
/// Invokes the expression
/// </summary>
public C Invoke<C>(Func<T, C> compiled, T target)
{
return compiled.Invoke(target);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;
namespace MFlow.Core.Internal
{
/// <summary>
/// An expression builder
/// </summary>
class ExpressionBuilder<T> : IExpressionBuilder<T>
{
static IDictionary<object, object> _expressions= new Dictionary<object, object>();
static IDictionary<InvokeCacheKey, object> _compilations = new Dictionary<InvokeCacheKey, object>();
/// <summary>
/// Compiles the expression
/// </summary>
public Func<T, C> Compile<C>(Expression<Func<T, C>> expression)
{
if(_expressions.ContainsKey(expression))
return (Func<T, C>)_expressions[expression];
var compiled = expression.Compile();
_expressions.Add(expression, compiled);
return compiled;
}
/// <summary>
/// Invokes the expression
/// </summary>
public C Invoke<C>(Func<T, C> compiled, T target)
{
return compiled.Invoke(target);
}
}
class InvokeCacheKey
{
public object Target{get;set;}
public object Func{get;set;}
}
}
| mit | C# |
a94ba6d6809caf82ff58306b8a02d54eef1dd785 | Correct #Name | TeamnetGroup/cap-net,darbio/cap-net | src/CAPNet.Tests/ValidatorTests/PolygonCoordinatePairsFirstLastValidatorTests.cs | src/CAPNet.Tests/ValidatorTests/PolygonCoordinatePairsFirstLastValidatorTests.cs | using CAPNet.Models;
using System.Linq;
using Xunit;
namespace CAPNet
{
public class PolygonCoordinatePairsFirstLastValidatorTests
{
[Fact]
public void PolygonWithFirstCoordinatePairDifferentFromLastCoordinatePairIsInvalid()
{
var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 39.47,-120.14");
var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon);
Assert.False(polygonCoordinatePairsFirstLastValidator.IsValid);
var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors
where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError)
select error;
Assert.NotEmpty(pairErrors);
}
[Fact]
public void PolygonWithFirstCoordinatePairEqualToLastCoordinatePairsIsValid()
{
var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 38.47,-120.14");
var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon);
Assert.True(polygonCoordinatePairsFirstLastValidator.IsValid);
var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors
where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError)
select error;
Assert.Empty(pairErrors);
}
}
}
| using CAPNet.Models;
using System.Linq;
using Xunit;
namespace CAPNet
{
public class PolygonCoordinatePairsFirstLastValidatorTests
{
[Fact]
public void PolygonWithFirstCoordinatePairDifferentFromLastCoordinatePairIsInvalid()
{
var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 39.47,-120.14");
var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon);
Assert.False(polygonCoordinatePairsFirstLastValidator.IsValid);
var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors
where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError)
select error;
Assert.NotEmpty(pairErrors);
}
[Fact]
public void PolygonWithFirstCoordinatePairEqualToLastCoordinateParisIsValid()
{
var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 38.47,-120.14");
var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon);
Assert.True(polygonCoordinatePairsFirstLastValidator.IsValid);
var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors
where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError)
select error;
Assert.Empty(pairErrors);
}
}
}
| mit | C# |
c97069f4ffdd2c0be82167daf681707606fb7314 | rework to inherit from BaseFormatterAttribute | billboga/Supurlative,kendaleiv/Supurlative,ritterim/Supurlative | src/Core/IgnoreAttribute.cs | src/Core/IgnoreAttribute.cs | using System;
using System.Collections.Generic;
namespace RimDev.Supurlative
{
[AttributeUsage(AttributeTargets.Property)]
public class IgnoreAttribute : BaseFormatterAttribute
{
public override void Invoke(string fullPropertyName, object value, Type valueType, IDictionary<string, object> dictionary, SupurlativeOptions options)
{
return;
}
public override bool IsMatch(Type currentType, SupurlativeOptions options)
{
return false;
}
}
}
| using System;
namespace RimDev.Supurlative
{
[AttributeUsage(AttributeTargets.Property)]
public class IgnoreAttribute : Attribute
{
public IgnoreAttribute()
{
Ignore = true;
}
public bool Ignore { get; private set; }
public static bool PropertyHasIgnoreAttribute(Object x, string propertyName)
{
var pi = x.GetType().GetProperty(propertyName);
if (pi == null) return false;
return Attribute.IsDefined(pi, typeof(IgnoreAttribute));
}
}
}
| mit | C# |
347a95b991400eac1ba9676d522354edbcc9e0af | Add doc comment. | eriawan/roslyn,KevinRansom/roslyn,xasx/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,jmarolf/roslyn,dotnet/roslyn,aelij/roslyn,VSadov/roslyn,weltkante/roslyn,abock/roslyn,mgoertz-msft/roslyn,genlu/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,mavasani/roslyn,AlekseyTs/roslyn,physhi/roslyn,aelij/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jcouv/roslyn,panopticoncentral/roslyn,physhi/roslyn,nguerrera/roslyn,jasonmalinowski/roslyn,gafter/roslyn,gafter/roslyn,cston/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,MichalStrehovsky/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,abock/roslyn,jcouv/roslyn,nguerrera/roslyn,DustinCampbell/roslyn,sharwell/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,bartdesmet/roslyn,tannergooding/roslyn,heejaechang/roslyn,eriawan/roslyn,heejaechang/roslyn,stephentoub/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,dotnet/roslyn,dpoeschl/roslyn,cston/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,davkean/roslyn,aelij/roslyn,nguerrera/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,sharwell/roslyn,davkean/roslyn,mavasani/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,tmat/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,MichalStrehovsky/roslyn,davkean/roslyn,tmeschter/roslyn,dpoeschl/roslyn,KevinRansom/roslyn,physhi/roslyn,cston/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,diryboy/roslyn,tmat/roslyn,dotnet/roslyn,weltkante/roslyn,agocke/roslyn,dpoeschl/roslyn,heejaechang/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,VSadov/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,MichalStrehovsky/roslyn,gafter/roslyn,reaction1989/roslyn,abock/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,genlu/roslyn,tmeschter/roslyn,brettfo/roslyn,tmat/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,brettfo/roslyn,xasx/roslyn,weltkante/roslyn,AlekseyTs/roslyn,diryboy/roslyn,agocke/roslyn,KirillOsenkov/roslyn,DustinCampbell/roslyn,diryboy/roslyn,reaction1989/roslyn,AmadeusW/roslyn,wvdd007/roslyn,genlu/roslyn,DustinCampbell/roslyn,jcouv/roslyn,xasx/roslyn | src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/IGenerateEqualsAndGetHashCodeService.cs | src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/IGenerateEqualsAndGetHashCodeService.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
/// <summary>
/// Service that can be used to generate <see cref="object.Equals(object)"/> and
/// <see cref="object.GetHashCode"/> overloads for use from other IDE features.
/// </summary>
internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService
{
/// <summary>
/// Formats only the members in the provided document that were generated by this interface.
/// </summary>
Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken);
Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string localNameOpt, CancellationToken cancellationToken);
Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken);
Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken);
Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken);
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
/// <summary>
/// Service that can be used to generate <see cref="object.Equals(object)"/> and
/// <see cref="object.GetHashCode"/> overloads for use from other IDE features.
/// </summary>
internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService
{
Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken);
Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string localNameOpt, CancellationToken cancellationToken);
Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken);
Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken);
Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken);
}
}
| mit | C# |
ad7de72e03d4a227ed9a63f7c9956864665c1d92 | Remove unused extension | mavasani/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn | src/Workspaces/Core/Portable/Shared/Extensions/FileLinePositionSpanExtensions.cs | src/Workspaces/Core/Portable/Shared/Extensions/FileLinePositionSpanExtensions.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.
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class FileLinePositionSpanExtensions
{
}
}
| // 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.
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class FileLinePositionSpanExtensions
{
/// <summary>
/// Get mapped file path if exist, otherwise return null.
/// </summary>
public static string? GetMappedFilePathIfExist(this FileLinePositionSpan fileLinePositionSpan)
=> fileLinePositionSpan.HasMappedPath ? fileLinePositionSpan.Path : null;
}
}
| mit | C# |
d673cf58bed631d51d3784479f19eb53192f4b6c | Make DataListBoxItemAutomationPeer an inner class. | zooba/PTVS,Microsoft/PTVS,huguesv/PTVS,int19h/PTVS,Microsoft/PTVS,huguesv/PTVS,Microsoft/PTVS,int19h/PTVS,zooba/PTVS,huguesv/PTVS,zooba/PTVS,huguesv/PTVS,int19h/PTVS,Microsoft/PTVS,huguesv/PTVS,int19h/PTVS,zooba/PTVS,int19h/PTVS,zooba/PTVS,int19h/PTVS,Microsoft/PTVS,huguesv/PTVS,Microsoft/PTVS,zooba/PTVS | Python/Product/EnvironmentsList/DataListBox.cs | Python/Product/EnvironmentsList/DataListBox.cs | // Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System.Windows.Automation.Peers;
using System.Windows.Controls;
namespace Microsoft.PythonTools.EnvironmentsList {
public sealed class DataListBox : ListBox {
protected override AutomationPeer OnCreateAutomationPeer() {
return new DataListBoxAutomationPeer(this);
}
sealed class DataListBoxAutomationPeer : ListBoxAutomationPeer {
public DataListBoxAutomationPeer(ListBox owner) : base(owner) { }
protected override ItemAutomationPeer CreateItemAutomationPeer(object item) {
return new DataListBoxItemAutomationPeer(item, this);
}
}
sealed class DataListBoxItemAutomationPeer : ListBoxItemAutomationPeer {
public DataListBoxItemAutomationPeer(object owner, SelectorAutomationPeer selectorAutomationPeer) : base(owner, selectorAutomationPeer) {
}
protected override string GetClassNameCore() {
return "DataListBoxItem";
}
protected override AutomationControlType GetAutomationControlTypeCore() {
return AutomationControlType.DataItem;
}
}
}
}
| // Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System.Windows.Automation.Peers;
using System.Windows.Controls;
namespace Microsoft.PythonTools.EnvironmentsList {
public sealed class DataListBox : ListBox {
protected override AutomationPeer OnCreateAutomationPeer() {
return new DataListBoxAutomationPeer(this);
}
sealed class DataListBoxAutomationPeer : ListBoxAutomationPeer {
public DataListBoxAutomationPeer(ListBox owner) : base(owner) { }
protected override ItemAutomationPeer CreateItemAutomationPeer(object item) {
return new DataListBoxItemAutomationPeer(item, this);
}
}
}
sealed class DataListBoxItemAutomationPeer : ListBoxItemAutomationPeer {
public DataListBoxItemAutomationPeer(object owner, SelectorAutomationPeer selectorAutomationPeer) : base(owner, selectorAutomationPeer) {
}
protected override string GetClassNameCore() {
return "DataListBoxItem";
}
protected override AutomationControlType GetAutomationControlTypeCore() {
return AutomationControlType.DataItem;
}
}
}
| apache-2.0 | C# |
c435caa7d13bae645a0e49d253f0cf2f547a4ade | Add check for new deployments to DaysLiveReportElement (#5299) | QuantConnect/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,StefanoRaggi/Lean,jameschch/Lean,QuantConnect/Lean,StefanoRaggi/Lean,jameschch/Lean,QuantConnect/Lean,AlexCatarino/Lean,JKarathiya/Lean,StefanoRaggi/Lean,AlexCatarino/Lean,AlexCatarino/Lean,jameschch/Lean,JKarathiya/Lean,JKarathiya/Lean,StefanoRaggi/Lean,jameschch/Lean,JKarathiya/Lean,jameschch/Lean,QuantConnect/Lean | Report/ReportElements/DaysLiveReportElement.cs | Report/ReportElements/DaysLiveReportElement.cs | /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Packets;
namespace QuantConnect.Report.ReportElements
{
internal class DaysLiveReportElement : ReportElement
{
private LiveResult _live;
/// <summary>
/// Create a new metric describing the number of days an algorithm has been live.
/// </summary>
/// <param name="name">Name of the widget</param>
/// <param name="key">Location of injection</param>
/// <param name="backtest">Backtest result object</param>
/// <param name="live">Live result object</param>
public DaysLiveReportElement(string name, string key, LiveResult live)
{
_live = live;
Name = name;
Key = key;
}
/// <summary>
/// The generated output string to be injected
/// </summary>
public override string Render()
{
if (_live == null)
{
return "-";
}
var equityPoints = ResultsUtil.EquityPoints(_live);
if (equityPoints.Count == 0)
{
Result = 0;
return "0";
}
var daysLive = (DateTime.UtcNow - equityPoints.First().Key).Days;
Result = daysLive;
return daysLive.ToStringInvariant();
}
}
}
| /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using QuantConnect.Packets;
namespace QuantConnect.Report.ReportElements
{
internal class DaysLiveReportElement : ReportElement
{
private LiveResult _live;
/// <summary>
/// Create a new metric describing the number of days an algorithm has been live.
/// </summary>
/// <param name="name">Name of the widget</param>
/// <param name="key">Location of injection</param>
/// <param name="backtest">Backtest result object</param>
/// <param name="live">Live result object</param>
public DaysLiveReportElement(string name, string key, LiveResult live)
{
_live = live;
Name = name;
Key = key;
}
/// <summary>
/// The generated output string to be injected
/// </summary>
public override string Render()
{
if (_live == null)
{
return "-";
}
var equityPoints = ResultsUtil.EquityPoints(_live);
var daysLive = (DateTime.UtcNow - equityPoints.First().Key).Days;
Result = daysLive;
return daysLive.ToStringInvariant();
}
}
}
| apache-2.0 | C# |
03e48bd941adc3cf03f66cac62944b18c8907da0 | Bump Version | mj1856/SimpleImpersonation | SimpleImpersonation/Properties/AssemblyInfo.cs | SimpleImpersonation/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SimpleImpersonation")]
[assembly: AssemblyDescription("A tiny library that lets you impersonate any user, by acting as a managed wrapper for the LogonUser Win32 function.")]
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Simple Impersonation")]
[assembly: AssemblyCopyright("Copyright © Matt Johnson")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("2.0.1.*")]
[assembly: AssemblyInformationalVersion("2.0.1")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("SimpleImpersonation")]
[assembly: AssemblyDescription("A tiny library that lets you impersonate any user, by acting as a managed wrapper for the LogonUser Win32 function.")]
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Simple Impersonation")]
[assembly: AssemblyCopyright("Copyright © Matt Johnson")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyInformationalVersion("2.0.0")]
| mit | C# |
aa1659333b65a7eb84b385c3c6cb264c29ca66fc | Remove override of DialogHandler.Invalidate | PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto | Source/Eto.Platform.Mac/Forms/DialogHandler.cs | Source/Eto.Platform.Mac/Forms/DialogHandler.cs | using System;
using SD = System.Drawing;
using Eto.Drawing;
using Eto.Forms;
using MonoMac.AppKit;
using MonoMac.Foundation;
namespace Eto.Platform.Mac.Forms
{
public class DialogHandler : MacWindow<MyWindow, Dialog>, IDialog
{
Button button;
MacModal.ModalHelper session;
class DialogWindow : MyWindow {
public new DialogHandler Handler
{
get { return base.Handler as DialogHandler; }
set { base.Handler = value; }
}
public DialogWindow()
: base(new SD.Rectangle(0,0,200,200), NSWindowStyle.Closable | NSWindowStyle.Titled, NSBackingStore.Buffered, false)
{
}
[Export("cancelOperation:")]
public void CancelOperation(IntPtr sender)
{
if (Handler.AbortButton != null)
Handler.AbortButton.OnClick (EventArgs.Empty);
}
}
public DialogDisplayMode DisplayMode { get; set; }
public Button AbortButton { get; set; }
public Button DefaultButton
{
get { return button; }
set
{
button = value;
if (button != null) {
var b = button.ControlObject as NSButton;
if (b != null)
Control.DefaultButtonCell = b.Cell;
else
Control.DefaultButtonCell = null;
}
else
Control.DefaultButtonCell = null;
}
}
public DialogHandler ()
{
this.DisposeControl = false;
var dlg = new DialogWindow();
dlg.Handler = this;
Control = dlg;
ConfigureWindow ();
}
public DialogResult ShowDialog (Control parent)
{
if (parent != null) {
if (parent.ControlObject is NSWindow) Control.ParentWindow = (NSWindow)parent.ControlObject;
else if (parent.ControlObject is NSView) Control.ParentWindow = ((NSView)parent.ControlObject).Window;
}
Control.MakeKeyWindow ();
Widget.Closed += HandleClosed;
switch (DisplayMode) {
case DialogDisplayMode.Attached:
MacModal.RunSheet (Control, out session);
break;
default:
case DialogDisplayMode.Default:
case DialogDisplayMode.Separate:
MacModal.Run (Control, out session);
break;
}
return Widget.DialogResult;
}
void HandleClosed (object sender, EventArgs e)
{
if (session != null)
session.Stop ();
Widget.Closed -= HandleClosed;
}
public override void Close ()
{
if (session != null && session.IsSheet) {
session.Stop ();
}
else
base.Close ();
}
}
}
| using System;
using SD = System.Drawing;
using Eto.Drawing;
using Eto.Forms;
using MonoMac.AppKit;
using MonoMac.Foundation;
namespace Eto.Platform.Mac.Forms
{
public class DialogHandler : MacWindow<MyWindow, Dialog>, IDialog
{
Button button;
MacModal.ModalHelper session;
class DialogWindow : MyWindow {
public new DialogHandler Handler
{
get { return base.Handler as DialogHandler; }
set { base.Handler = value; }
}
public DialogWindow()
: base(new SD.Rectangle(0,0,200,200), NSWindowStyle.Closable | NSWindowStyle.Titled, NSBackingStore.Buffered, false)
{
}
[Export("cancelOperation:")]
public void CancelOperation(IntPtr sender)
{
if (Handler.AbortButton != null)
Handler.AbortButton.OnClick (EventArgs.Empty);
}
}
public DialogDisplayMode DisplayMode { get; set; }
public Button AbortButton { get; set; }
public Button DefaultButton
{
get { return button; }
set
{
button = value;
if (button != null) {
var b = button.ControlObject as NSButton;
if (b != null)
Control.DefaultButtonCell = b.Cell;
else
Control.DefaultButtonCell = null;
}
else
Control.DefaultButtonCell = null;
}
}
public DialogHandler ()
{
this.DisposeControl = false;
var dlg = new DialogWindow();
dlg.Handler = this;
Control = dlg;
ConfigureWindow ();
}
public DialogResult ShowDialog (Control parent)
{
if (parent != null) {
if (parent.ControlObject is NSWindow) Control.ParentWindow = (NSWindow)parent.ControlObject;
else if (parent.ControlObject is NSView) Control.ParentWindow = ((NSView)parent.ControlObject).Window;
}
Control.MakeKeyWindow ();
Widget.Closed += HandleClosed;
switch (DisplayMode) {
case DialogDisplayMode.Attached:
MacModal.RunSheet (Control, out session);
break;
default:
case DialogDisplayMode.Default:
case DialogDisplayMode.Separate:
MacModal.Run (Control, out session);
break;
}
return Widget.DialogResult;
}
public void Invalidate(Rectangle rect)
{
throw new NotImplementedException();
}
void HandleClosed (object sender, EventArgs e)
{
if (session != null)
session.Stop ();
Widget.Closed -= HandleClosed;
}
public override void Close ()
{
if (session != null && session.IsSheet) {
session.Stop ();
}
else
base.Close ();
}
}
}
| bsd-3-clause | C# |
3949f78f2487d6cce561f8ff8bbd537ff2e51cc3 | change input on menu | heyx3/rubber-duck-love | Assets/Scripts/SplashMenu.cs | Assets/Scripts/SplashMenu.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SplashMenu : MonoBehaviour
{
public AudioSource music;
public bool splashDone;
public bool musicPlaying;
public SpriteRenderer splash;
public Animator instruction;
public Animator credits;
// Update is called once per frame
void Start()
{
StartCoroutine(WaitAndStart(3.0f));
}
void Update()
{
if (splashDone)
{
if (!musicPlaying)
{
splash.enabled = false;
music.Play();
musicPlaying = true;
}
if (Input.anyKeyDown)
{
if (instruction.GetBool("visible") == true)
{
if (Input.GetButtonDown("Throw"))
{
SceneManager.LoadScene(1);
}
}
if (Input.GetButtonDown("Quack"))
{
bool cred = credits.GetBool("visible");
credits.SetBool("visible", !cred);
}
if (instruction.GetBool("visible") != true)
{
instruction.SetBool("visible", true);
}
}
}
}
private IEnumerator WaitAndStart(float waitTime)
{
yield return new WaitForSeconds(waitTime);
splashDone = true;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SplashMenu : MonoBehaviour
{
public AudioSource music;
public bool splashDone;
public bool musicPlaying;
public SpriteRenderer splash;
public Animator instruction;
public Animator credits;
// Update is called once per frame
void Start()
{
StartCoroutine(WaitAndStart(3.0f));
}
void Update()
{
if (splashDone)
{
if (!musicPlaying)
{
splash.enabled = false;
music.Play();
musicPlaying = true;
}
if (Input.anyKeyDown)
{
if (instruction.GetBool("visible") == true)
{
if (Input.GetKeyDown(KeyCode.Space))
{
SceneManager.LoadScene(1);
}
}
if (Input.GetKeyDown(KeyCode.C))
{
bool cred = credits.GetBool("visible");
credits.SetBool("visible", !cred);
}
if (instruction.GetBool("visible") != true)
{
instruction.SetBool("visible", true);
}
}
}
}
private IEnumerator WaitAndStart(float waitTime)
{
yield return new WaitForSeconds(waitTime);
splashDone = true;
}
}
| mit | C# |
ba32cc21d92bed02a0b08c16d8a8131c7e57ec53 | Add missing ctor field initializations | mkoscielniak/SSMScripter | SSMScripter/Scripter/Smo/SmoObjectMetadata.cs | SSMScripter/Scripter/Smo/SmoObjectMetadata.cs | using SSMScripter.Integration;
using System;
using System.Data;
namespace SSMScripter.Scripter.Smo
{
public class SmoObjectMetadata
{
public SmoObjectType Type { get; protected set; }
public string Schema { get; protected set; }
public string Name { get; protected set; }
public string ParentSchema { get; protected set; }
public string ParentName { get; protected set; }
public bool? AnsiNullsStatus { get; set; }
public bool? QuotedIdentifierStatus { get; set; }
public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName)
{
Type = type;
Schema = schema;
Name = name;
ParentSchema = parentSchema;
ParentName = parentName;
}
}
}
| using SSMScripter.Integration;
using System;
using System.Data;
namespace SSMScripter.Scripter.Smo
{
public class SmoObjectMetadata
{
public SmoObjectType Type { get; protected set; }
public string Schema { get; protected set; }
public string Name { get; protected set; }
public string ParentSchema { get; protected set; }
public string ParentName { get; protected set; }
public bool? AnsiNullsStatus { get; set; }
public bool? QuotedIdentifierStatus { get; set; }
public SmoObjectMetadata(SmoObjectType type, string schema, string name, string parentSchema, string parentName)
{
Schema = schema;
Name = name;
}
}
}
| mit | C# |
eefff8f026d2827190188811ba7b08031b238b7c | Update SettingsFixture.cs | Shuttle/Shuttle.Esb | Shuttle.Esb.Tests/Settings/SettingsFixture.cs | Shuttle.Esb.Tests/Settings/SettingsFixture.cs | using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace Shuttle.Esb.Tests
{
public class SettingsFixture
{
protected ServiceBusSettings GetSettings()
{
var result = new ServiceBusSettings();
new ConfigurationBuilder()
.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @".\Settings\appsettings.json")).Build()
.GetSection(ServiceBusSettings.SectionName).Bind(result);
return result;
}
}
} | using System;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace Shuttle.Esb.Tests
{
public class SettingsFixture
{
protected ServiceBusSettings GetSettings()
{
var result = new Esb.ServiceBusSettings();
new ConfigurationBuilder()
.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @".\Settings\appsettings.json")).Build()
.GetSection(Esb.ServiceBusSettings.SectionName).Bind(result);
return result;
}
}
} | bsd-3-clause | C# |
87a7898f8817b35eca5e0649716990174818f252 | Update Shaco.cs | metaphorce/leaguesharp | MetaSmite/Champions/Shaco.cs | MetaSmite/Champions/Shaco.cs | using System;
using LeagueSharp;
using LeagueSharp.Common;
using SharpDX;
namespace MetaSmite.Champions
{
public static class Shaco
{
internal static Spell champSpell;
private static Menu Config = MetaSmite.Config;
private static double totalDamage;
private static double spellDamage;
public static void Load()
{
//Load spells
champSpell = new Spell(SpellSlot.E, 625f);
//Spell usage.
Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true);
//Events
Game.OnUpdate += OnGameUpdate;
}
private static void OnGameUpdate(EventArgs args)
{
if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active)
{
if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range)
{
spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot);
totalDamage = spellDamage + SmiteManager.damage;
if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() &&
SmiteManager.smite.IsReady() &&
champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health)
{
MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob);
}
if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() &&
champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health)
{
MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob);
}
}
}
}
}
}
| using System;
using LeagueSharp;
using LeagueSharp.Common;
using SharpDX;
namespace MetaSmite.Champions
{
public static class Shaco
{
internal static Spell champSpell;
private static Menu Config = MetaSmite.Config;
private static double totalDamage;
private static double spellDamage;
public static void Load()
{
//Load spells
champSpell = new Spell(SpellSlot.E, 625f);
//Spell usage.
Config.AddItem(new MenuItem("Enabled-" + MetaSmite.Player.ChampionName, MetaSmite.Player.ChampionName + "-" + champSpell.Slot)).SetValue(true);
//Events
Game.OnGameUpdate += OnGameUpdate;
}
private static void OnGameUpdate(EventArgs args)
{
if (Config.Item("Enabled").GetValue<KeyBind>().Active || Config.Item("EnabledH").GetValue<KeyBind>().Active)
{
if (SmiteManager.mob != null && Config.Item(SmiteManager.mob.BaseSkinName).GetValue<bool>() && Vector3.Distance(MetaSmite.Player.ServerPosition, SmiteManager.mob.ServerPosition) <= champSpell.Range)
{
spellDamage = MetaSmite.Player.GetSpellDamage(SmiteManager.mob, champSpell.Slot);
totalDamage = spellDamage + SmiteManager.damage;
if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() &&
SmiteManager.smite.IsReady() &&
champSpell.IsReady() && totalDamage >= SmiteManager.mob.Health)
{
MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob);
}
if (Config.Item("Enabled-" + ObjectManager.Player.ChampionName).GetValue<bool>() &&
champSpell.IsReady() && spellDamage >= SmiteManager.mob.Health)
{
MetaSmite.Player.Spellbook.CastSpell(champSpell.Slot, SmiteManager.mob);
}
}
}
}
}
}
| mit | C# |
950dd65f839144a2e06263673b498eecee46f2ae | make it a function | taka-oyama/UniHttp | Assets/UniHttp/Support/Cache/CacheStorage.cs | Assets/UniHttp/Support/Cache/CacheStorage.cs | using UnityEngine;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace UniHttp
{
public class CacheStorage
{
// for some reason File.Exists returns false when threading, so I'm forced to lock it.
object locker;
IFileHandler fileHandler;
DirectoryInfo baseDirectory;
MD5 hash;
string password;
public CacheStorage(IFileHandler fileHandler, string baseDirectory)
{
this.locker = new object();
this.fileHandler = fileHandler;
this.baseDirectory = new DirectoryInfo(baseDirectory).CreateSubdirectory("Cache");
this.hash = new MD5CryptoServiceProvider();
this.password = Application.identifier;
}
public virtual void Write(Uri uri, byte[] data)
{
lock(locker) {
fileHandler.Write(ComputePath(uri), data);
}
}
public virtual byte[] Read(Uri uri)
{
lock(locker) {
return fileHandler.Read(ComputePath(uri));
}
}
public virtual bool Exists(Uri uri)
{
lock(locker) {
return fileHandler.Exists(ComputePath(uri));
}
}
public virtual void Clear()
{
lock(locker) {
var dirs = baseDirectory.GetDirectories();
for(var i = 0; i < dirs.Length; i++) {
dirs[i].Delete(true);
}
}
}
string ComputePath(Uri uri)
{
return ComputeDirectory(uri) + ComputeFileName(uri);
}
string ComputeDirectory(Uri uri)
{
return baseDirectory.FullName + "/" + uri.Authority.Replace(":", "_") + "/";
}
string ComputeFileName(Uri uri)
{
string data = string.Concat(password, uri.Authority, uri.AbsolutePath);
byte[] bytes = hash.ComputeHash(Encoding.ASCII.GetBytes(data));
StringBuilder sb = new StringBuilder();
for(int i = 0; i < bytes.Length; i++) {
sb.Append(bytes[i].ToString("X2"));
}
return sb.ToString();
}
}
}
| using UnityEngine;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace UniHttp
{
public class CacheStorage
{
// for some reason File.Exists returns false when threading, so I'm forced to lock it.
object locker;
IFileHandler fileHandler;
DirectoryInfo baseDirectory;
MD5 hash;
string password;
public CacheStorage(IFileHandler fileHandler, string baseDirectory)
{
this.locker = new object();
this.fileHandler = fileHandler;
this.baseDirectory = new DirectoryInfo(baseDirectory).CreateSubdirectory("Cache");
this.hash = new MD5CryptoServiceProvider();
this.password = Application.identifier;
}
public virtual void Write(Uri uri, byte[] data)
{
lock(locker) {
fileHandler.Write(ComputeDirectory(uri) + ComputeFileName(uri), data);
}
}
public virtual byte[] Read(Uri uri)
{
lock(locker) {
return fileHandler.Read(ComputeDirectory(uri) + ComputeFileName(uri));
}
}
public virtual bool Exists(Uri uri)
{
lock(locker) {
return fileHandler.Exists(ComputeDirectory(uri) + ComputeFileName(uri));
}
}
public virtual void Clear()
{
lock(locker) {
var dirs = baseDirectory.GetDirectories();
for(var i = 0; i < dirs.Length; i++) {
dirs[i].Delete(true);
}
}
}
string ComputeDirectory(Uri uri)
{
return baseDirectory.FullName + "/" + uri.Authority.Replace(":", "_") + "/";
}
string ComputeFileName(Uri uri)
{
string data = string.Concat(password, uri.Authority, uri.AbsolutePath);
byte[] bytes = hash.ComputeHash(Encoding.ASCII.GetBytes(data));
StringBuilder sb = new StringBuilder();
for(int i = 0; i < bytes.Length; i++) {
sb.Append(bytes[i].ToString("X2"));
}
return sb.ToString();
}
}
}
| mit | C# |
14c3a35c07ed0842d55bb8f18a885b13c5966cd2 | Modify institutions path retrieval | code4romania/anabi-gestiune-api,code4romania/anabi-gestiune-api,code4romania/anabi-gestiune-api | Anabi.InstitutionsImporter/InstitutionImporter.cs | Anabi.InstitutionsImporter/InstitutionImporter.cs | using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
namespace Anabi.InstitutionsImporter
{
public static class InstitutionImporter
{
private readonly static string SOURCE = "institutions.json";
public static List<Institution> Deserialize()
{
string institutionsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), SOURCE);
using (StreamReader streamReader = File.OpenText(institutionsPath))
{
JsonSerializer serializer = new JsonSerializer();
return (List<Institution>)serializer
.Deserialize(streamReader, typeof(List<Institution>));
}
}
}
}
| using Newtonsoft.Json;
using System.IO;
using System.Collections.Generic;
namespace Anabi.InstitutionsImporter
{
public static class InstitutionImporter
{
public static List<Institution> Deserialize()
{
using (StreamReader streamReader = File.OpenText($@"institutions.json"))
{
JsonSerializer serializer = new JsonSerializer();
return (List<Institution>)serializer
.Deserialize(streamReader, typeof(List<Institution>));
}
}
}
}
| mpl-2.0 | C# |
6c8ccb4455e357fcbfbf3f287705a486d794ce64 | 优化函数“空转”效率 | topameng/tolua | Assets/ToLua/Injection/LuaInjectionStation.cs | Assets/ToLua/Injection/LuaInjectionStation.cs | using System;
using System.Collections;
using System.Collections.Generic;
namespace LuaInterface
{
[Flags]
public enum InjectType
{
None = 0,
After = 1,
Before = 1 << 1,
Replace = 1 << 2,
ReplaceWithPreInvokeBase = 1 << 3,
ReplaceWithPostInvokeBase = 1 << 4
}
public class LuaInjectionStation
{
public const byte NOT_INJECTION_FLAG = 0;
public const byte INVALID_INJECTION_FLAG = byte.MaxValue;
static int cacheSize;
static byte[] injectionFlagCache;
static LuaFunction[] injectFunctionCache;
static LuaInjectionStation()
{
injectionFlagCache = new byte[cacheSize];
injectFunctionCache = new LuaFunction[cacheSize];
}
public static byte GetInjectFlag(int index)
{
byte result = INVALID_INJECTION_FLAG;
result = injectionFlagCache[index];
if (result == INVALID_INJECTION_FLAG)
{
return NOT_INJECTION_FLAG;
}
else if (result == NOT_INJECTION_FLAG)
{
/// Delay injection not supported
if (LuaState.GetInjectInitState(index))
{
injectionFlagCache[index] = INVALID_INJECTION_FLAG;
}
}
return result;
}
public static LuaFunction GetInjectionFunction(int index)
{
return injectFunctionCache[index];
}
public static void CacheInjectFunction(int index, byte injectFlag, LuaFunction func)
{
injectFunctionCache[index] = func;
injectionFlagCache[index] = injectFlag;
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
namespace LuaInterface
{
[Flags]
public enum InjectType
{
None = 0,
After = 1,
Before = 1 << 1,
Replace = 1 << 2,
ReplaceWithPreInvokeBase = 1 << 3,
ReplaceWithPostInvokeBase = 1 << 4
}
public class LuaInjectionStation
{
public const byte NOT_INJECTION_FLAG = 0;
public const byte INVALID_INJECTION_FLAG = byte.MaxValue;
static int cacheSize;
static byte[] injectionFlagCache;
static LuaFunction[] injectFunctionCache;
static LuaInjectionStation()
{
injectionFlagCache = new byte[cacheSize];
injectFunctionCache = new LuaFunction[cacheSize];
}
public static byte GetInjectFlag(int index)
{
byte result = INVALID_INJECTION_FLAG;
result = injectionFlagCache[index];
if (result == NOT_INJECTION_FLAG)
{
/// Delay injection not supported
if (LuaState.GetInjectInitState(index))
{
injectionFlagCache[index] = INVALID_INJECTION_FLAG;
}
}
else if (result == INVALID_INJECTION_FLAG)
{
return NOT_INJECTION_FLAG;
}
return result;
}
public static LuaFunction GetInjectionFunction(int index)
{
return injectFunctionCache[index];
}
public static void CacheInjectFunction(int index, byte injectFlag, LuaFunction func)
{
injectFunctionCache[index] = func;
injectionFlagCache[index] = injectFlag;
}
}
}
| mit | C# |
c10516fe3c679bb3dc3535970b9d242fa8e85035 | increment patch version, | jwChung/Experimentalism,jwChung/Experimentalism | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.8.18")]
[assembly: AssemblyInformationalVersion("0.8.18")]
/*
* Version 0.8.18
*
* This version publishes the Experiment nuget package again.
*/ | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.8.18")]
[assembly: AssemblyInformationalVersion("0.8.18-pre01")]
/*
* Version 0.8.18-pre01
*
* To test publishing.
*/ | mit | C# |
d9886d8c6b6a11c4ce8ca43b8483caabca2269d2 | Fix typos | EricSten-MSFT/kudu,juvchan/kudu,shibayan/kudu,duncansmart/kudu,projectkudu/kudu,puneet-gupta/kudu,kenegozi/kudu,juvchan/kudu,mauricionr/kudu,EricSten-MSFT/kudu,dev-enthusiast/kudu,projectkudu/kudu,uQr/kudu,MavenRain/kudu,YOTOV-LIMITED/kudu,YOTOV-LIMITED/kudu,sitereactor/kudu,uQr/kudu,YOTOV-LIMITED/kudu,puneet-gupta/kudu,bbauya/kudu,puneet-gupta/kudu,oliver-feng/kudu,projectkudu/kudu,shanselman/kudu,shanselman/kudu,duncansmart/kudu,duncansmart/kudu,barnyp/kudu,chrisrpatterson/kudu,shrimpy/kudu,EricSten-MSFT/kudu,projectkudu/kudu,kali786516/kudu,kali786516/kudu,shrimpy/kudu,shibayan/kudu,oliver-feng/kudu,duncansmart/kudu,kenegozi/kudu,badescuga/kudu,kenegozi/kudu,shibayan/kudu,mauricionr/kudu,sitereactor/kudu,chrisrpatterson/kudu,barnyp/kudu,badescuga/kudu,badescuga/kudu,barnyp/kudu,EricSten-MSFT/kudu,juvchan/kudu,chrisrpatterson/kudu,kenegozi/kudu,juvchan/kudu,dev-enthusiast/kudu,projectkudu/kudu,bbauya/kudu,mauricionr/kudu,juoni/kudu,kali786516/kudu,shibayan/kudu,uQr/kudu,mauricionr/kudu,dev-enthusiast/kudu,WeAreMammoth/kudu-obsolete,shanselman/kudu,bbauya/kudu,shrimpy/kudu,YOTOV-LIMITED/kudu,MavenRain/kudu,sitereactor/kudu,MavenRain/kudu,WeAreMammoth/kudu-obsolete,barnyp/kudu,puneet-gupta/kudu,MavenRain/kudu,badescuga/kudu,juvchan/kudu,bbauya/kudu,chrisrpatterson/kudu,juoni/kudu,sitereactor/kudu,shibayan/kudu,WeAreMammoth/kudu-obsolete,oliver-feng/kudu,badescuga/kudu,dev-enthusiast/kudu,kali786516/kudu,EricSten-MSFT/kudu,oliver-feng/kudu,sitereactor/kudu,juoni/kudu,shrimpy/kudu,puneet-gupta/kudu,juoni/kudu,uQr/kudu | Kudu.Services/Deployment/DeploymentService.cs | Kudu.Services/Deployment/DeploymentService.cs | using System.Collections.Generic;
using System.ComponentModel;
using System.Json;
using System.ServiceModel;
using System.ServiceModel.Web;
using Kudu.Core.Deployment;
namespace Kudu.Services.Deployment
{
[ServiceContract]
public class DeploymentService
{
private readonly IDeploymentManager _deploymentManager;
public DeploymentService(IDeploymentManager deploymentManager)
{
_deploymentManager = deploymentManager;
}
[Description("Gets the id of the current active deployment.")]
[WebGet(UriTemplate = "id")]
public string GetActiveDeploymentId()
{
return _deploymentManager.ActiveDeploymentId;
}
[Description("Performs a deployment.")]
[WebInvoke(UriTemplate = "")]
public void Deploy()
{
_deploymentManager.Deploy();
}
[Description("Restore a previously successful deployment based on its id.")]
[WebInvoke(UriTemplate = "restore")]
public void Restore(JsonObject input)
{
_deploymentManager.Deploy((string)input["id"]);
}
[Description("Builds a specific deployment based on its id.")]
[WebInvoke(UriTemplate = "build")]
public void Build(JsonObject input)
{
_deploymentManager.Build((string)input["id"]);
}
[Description("Gets the deployment results of all deployments.")]
[WebGet(UriTemplate = "log")]
public IEnumerable<DeployResult> GetDeployResults()
{
return _deploymentManager.GetResults();
}
[Description("Gets the log of a specific deployment based on its id.")]
[WebGet(UriTemplate = "log?id={id}")]
public IEnumerable<LogEntry> GetLogEntry(string id)
{
return _deploymentManager.GetLogEntries(id);
}
[Description("Gets the deployment result of a specific deployment based on its id.")]
[WebGet(UriTemplate = "details?id={id}")]
public DeployResult GetResult(string id)
{
return _deploymentManager.GetResult(id);
}
}
}
| using System.Collections.Generic;
using System.ComponentModel;
using System.Json;
using System.ServiceModel;
using System.ServiceModel.Web;
using Kudu.Core.Deployment;
namespace Kudu.Services.Deployment
{
[ServiceContract]
public class DeploymentService
{
private readonly IDeploymentManager _deploymentManager;
public DeploymentService(IDeploymentManager deploymentManager)
{
_deploymentManager = deploymentManager;
}
[Description("Gets the id of the current active deployement.")]
[WebGet(UriTemplate = "id")]
public string GetActiveDeploymentId()
{
return _deploymentManager.ActiveDeploymentId;
}
[Description("Performs a deployment.")]
[WebInvoke(UriTemplate = "")]
public void Deploy()
{
_deploymentManager.Deploy();
}
[Description("Restore a previously successful deployment based on its id.")]
[WebInvoke(UriTemplate = "restore")]
public void Restore(JsonObject input)
{
_deploymentManager.Deploy((string)input["id"]);
}
[Description("Builds a specific deployement based on its id.")]
[WebInvoke(UriTemplate = "build")]
public void Build(JsonObject input)
{
_deploymentManager.Build((string)input["id"]);
}
[Description("Gets the deployment results of all deployments.")]
[WebGet(UriTemplate = "log")]
public IEnumerable<DeployResult> GetDeployResults()
{
return _deploymentManager.GetResults();
}
[Description("Gets the log of a specific deployement based on its id.")]
[WebGet(UriTemplate = "log?id={id}")]
public IEnumerable<LogEntry> GetLogEntry(string id)
{
return _deploymentManager.GetLogEntries(id);
}
[Description("Gets the deployement result of a specific deployement based on its id.")]
[WebGet(UriTemplate = "details?id={id}")]
public DeployResult GetResult(string id)
{
return _deploymentManager.GetResult(id);
}
}
}
| apache-2.0 | C# |
a4997e0f51b45aef43d860b663161e00cf7b8563 | Add ScriptNamedArgument.ToString | textamina/scriban,lunet-io/scriban | src/Scriban/Syntax/ScriptNamedArgument.cs | src/Scriban/Syntax/ScriptNamedArgument.cs | // Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
namespace Scriban.Syntax
{
public class ScriptNamedArgument : ScriptExpression
{
public ScriptNamedArgument()
{
}
public ScriptNamedArgument(string name)
{
Name = name;
}
public ScriptNamedArgument(string name, ScriptExpression value)
{
Name = name;
Value = value;
}
public string Name { get; set; }
public ScriptExpression Value { get; set; }
public override object Evaluate(TemplateContext context)
{
if (Value != null) return context.Evaluate(Value);
return true;
}
public override void Write(RenderContext context)
{
if (Name == null)
{
return;
}
context.Write(Name);
if (Value != null)
{
context.Write(":");
context.Write(Value);
}
}
public override string ToString()
{
return $"{Name}: {Value}";
}
}
} | // Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
namespace Scriban.Syntax
{
public class ScriptNamedArgument : ScriptExpression
{
public ScriptNamedArgument()
{
}
public ScriptNamedArgument(string name)
{
Name = name;
}
public ScriptNamedArgument(string name, ScriptExpression value)
{
Name = name;
Value = value;
}
public string Name { get; set; }
public ScriptExpression Value { get; set; }
public override object Evaluate(TemplateContext context)
{
if (Value != null) return context.Evaluate(Value);
return true;
}
public override void Write(RenderContext context)
{
if (Name == null)
{
return;
}
context.Write(Name);
if (Value != null)
{
context.Write(":");
context.Write(Value);
}
}
}
} | bsd-2-clause | C# |
a6e47c7c78eb2ceeb52004894bad3e0d2d8798b6 | Fix typo | MarcosMeli/FileHelpers | FileHelpers/Attributes/FieldNullValueAttribute.cs | FileHelpers/Attributes/FieldNullValueAttribute.cs | using System;
using System.ComponentModel;
namespace FileHelpers
{
/// <summary>
/// Indicates the value to assign to the field in the case of a NULL value.
/// A default value if none supplied in the field itself.
/// </summary>
/// <remarks>
/// You must specify a string and a converter that can be converted to the
/// type or an object of the correct type to be directly assigned.
/// <para/>
/// See the <a href="http://www.filehelpers.net/mustread">complete attributes list</a> for more
/// information and examples of each one.
/// </remarks>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class FieldNullValueAttribute : Attribute
{
/// <summary>Default value for a null value.</summary>
public object NullValue { get; private set; }
// internal bool NullValueOnWrite = false;
/// <summary>
/// Defines the default in event of a null value.
/// Object must be of the correct type
/// </summary>
/// <param name="nullValue">The value to assign the case of a NULL value.</param>
public FieldNullValueAttribute(object nullValue)
{
NullValue = nullValue;
// NullValueOnWrite = useOnWrite;
}
// /// <summary>Defines the default for a null value.</summary>
// /// <param name="nullValue">The value to assign in the "NULL" case.</param>
// public FieldNullValueAttribute(object nullValue): this(nullValue, false)
// {}
// /// <summary>Indicates a type and a string to be converted to that type.</summary>
// /// <param name="type">The type of the null value.</param>
// /// <param name="nullValue">The string to be converted to the specified type.</param>
// /// <param name="useOnWrite">Indicates that if the field has that value when the library writes, then the engine use an empty string.</param>
// public FieldNullValueAttribute(Type type, string nullValue, bool useOnWrite):this(Convert.ChangeType(nullValue, type, null), useOnWrite)
// {}
/// <summary>Indicates a type and a string to be converted to that type.</summary>
/// <param name="type">The type of the null value.</param>
/// <param name="nullValue">The string to be converted to the specified type.</param>
public FieldNullValueAttribute(Type type, string nullValue)
: this(TypeDescriptor.GetConverter(type).ConvertFromString(nullValue)) {}
}
} | using System;
using System.ComponentModel;
namespace FileHelpers
{
/// <summary>
/// Indicates the value to assign to the field in the case of a NULL value.
/// A default value if none supplied in the field itself.
/// </summary>
/// <remarks>
/// You must specify a string and a converter that can be converted to the
/// type or an object of the correct type to be directly assigned.
/// <para/>
/// See the <a href="http://www.filehelpers.net/mustread">complete attributes list</a> for more
/// information and examples of each one.
/// </remarks>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class FieldNullValueAttribute : Attribute
{
/// <summary>Default value for a null value.</summary>
public object NullValue { get; private set; }
// internal bool NullValueOnWrite = false;
/// <summary>
/// Defines the default in event of a null value.
/// Object must be of teh correct type
/// </summary>
/// <param name="nullValue">The value to assign the case of a NULL value.</param>
public FieldNullValueAttribute(object nullValue)
{
NullValue = nullValue;
// NullValueOnWrite = useOnWrite;
}
// /// <summary>Defines the default for a null value.</summary>
// /// <param name="nullValue">The value to assign in the "NULL" case.</param>
// public FieldNullValueAttribute(object nullValue): this(nullValue, false)
// {}
// /// <summary>Indicates a type and a string to be converted to that type.</summary>
// /// <param name="type">The type of the null value.</param>
// /// <param name="nullValue">The string to be converted to the specified type.</param>
// /// <param name="useOnWrite">Indicates that if the field has that value when the library writes, then the engine use an empty string.</param>
// public FieldNullValueAttribute(Type type, string nullValue, bool useOnWrite):this(Convert.ChangeType(nullValue, type, null), useOnWrite)
// {}
/// <summary>Indicates a type and a string to be converted to that type.</summary>
/// <param name="type">The type of the null value.</param>
/// <param name="nullValue">The string to be converted to the specified type.</param>
public FieldNullValueAttribute(Type type, string nullValue)
: this(TypeDescriptor.GetConverter(type).ConvertFromString(nullValue)) {}
}
} | mit | C# |
07a4459c02f728b936cd993209b8e8cc220149e7 | Update testeController.cs | NanoMania/GitRepoVisualStudio,NanoMania/GitRepoVisualStudio | GitTutorialVS/Controllers/testeController.cs | GitTutorialVS/Controllers/testeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GitTutorialVS.Controllers
{
public class testeController : Controller
{
// GET: teste
public ActionResult Index()
{
//wejdwe jhfvsdjhsdjhcskjdzikzshisizk
return View();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GitTutorialVS.Controllers
{
public class testeController : Controller
{
// GET: teste
public ActionResult Index()
{
//wejdwejhfvsdjhsdjhcskjdzikzshisizk
return View();
}
}
} | mit | C# |
a0c2376fc139facf1c67d18f40ea729bc2a12cae | fix package name | WasimAhmad/Serenity,linpiero/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,TukekeSoft/Serenity,rolembergfilho/Serenity,TukekeSoft/Serenity,linpiero/Serenity,WasimAhmad/Serenity,TukekeSoft/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,dfaruque/Serenity,volkanceylan/Serenity,linpiero/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,linpiero/Serenity,dfaruque/Serenity,linpiero/Serenity,dfaruque/Serenity,TukekeSoft/Serenity | Serenity.Reporting/Properties/AssemblyInfo.cs | Serenity.Reporting/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Serenity Platform - Reporting Library")]
[assembly: AssemblyDescription(
"Contains reporting classes...")]
[assembly: ComVisible(false)] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Serenity Platform - Data Entity Library")]
[assembly: AssemblyDescription(
"Contains reporting classes...")]
[assembly: ComVisible(false)] | mit | C# |
99b156f4ef623885638a17a295c9f7a426c2d22f | edit parameter in login request. | robertzml/Hyperion,robertzml/Hyperion,robertzml/Hyperion | Hyperion.BizAdapter/Protocol/LoginRequest.cs | Hyperion.BizAdapter/Protocol/LoginRequest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hyperion.BizAdapter.Protocol
{
using Newtonsoft.Json;
/// <summary>
/// 登录请求
/// </summary>
public class LoginRequest : BaseRequest
{
#region Field
/// <summary>
/// 控制器
/// </summary>
private string contolller = "freemall/accountToApp/";
#endregion //Field
#region Method
/// <summary>
/// 用户登录
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="password">密码</param>
/// <param name="osType">操作系统类型</param>
/// <param name="loginType">登录方式</param>
/// <param name="imei">IMEI</param>
/// <returns></returns>
public dynamic Login(string userName, string password, int osType, int loginType, string imei)
{
string url = "";
if (loginType == 3)
{
url = string.Format("{0}{1}login?phone={2}&password={3}&osType={4}&loginType={5}&imei={6}",
host, contolller, userName, password, osType, loginType, imei);
}
else
{
url = string.Format("{0}{1}login?userName={2}&password={3}&osType={4}&loginType={5}&imei={6}",
host, contolller, userName, password, osType, loginType, imei);
}
var content = Get(url);
dynamic obj = JsonConvert.DeserializeObject<dynamic>(content);
return obj;
}
#endregion //Method
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hyperion.BizAdapter.Protocol
{
using Newtonsoft.Json;
/// <summary>
/// 登录请求
/// </summary>
public class LoginRequest : BaseRequest
{
#region Field
/// <summary>
/// 控制器
/// </summary>
private string contolller = "freemall/accountToApp/";
#endregion //Field
#region Method
/// <summary>
/// 用户登录
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="password">密码</param>
/// <param name="osType">操作系统类型</param>
/// <param name="loginType">登录方式</param>
/// <param name="imei">IMEI</param>
/// <returns></returns>
public dynamic Login(string userName, string password, int osType, int loginType, string imei)
{
string url = string.Format("{0}{1}login?userName={2}&password={3}&phoneType={4}&loginType={5}&imei={6}",
host, contolller, userName, password, osType, loginType, imei);
var content = Get(url);
dynamic obj = JsonConvert.DeserializeObject<dynamic>(content);
return obj;
}
#endregion //Method
}
}
| apache-2.0 | C# |
c6ad963c8de38c88abeb696b0f3f7c7cf53a91fb | clone the connection for each reader and writer, allow multithread access to the event store | Pondidum/Ledger.Stores.Postgres,Pondidum/Ledger.Stores.Postgres | Ledger.Stores.Postgres/PostgresEventStore.cs | Ledger.Stores.Postgres/PostgresEventStore.cs | using Npgsql;
namespace Ledger.Stores.Postgres
{
public class PostgresEventStore : IEventStore
{
private readonly NpgsqlConnection _connection;
public PostgresEventStore(NpgsqlConnection connection)
{
_connection = connection;
}
public IStoreReader<TKey> CreateReader<TKey>(IStoreConventions storeConventions)
{
var connection = _connection.Clone();
connection.Open();
var transaction = connection.BeginTransaction();
return new PostgresStoreReader<TKey>(
connection,
transaction,
sql => Events(storeConventions, sql),
sql => Snapshots(storeConventions, sql)
);
}
public IStoreWriter<TKey> CreateWriter<TKey>(IStoreConventions storeConventions)
{
var connection = _connection.Clone();
connection.Open();
var transaction = connection.BeginTransaction();
return new PostgresStoreWriter<TKey>(
connection,
transaction,
sql => Events(storeConventions, sql),
sql => Snapshots(storeConventions, sql)
);
}
private string Events(IStoreConventions conventions, string sql)
{
return sql.Replace("{table}", conventions.EventStoreName());
}
private string Snapshots(IStoreConventions conventions, string sql)
{
return sql.Replace("{table}", conventions.SnapshotStoreName());
}
}
}
| using System.Collections.Generic;
using System.Data;
using System.Linq;
using Dapper;
using Newtonsoft.Json;
using Npgsql;
namespace Ledger.Stores.Postgres
{
public class PostgresEventStore : IEventStore
{
private readonly NpgsqlConnection _connection;
public PostgresEventStore(NpgsqlConnection connection)
{
_connection = connection;
}
public IStoreReader<TKey> CreateReader<TKey>(IStoreConventions storeConventions)
{
if (_connection.State != ConnectionState.Open)
_connection.Open();
var transaction = _connection.BeginTransaction();
return new PostgresStoreReader<TKey>(
_connection,
transaction,
sql => Events(storeConventions, sql),
sql => Snapshots(storeConventions, sql)
);
}
public IStoreWriter<TKey> CreateWriter<TKey>(IStoreConventions storeConventions)
{
if (_connection.State != ConnectionState.Open)
_connection.Open();
var transaction = _connection.BeginTransaction();
return new PostgresStoreWriter<TKey>(
_connection,
transaction,
sql => Events(storeConventions, sql),
sql => Snapshots(storeConventions, sql)
);
}
private string Events(IStoreConventions conventions, string sql)
{
return sql.Replace("{table}", conventions.EventStoreName());
}
private string Snapshots(IStoreConventions conventions, string sql)
{
return sql.Replace("{table}", conventions.SnapshotStoreName());
}
}
}
| lgpl-2.1 | C# |
a428e82d22faf94ffc245688e8a7d353e648c714 | change parameter name | kaosborn/KaosCollections | Source/RankedSet/ICollectionDebugView.cs | Source/RankedSet/ICollectionDebugView.cs | //
// Library: KaosCollections
// File: ICollectionDebugView.cs
//
// Copyright © 2009-2017 Kasey Osborn (github.com/kaosborn)
// MIT License - Use and redistribute freely
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Kaos.Collections
{
internal class ICollectionDebugView<T>
{
private readonly ICollection<T> target;
public ICollectionDebugView (ICollection<T> collection)
{
if (collection == null)
throw new ArgumentNullException (nameof (collection));
this.target = collection;
}
[DebuggerBrowsable (DebuggerBrowsableState.RootHidden)]
public T[] Items
{
get
{
var items = new T[target.Count];
target.CopyTo (items, 0);
return items;
}
}
}
}
| //
// Library: KaosCollections
// File: ICollectionDebugView.cs
//
// Copyright © 2009-2017 Kasey Osborn (github.com/kaosborn)
// MIT License - Use and redistribute freely
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Kaos.Collections
{
/// <exclude />
internal class ICollectionDebugView<T>
{
private readonly ICollection<T> target;
public ICollectionDebugView (ICollection<T> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException (nameof (dictionary));
this.target = dictionary;
}
[DebuggerBrowsable (DebuggerBrowsableState.RootHidden)]
public T[] Items
{
get
{
var items = new T[target.Count];
target.CopyTo (items, 0);
return items;
}
}
}
}
| mit | C# |
018826069452470464326ebf4dc81fe330e10f40 | Mark SynthesisEditContext obsolete because it is a bad pattern to use. | kamsar/Synthesis | Source/Synthesis/SynthesisEditContext.cs | Source/Synthesis/SynthesisEditContext.cs | using System;
using Sitecore.Data.Items;
namespace Synthesis
{
#pragma warning disable 0618 // disable the warning about InnerItem here - it's cool
/// <summary>
/// Provides a means to put an item in editing mode.
/// </summary>
/// <remarks>
/// The item is enters editing mode when this object is created and leaves editing
/// mode when the object is disposed.
/// This provides an easy to use mechanism for editing items.
/// </remarks>
[Obsolete("You should not use an edit context because if an exception is thrown partial updates may be written to the item anyway. Use Editing.BeginEdit()...Editing.EndEdit() instead.")]
public class SynthesisEditContext : EditContext
{
public SynthesisEditContext(IStandardTemplateItem item) : base(item.InnerItem)
{
}
}
#pragma warning restore 0618
}
| using Sitecore.Data.Items;
namespace Synthesis
{
#pragma warning disable 0618 // disable the warning about InnerItem here - it's cool
/// <summary>
/// Provides a means to put an item in editing mode.
/// </summary>
/// <remarks>
/// The item is enters editing mode when this object is created and leaves editing
/// mode when the object is disposed.
/// This provides an easy to use mechanism for editing items.
/// </remarks>
public class SynthesisEditContext : EditContext
{
public SynthesisEditContext(IStandardTemplateItem item) : base(item.InnerItem)
{
}
}
#pragma warning restore 0618
}
| mit | C# |
ccd23a11e1f25525384c865c06248772adaedd95 | Add optional predicate to Slash.System.FileUtils.CopyDirectory to filter the files that should be copied | SlashGames/slash-framework,SlashGames/slash-framework,SlashGames/slash-framework | Source/Slash.System/Source/Utils/FileUtils.cs | Source/Slash.System/Source/Utils/FileUtils.cs | namespace Slash.SystemExt.Utils
{
using System;
using System.IO;
public static class FileUtils
{
public static void CopyDirectory(string sourcePath, string destinationPath, Func<string, bool> predicate = null)
{
sourcePath = Path.GetFullPath(sourcePath);
destinationPath = Path.GetFullPath(destinationPath);
Directory.CreateDirectory(destinationPath);
//Now Create all of the directories
foreach (var dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));
}
//Copy all the files & Replaces any files with the same name
foreach (var newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
{
if (predicate == null || predicate(newPath))
{
File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true);
}
}
}
}
} | namespace Slash.SystemExt.Utils
{
using System.IO;
public static class FileUtils
{
public static void CopyDirectory(string sourcePath, string destinationPath)
{
sourcePath = Path.GetFullPath(sourcePath);
destinationPath = Path.GetFullPath(destinationPath);
Directory.CreateDirectory(destinationPath);
//Now Create all of the directories
foreach (var dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, destinationPath));
}
//Copy all the files & Replaces any files with the same name
foreach (var newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcePath, destinationPath), true);
}
}
}
} | mit | C# |
73c29ac36091855c94929de1756e87a9ed815241 | Update CPUReadCPUIDAsm.cs | CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos | source/Cosmos.Core_Asm/CPU/CPUReadCPUIDAsm.cs | source/Cosmos.Core_Asm/CPU/CPUReadCPUIDAsm.cs | using Cosmos.Debug.Kernel;
using XSharp;
using XSharp.Assembler;
using static XSharp.XSRegisters;
namespace Cosmos.Core_Asm
{
public class CPUReadCPUIDAsm : AssemblerMethod
{
private const int CpuIdTypeArgOffset = 4;
private const int CpuIdEAXAddressArgOffset = 8;
private const int CpuIdEBXAddressArgOffset = 12;
private const int CpuIdECXAddressArgOffset = 16;
private const int CpuIdEDXAddressArgOffset = 20;
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
XS.Comment("Load type arg");
XS.Set(EAX, EBP, sourceDisplacement: CpuIdTypeArgOffset, sourceIsIndirect: true);
XS.Cpuid();
XS.Comment("Save eax result arg");
XS.Set(EDI, EBP, sourceDisplacement: CpuIdEAXAddressArgOffset, sourceIsIndirect: true);
XS.Set(EDI, EAX, destinationIsIndirect: true);
XS.Comment("Save ebx result arg");
XS.Set(EDI, EBP, sourceDisplacement: CpuIdEBXAddressArgOffset, sourceIsIndirect: true);
XS.Set(EDI, EBX, destinationIsIndirect: true);
XS.Comment("Save ecx result arg");
XS.Set(EDI, EBP, sourceDisplacement: CpuIdECXAddressArgOffset, sourceIsIndirect: true);
XS.Set(EDI, ECX, destinationIsIndirect: true);
XS.Comment("Save edx result arg");
XS.Set(EDI, EBP, sourceDisplacement: CpuIdEDXAddressArgOffset, sourceIsIndirect: true);
XS.Set(EDI, EDX, destinationIsIndirect: true);
}
}
}
| using XSharp.Assembler;
namespace Cosmos.Core_Asm
{
public class CPUReadCPUIDAsm : AssemblerMethod
{
public override void AssembleNew(Assembler aAssembler, object aMethodInfo)
{
// TODO Get the type parameter from EBP+8 and move it to EAX
/*
* mov eax, 16h
* cpuid
*/
// TODO The result of cpuid will be in EDX:EAX so it will need to be moved to the return value
// Set ESI to EBP+8?
}
}
}
| bsd-3-clause | C# |
9c03290966f85e78a865fe75932fd14aac653a40 | Bump to v0.5.1 | dancol90/mi-360 | Source/mi-360/Properties/AssemblyInfo.cs | Source/mi-360/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Modificare i valori di questi attributi per modificare le informazioni
// associate a un assembly.
[assembly: AssemblyTitle("mi-360")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniele Colanardi")]
[assembly: AssemblyProduct("mi-360")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
[assembly: Guid("885b11ae-354c-4690-a0a5-e9a82f51f262")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Versione principale
// Versione secondaria
// Numero di build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// usando l'asterisco '*' come illustrato di seguito:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Modificare i valori di questi attributi per modificare le informazioni
// associate a un assembly.
[assembly: AssemblyTitle("mi-360")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniele Colanardi")]
[assembly: AssemblyProduct("mi-360")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
[assembly: Guid("885b11ae-354c-4690-a0a5-e9a82f51f262")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Versione principale
// Versione secondaria
// Numero di build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// usando l'asterisco '*' come illustrato di seguito:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.0")]
| bsd-3-clause | C# |
b99af5b461c017c04b2ec0acc9f9689376e4d37b | Throw more specific error if no SSL cert | MatthewSteeples/XeroAPI.Net | source/XeroApi/OAuth/XeroApiPartnerSession.cs | source/XeroApi/OAuth/XeroApiPartnerSession.cs | using System;
using System.Security.Cryptography.X509Certificates;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
using DevDefined.OAuth.Storage.Basic;
namespace XeroApi.OAuth
{
public class XeroApiPartnerSession : OAuthSession
{
[Obsolete("Use the constructor with ITokenRepository")]
public XeroApiPartnerSession(string userAgent, string consumerKey, X509Certificate2 signingCertificate, X509Certificate2 sslCertificate)
: base(CreateConsumerContext(userAgent, consumerKey, signingCertificate))
{
ConsumerRequestFactory = new DefaultConsumerRequestFactory(new SimpleCertificateFactory(sslCertificate));
}
public XeroApiPartnerSession(string userAgent, string consumerKey, X509Certificate2 signingCertificate, X509Certificate2 sslCertificate, ITokenRepository tokenRepository)
: base(CreateConsumerContext(userAgent, consumerKey, signingCertificate), tokenRepository)
{
ConsumerRequestFactory = new DefaultConsumerRequestFactory(new SimpleCertificateFactory(sslCertificate));
}
private static IOAuthConsumerContext CreateConsumerContext(string userAgent, string consumerKey, X509Certificate2 signingCertificate)
{
if (signingCertificate == null)
throw new ArgumentNullException(nameof(signingCertificate));
return new OAuthConsumerContext
{
// Public apps use HMAC-SHA1
SignatureMethod = SignatureMethod.RsaSha1,
UseHeaderForOAuthParameters = true,
// Urls
RequestTokenUri = XeroApiEndpoints.PartnerRequestTokenUri,
UserAuthorizeUri = XeroApiEndpoints.UserAuthorizeUri,
AccessTokenUri = XeroApiEndpoints.PartnerAccessTokenUri,
BaseEndpointUri = XeroApiEndpoints.PartnerBaseEndpointUri,
Key = signingCertificate.PrivateKey,
ConsumerKey = consumerKey,
ConsumerSecret = string.Empty,
UserAgent = userAgent,
};
}
}
}
| using System;
using System.Security.Cryptography.X509Certificates;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
using DevDefined.OAuth.Storage.Basic;
namespace XeroApi.OAuth
{
public class XeroApiPartnerSession : OAuthSession
{
[Obsolete("Use the constructor with ITokenRepository")]
public XeroApiPartnerSession(string userAgent, string consumerKey, X509Certificate2 signingCertificate, X509Certificate2 sslCertificate)
: base(CreateConsumerContext(userAgent, consumerKey, signingCertificate))
{
ConsumerRequestFactory = new DefaultConsumerRequestFactory(new SimpleCertificateFactory(sslCertificate));
}
public XeroApiPartnerSession(string userAgent, string consumerKey, X509Certificate2 signingCertificate, X509Certificate2 sslCertificate, ITokenRepository tokenRepository)
: base(CreateConsumerContext(userAgent, consumerKey, signingCertificate), tokenRepository)
{
ConsumerRequestFactory = new DefaultConsumerRequestFactory(new SimpleCertificateFactory(sslCertificate));
}
private static IOAuthConsumerContext CreateConsumerContext(string userAgent, string consumerKey, X509Certificate2 signingCertificate)
{
return new OAuthConsumerContext
{
// Public apps use HMAC-SHA1
SignatureMethod = SignatureMethod.RsaSha1,
UseHeaderForOAuthParameters = true,
// Urls
RequestTokenUri = XeroApiEndpoints.PartnerRequestTokenUri,
UserAuthorizeUri = XeroApiEndpoints.UserAuthorizeUri,
AccessTokenUri = XeroApiEndpoints.PartnerAccessTokenUri,
BaseEndpointUri = XeroApiEndpoints.PartnerBaseEndpointUri,
Key = signingCertificate.PrivateKey,
ConsumerKey = consumerKey,
ConsumerSecret = string.Empty,
UserAgent = userAgent,
};
}
}
}
| mit | C# |
230bd74ee55f71e0bbf592b310c89d2657efbc8b | Increment version. | jyuch/ReflectionToStringBuilder | src/ReflectionToStringBuilder/Properties/AssemblyInfo.cs | src/ReflectionToStringBuilder/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("ReflectionToStringBuilder")]
[assembly: AssemblyDescription("ReflectionでToStringするアレ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReflectionToStringBuilder")]
[assembly: AssemblyCopyright("Copyright © 2015 jyuch")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("7e1cb969-5d63-4c0f-89ec-a1d0604eba75")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("ReflectionToStringBuilder")]
[assembly: AssemblyDescription("ReflectionでToStringするアレ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReflectionToStringBuilder")]
[assembly: AssemblyCopyright("Copyright © 2015 jyuch")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("7e1cb969-5d63-4c0f-89ec-a1d0604eba75")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
| mit | C# |
487af09a76cbbad363a1c88fa0b7f09cc72bc5d3 | Create first automated acceptance test | lifebeyondfife/Decider | Tests/Acceptance/LeagueGenerationTest.cs | Tests/Acceptance/LeagueGenerationTest.cs | /*
Copyright Iain McDonald 2010-2020
This file is part of Decider.
*/
using System;
using Xunit;
using Decider.Example.LeagueGeneration;
namespace Decider.Tests.Example
{
public class LeagueGenerationTest
{
[Fact]
public void TestGenerating10()
{
var leagueGeneration = new LeagueGeneration(10);
leagueGeneration.Search();
leagueGeneration.GenerateFixtures();
Assert.Equal(10, leagueGeneration.FixtureWeeks[0][1]);
Assert.Equal(11, leagueGeneration.FixtureWeeks[0][2]);
Assert.Equal(12, leagueGeneration.FixtureWeeks[0][3]);
Assert.Equal(11, leagueGeneration.FixtureWeeks[5][6]);
Assert.Equal(12, leagueGeneration.FixtureWeeks[5][7]);
Assert.Equal(13, leagueGeneration.FixtureWeeks[5][8]);
Assert.Equal(0, leagueGeneration.State.Backtracks);
Assert.Equal(1, leagueGeneration.State.NumberOfSolutions);
}
[Fact]
public void TestGenerating20()
{
var leagueGeneration = new LeagueGeneration(20);
leagueGeneration.Search();
leagueGeneration.GenerateFixtures();
Assert.Equal(20, leagueGeneration.FixtureWeeks[0][1]);
Assert.Equal(21, leagueGeneration.FixtureWeeks[0][2]);
Assert.Equal(22, leagueGeneration.FixtureWeeks[0][3]);
Assert.Equal(30, leagueGeneration.FixtureWeeks[5][6]);
Assert.Equal(31, leagueGeneration.FixtureWeeks[5][7]);
Assert.Equal(32, leagueGeneration.FixtureWeeks[5][8]);
Assert.Equal(17, leagueGeneration.FixtureWeeks[17][0]);
Assert.Equal(18, leagueGeneration.FixtureWeeks[17][1]);
Assert.Equal(19, leagueGeneration.FixtureWeeks[17][2]);
Assert.Equal(6262, leagueGeneration.State.Backtracks);
Assert.Equal(1, leagueGeneration.State.NumberOfSolutions);
}
}
}
| /*
Copyright Iain McDonald 2010-2020
This file is part of Decider.
*/
using System;
using Xunit;
using Decider.Example.LeagueGeneration;
namespace Decider.Tests.Example
{
public class LeagueGenerationTest
{
[Fact]
public void TestGenerating10()
{
var leagueGeneration = new LeagueGeneration(10);
leagueGeneration.Search();
leagueGeneration.GenerateFixtures();
Assert.Equal(10, leagueGeneration.FixtureWeeks[0][1]);
Assert.Equal(11, leagueGeneration.FixtureWeeks[0][2]);
Assert.Equal(12, leagueGeneration.FixtureWeeks[0][3]);
Assert.Equal(11, leagueGeneration.FixtureWeeks[5][6]);
Assert.Equal(12, leagueGeneration.FixtureWeeks[5][7]);
Assert.Equal(13, leagueGeneration.FixtureWeeks[5][8]);
Assert.Equal(0, leagueGeneration.State.Backtracks);
Assert.Equal(1, leagueGeneration.State.NumberOfSolutions);
}
[Fact]
public void TestGenerating20()
{
var leagueGeneration = new LeagueGeneration(20);
leagueGeneration.Search();
leagueGeneration.GenerateFixtures();
Assert.Equal(20, leagueGeneration.FixtureWeeks[0][1]);
Assert.Equal(21, leagueGeneration.FixtureWeeks[0][2]);
Assert.Equal(22, leagueGeneration.FixtureWeeks[0][3]);
Assert.Equal(30, leagueGeneration.FixtureWeeks[5][6]);
Assert.Equal(31, leagueGeneration.FixtureWeeks[5][7]);
Assert.Equal(32, leagueGeneration.FixtureWeeks[5][8]);
Assert.Equal(17, leagueGeneration.FixtureWeeks[17][0]);
Assert.Equal(18, leagueGeneration.FixtureWeeks[17][1]);
Assert.Equal(19, leagueGeneration.FixtureWeeks[17][2]);
Assert.Equal(6262, leagueGeneration.State.Backtracks);
Assert.Equal(1, leagueGeneration.State.NumberOfSolutions);
}
}
}
| mit | C# |
2e60ba768d0c0a7feb4b5bdec18abb10e5c0dbb3 | Update EnumerableExtensions.cs | keith-hall/Extensions,keith-hall/Extensions | src/EnumerableExtensions.cs | src/EnumerableExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace HallLibrary.Extensions
{
/// <summary>
/// Contains static methods for working with enumerables.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Randomise the order of the elements in the <paramref name="source"/> enumerable.
/// </summary>
/// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam>
/// <param name="source">The enumerable containing the elements to shuffle.</param>
/// <returns>An enumerable containing the same elements but in a random order.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return Shuffle(source, new Random());
}
/// <summary>
/// Randomise the order of the elements in the <paramref name="source"/> enumerable, using the specified <paramref name="random"/> seed.
/// </summary>
/// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam>
/// <param name="source">The enumerable containing the elements to shuffle.</param>
/// <param name="random">The random seed to use.</param>
/// <returns>An enumerable containing the same elements but in a random order.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{ // http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm
var elements = source.ToArray();
for (var i = elements.Length - 1; i >= 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
// ... except we don't really need to swap it fully, as we can
// return it immediately, and afterwards it's irrelevant.
var swapIndex = random.Next(i + 1); // Random.Next maxValue is an exclusive upper-bound, which is why we add 1
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
/// <summary>
/// Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>, without enumerating through every element.
/// </summary>
/// <typeparam name="T">The type of elements in the enumerable.</typeparam>
/// <param name="enumerable">The enumerable sequence to check.</param>
/// <param name="count">The count to exceed.</param>
/// <returns>Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>.</returns>
public static bool CountExceeds<T>(this IEnumerable<T> enumerable, int count)
{
return enumerable.Take(count + 1).Count() > count;
}
/// <summary>
/// Converts the current <paramref name="value"/> to an enumerable, containing the <paramref name="value"/> as it's sole element.
/// </summary>
/// <typeparam name="T">The type of the element.</typeparam>
/// <param name="value">The value that the new enumerable will contain.</param>
/// <returns>Returns an enumerable containing a single element.</returns>
public static IEnumerable<T> AsSingleEnumerable<T>(this T value)
{
//x return Enumerable.Repeat(value, 1);
return new[] { value };
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace HallLibrary.Extensions
{
/// <summary>
/// Contains static methods for working with <see cref="IEnumerable" />s.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Randomise the order of the elements in the <paramref name="source"/> enumerable.
/// </summary>
/// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam>
/// <param name="source">The enumerable containing the elements to shuffle.</param>
/// <returns>An enumerable containing the same elements but in a random order.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return Shuffle(source, new Random());
}
/// <summary>
/// Randomise the order of the elements in the <paramref name="source"/> enumerable, using the specified <paramref name="random"/> seed.
/// </summary>
/// <typeparam name="T">The type of the elements in the <paramref name="source"/> enumerable.</typeparam>
/// <param name="source">The enumerable containing the elements to shuffle.</param>
/// <param name="random">The random seed to use.</param>
/// <returns>An enumerable containing the same elements but in a random order.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{ // http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm
var elements = source.ToArray();
for (var i = elements.Length - 1; i >= 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
// ... except we don't really need to swap it fully, as we can
// return it immediately, and afterwards it's irrelevant.
var swapIndex = random.Next(i + 1); // Random.Next maxValue is an exclusive upper-bound, which is why we add 1
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
}
}
/// <summary>
/// Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>, without enumerating through every element.
/// </summary>
/// <typeparam name="T">The type of elements in the enumerable.</typeparam>
/// <param name="enumerable">The enumerable sequence to check.</param>
/// <param name="count">The count to exceed.</param>
/// <returns>Returns <c>true</c> if the number of elements in the <paramref name="enumerable"/> exceeds the specified <paramref name="count"/>.</returns>
public static bool CountExceeds<T>(this IEnumerable<T> enumerable, int count)
{
return enumerable.Take(count + 1).Count() > count;
}
/// <summary>
/// Converts the current <paramref name="value"/> to an enumerable, containing the <paramref name="value"/> as it's sole element.
/// </summary>
/// <typeparam name="T">The type of the element.</typeparam>
/// <param name="value">The value that the new enumerable will contain.</param>
/// <returns>Returns an enumerable containing a single element.</returns>
public static IEnumerable<T> AsSingleEnumerable<T>(this T value)
{
//x return Enumerable.Repeat(value, 1);
return new[] { value };
}
}
}
| apache-2.0 | C# |
b4fd5a90c020cc9ef592d2980232742424b63088 | Add thank you text to Complete page | ParcelForMe/p4m-demo-shop,ParcelForMe/p4m-demo-shop,ParcelForMe/p4m-demo-shop,ParcelForMe/p4m-demo-shop | OpenOrderFramework/Views/Checkout/Complete.cshtml | OpenOrderFramework/Views/Checkout/Complete.cshtml | @model int
@{
ViewBag.Title = "Checkout Complete";
}
<link rel="import" href="/Scripts/widgets/p4m-ajax-block/p4m-ajax-block.html">
<p4m-ajax-block content-url="https://local.parcelfor.me:44333/Content/Thankyou/Thankyou.html"></p4m-ajax-block>
<h2>Checkout Complete</h2>
<p>Thanks for your order! Your order number is: @Model</p>
<p>
How about shopping for some more stuff in our
@Html.ActionLink("store","Index", "Home")
</p>
| @model int
@{
ViewBag.Title = "Checkout Complete";
}
<h2>Checkout Complete</h2>
<p>Thanks for your order! Your order number is: @Model</p>
<p>
How about shopping for some more stuff in our
@Html.ActionLink("store","Index", "Home")
</p>
| mit | C# |
057c66b849821fcde23e63a5ec3cc2b4cc802e0f | fix bugs in ConsoleBitmapViewer | workabyte/PowerArgs,adamabdelhamed/PowerArgs,adamabdelhamed/PowerArgs,workabyte/PowerArgs | PowerArgs/CLI/Drawing/ConsoleBitmapViewer.cs | PowerArgs/CLI/Drawing/ConsoleBitmapViewer.cs | namespace PowerArgs.Cli
{
/// <summary>
/// A control that can render a ConsoleBitmap
/// </summary>
public class ConsoleBitmapViewer : ConsoleControl
{
/// <summary>
/// The bitmap to render
/// </summary>
public ConsoleBitmap Bitmap { get => Get<ConsoleBitmap>(); set => Set(value); }
/// <summary>
/// Creates a new console bitmap viewer
/// </summary>
public ConsoleBitmapViewer()
{
this.CanFocus = false;
}
/// <summary>
/// Pains the target bitmap
/// </summary>
/// <param name="context"></param>
protected override void OnPaint(ConsoleBitmap context)
{
if (Bitmap == null) return;
for(var x = 0; x < Width && x < Bitmap.Width; x++)
{
for(var y = 0; y < Height && y < Bitmap.Height; y++)
{
var c = Bitmap.GetPixel(x, y).Value;
if(c.HasValue)
{
context.Pen = c.Value;
context.DrawPoint(x, y);
}
}
}
}
}
}
| namespace PowerArgs.Cli
{
/// <summary>
/// A control that can render a ConsoleBitmap
/// </summary>
public class ConsoleBitmapViewer : ConsoleControl
{
/// <summary>
/// The bitmap to render
/// </summary>
public ConsoleBitmap Bitmap { get; set; }
/// <summary>
/// Creates a new console bitmap viewer
/// </summary>
public ConsoleBitmapViewer()
{
this.CanFocus = false;
}
/// <summary>
/// Pains the target bitmap
/// </summary>
/// <param name="context"></param>
protected override void OnPaint(ConsoleBitmap context)
{
if (Bitmap == null) return;
for(var x = 0; x < Width && x < Bitmap.Width; x++)
{
for(var y = 0; y < Height & Y < Bitmap.Height; y++)
{
var c = Bitmap.GetPixel(x, y).Value;
if(c.HasValue)
{
context.Pen = c.Value;
context.DrawPoint(x, y);
}
}
}
}
}
}
| mit | C# |
807bb4151f9483a513ceb423738f4b0aa95573b5 | Add Debug output | MorganR/wizards-chess,MorganR/wizards-chess | WizardsChess/WizardsChess/GpioToggler.cs | WizardsChess/WizardsChess/GpioToggler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Gpio;
namespace WizardsChess
{
public sealed class GpioToggler
{
public GpioToggler(TimeSpan period, int pinNum)
{
this.period = period;
gpio = GpioController.GetDefault();
pin = gpio.OpenPin(pinNum);
}
public void Start()
{
pin.Write(GpioPinValue.High);
currentPinVal = GpioPinValue.High;
pin.SetDriveMode(GpioPinDriveMode.Output);
toggleTask = Task.Run(async () => {
while (true)
{
await Task.Delay(period);
toggle();
}
});
}
private void toggle()
{
System.Diagnostics.Debug.WriteLine("Toggling");
switch (currentPinVal)
{
case GpioPinValue.High:
pin.Write(GpioPinValue.Low);
currentPinVal = GpioPinValue.Low;
break;
case GpioPinValue.Low:
default:
pin.Write(GpioPinValue.High);
currentPinVal = GpioPinValue.High;
break;
}
}
private TimeSpan period;
private GpioPinValue currentPinVal;
private GpioPin pin;
private GpioController gpio;
private Task toggleTask;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Gpio;
namespace WizardsChess
{
public sealed class GpioToggler
{
public GpioToggler(TimeSpan period, int pinNum)
{
this.period = period;
gpio = GpioController.GetDefault();
pin = gpio.OpenPin(pinNum);
}
public void Start()
{
pin.Write(GpioPinValue.High);
currentPinVal = GpioPinValue.High;
pin.SetDriveMode(GpioPinDriveMode.Output);
toggleTask = Task.Run(async () => {
while (true)
{
await Task.Delay(period);
toggle();
}
});
}
private void toggle()
{
switch (currentPinVal)
{
case GpioPinValue.High:
pin.Write(GpioPinValue.Low);
currentPinVal = GpioPinValue.Low;
break;
case GpioPinValue.Low:
default:
pin.Write(GpioPinValue.High);
currentPinVal = GpioPinValue.High;
break;
}
}
private TimeSpan period;
private GpioPinValue currentPinVal;
private GpioPin pin;
private GpioController gpio;
private Task toggleTask;
}
}
| apache-2.0 | C# |
c983ed8092ea9deece58581f6759a9651d961aa3 | change api config | iuv-dev/routecore,iuv-dev/routecore | RouteCore/RouteCore/App_Start/WebApiConfig.cs | RouteCore/RouteCore/App_Start/WebApiConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace RouteCore
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "API/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace RouteCore
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| mit | C# |
0b9466029c96d547de28f3859482cd7344fcd773 | remove unneeded method | matrostik/SQLitePCL.pretty,bordoley/SQLitePCL.pretty | SQLitePCL.pretty.Async/InterfacesContract.cs | SQLitePCL.pretty.Async/InterfacesContract.cs | /*
Copyright 2014 David Bordoley
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace SQLitePCL.pretty
{
[ContractClassFor(typeof(IAsyncDatabaseConnection))]
internal abstract class IAsyncDatabaseConnectionContract : IAsyncDatabaseConnection
{
public abstract IObservable<DatabaseTraceEventArgs> Trace { get; }
public abstract IObservable<DatabaseProfileEventArgs> Profile { get; }
public abstract IObservable<DatabaseUpdateEventArgs> Update { get; }
public abstract void Dispose();
public abstract Task DisposeAsync();
public IObservable<T> Use<T>(Func<IDatabaseConnection, IEnumerable<T>> f)
{
Contract.Requires(f != null);
return default(IObservable<T>);
}
}
[ContractClassFor(typeof(IAsyncStatement))]
internal abstract class IAsyncStatementContract : IAsyncStatement
{
public abstract void Dispose();
public IObservable<T> Use<T>(Func<IStatement, IEnumerable<T>> f)
{
Contract.Requires(f != null);
return default(IObservable<T>);
}
}
}
| /*
Copyright 2014 David Bordoley
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace SQLitePCL.pretty
{
[ContractClassFor(typeof(IAsyncDatabaseConnection))]
internal abstract class IAsyncDatabaseConnectionContract : IAsyncDatabaseConnection
{
public abstract IObservable<DatabaseTraceEventArgs> Trace { get; }
public abstract IObservable<DatabaseProfileEventArgs> Profile { get; }
public abstract IObservable<DatabaseUpdateEventArgs> Update { get; }
public abstract void Dispose();
public abstract Task DisposeAsync();
public IObservable<T> Use<T>(Func<IDatabaseConnection, IEnumerable<T>> f)
{
Contract.Requires(f != null);
return default(IObservable<T>);
}
}
[ContractClassFor(typeof(IAsyncStatement))]
internal abstract class IAsyncStatementContract : IAsyncStatement
{
public abstract void Dispose();
public abstract Task DisposeAsync();
public IObservable<T> Use<T>(Func<IStatement, IEnumerable<T>> f)
{
Contract.Requires(f != null);
return default(IObservable<T>);
}
}
}
| apache-2.0 | C# |
a2fccb073d6aa0b636b0f4b63fae22182d91930d | Change div class and change the position of button back | Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog,Team-Code-Ninjas/SpaceBlog | SpaceBlog/SpaceBlog/Views/Comment/Edit.cshtml | SpaceBlog/SpaceBlog/Views/Comment/Edit.cshtml | @model SpaceBlog.Models.CommentViewModel
@{
ViewBag.Title = "Edit";
ViewBag.Message = "Comment";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="container">
<h2>@ViewBag.Title</h2>
<h4>@ViewBag.Message</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.ArticleId)
@Html.HiddenFor(m => m.AuthorId)
<div class="form-group">
@Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10" style="margin-top: 10px">
<input type="submit" value="Save" class="btn btn-success" />
@Html.ActionLink("Back", "Index", new { @id = ""}, new { @class = "btn btn-primary" })
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
} | @model SpaceBlog.Models.CommentViewModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Comment</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(m => m.Id)
@Html.HiddenFor(m => m.ArticleId)
@Html.HiddenFor(m => m.AuthorId)
<div class="form-group">
@Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
| mit | C# |
47c6d90db3bef9f0100b5d886b43c8711e13c448 | fix S_BOSS_GAGE_INFO field types | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TeraPacketParser/Messages/S_BOSS_GAGE_INFO.cs | TeraPacketParser/Messages/S_BOSS_GAGE_INFO.cs | namespace TeraPacketParser.Messages
{
public class S_BOSS_GAGE_INFO : ParsedMessage
{
//private ulong id, targetId;
//private int templateId, huntingZoneId;//, unk1;
//private float /*hpDiff,*/ currHp, maxHp;
//private byte enrage/*, unk3*/;
public ulong EntityId { get; }
public uint TemplateId { get; }
public uint HuntingZoneId { get; }
public float CurrentHP { get; }
public float MaxHP { get; }
public ulong Target { get; }
public bool Enrage { get; }
public S_BOSS_GAGE_INFO(TeraMessageReader reader) : base(reader)
{
EntityId = reader.ReadUInt64();
HuntingZoneId = reader.ReadUInt32();
TemplateId = reader.ReadUInt32();
Target = reader.ReadUInt64();
reader.Skip(4); //unk1 = reader.ReadInt32();
//if (reader.Version < 321550 || reader.Version > 321600)
//{
Enrage = reader.ReadBoolean();
CurrentHP = reader.ReadInt64();
MaxHP = reader.ReadInt64();
//}
//else
//{
// hpDiff = reader.ReadSingle();
// enrage = reader.ReadByte();
// currHp = reader.ReadSingle();
// maxHp = reader.ReadSingle();
//}
//unk3 = reader.ReadByte();
}
}
} | namespace TeraPacketParser.Messages
{
public class S_BOSS_GAGE_INFO : ParsedMessage
{
//private ulong id, targetId;
//private int templateId, huntingZoneId;//, unk1;
//private float /*hpDiff,*/ currHp, maxHp;
//private byte enrage/*, unk3*/;
public ulong EntityId { get; }
public int TemplateId { get; }
public int HuntingZoneId { get; }
public float CurrentHP { get; }
public float MaxHP { get; }
public ulong Target { get; }
public bool Enrage { get; }
public S_BOSS_GAGE_INFO(TeraMessageReader reader) : base(reader)
{
EntityId = reader.ReadUInt64();
HuntingZoneId = reader.ReadInt32();
TemplateId = reader.ReadInt32();
Target = reader.ReadUInt64();
reader.Skip(4); //unk1 = reader.ReadInt32();
//if (reader.Version < 321550 || reader.Version > 321600)
//{
Enrage = reader.ReadBoolean();
CurrentHP = reader.ReadInt64();
MaxHP = reader.ReadInt64();
//}
//else
//{
// hpDiff = reader.ReadSingle();
// enrage = reader.ReadByte();
// currHp = reader.ReadSingle();
// maxHp = reader.ReadSingle();
//}
//unk3 = reader.ReadByte();
}
}
} | mit | C# |
d519f13fe62047aa7d9fe93614c4426adca52031 | Ajuste no valor Maximum closes #3 | adrianocaldeira/thunder | src/main/Thunder/ComponentModel/DataAnnotations/NumberAttribute.cs | src/main/Thunder/ComponentModel/DataAnnotations/NumberAttribute.cs | using System;
using System.ComponentModel.DataAnnotations;
namespace Thunder.ComponentModel.DataAnnotations
{
/// <summary>
/// Positive number validator
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class NumberAttribute : ValidationAttribute
{
/// <summary>
/// Initialize new instance of <see cref="NumberAttribute"/>.
/// </summary>
public NumberAttribute()
{
Maximum = 9999999;
}
/// <summary>
/// Get or set minimum mumber. Default 0.
/// </summary>
public int Minimum { get; set; }
/// <summary>
/// Get or set maximum mumber. Default 999.
/// </summary>
public int Maximum { get; set; }
/// <summary>
/// Is number
/// </summary>
/// <param name="value">Value</param>
/// <returns></returns>
public override bool IsValid(object value)
{
if (value == null)
return true;
int number;
if (int.TryParse(value.ToString(), out number))
{
return (number >= Minimum && number <= Maximum);
}
return false;
}
}
}
| using System;
using System.ComponentModel.DataAnnotations;
namespace Thunder.ComponentModel.DataAnnotations
{
/// <summary>
/// Positive number validator
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class NumberAttribute : ValidationAttribute
{
/// <summary>
/// Initialize new instance of <see cref="NumberAttribute"/>.
/// </summary>
public NumberAttribute()
{
Maximum = 999;
}
/// <summary>
/// Get or set minimum mumber. Default 0.
/// </summary>
public int Minimum { get; set; }
/// <summary>
/// Get or set maximum mumber. Default 999.
/// </summary>
public int Maximum { get; set; }
/// <summary>
/// Is number
/// </summary>
/// <param name="value">Value</param>
/// <returns></returns>
public override bool IsValid(object value)
{
if (value == null)
return true;
int number;
if (int.TryParse(value.ToString(), out number))
{
return (number >= Minimum && number <= Maximum);
}
return false;
}
}
}
| mit | C# |
3ea220ebe6f6a814ef0b5fb391e2af4523fec3b6 | Add new file userAuth.cpl/Droid/Properties/AssemblyInfo.cs | ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl | userAuth.cpl/Droid/Properties/AssemblyInfo.cs | userAuth.cpl/Droid/Properties/AssemblyInfo.cs |