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 |
|---|---|---|---|---|---|---|---|---|
dd15d2daf02433c83c3ce1a6212ef27e0e91de77 | Update WalletWasabi/BitcoinCore/Monitoring/RpcFeeProvider.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/BitcoinCore/Monitoring/RpcFeeProvider.cs | WalletWasabi/BitcoinCore/Monitoring/RpcFeeProvider.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NBitcoin;
using NBitcoin.RPC;
using WalletWasabi.Bases;
using WalletWasabi.Helpers;
namespace WalletWasabi.BlockchainAnalysis.FeesEstimation
{
public class RpcFeeProvider : PeriodicRunner, IFeeProvider
{
private AllFeeEstimate _allFeeEstimate;
public AllFeeEstimate AllFeeEstimate
{
get => _allFeeEstimate;
private set => RaiseAndSetIfChanged(ref _allFeeEstimate, value);
}
public RPCClient RpcClient { get; set; }
public bool TolerateFailure { get; }
public RpcFeeProvider(TimeSpan period, RPCClient rpcClient, bool tolerateFailure) : base(period, null)
{
RpcClient = Guard.NotNull(nameof(rpcClient), rpcClient);
TolerateFailure = tolerateFailure;
}
public override async Task<object> ActionAsync(CancellationToken cancel)
{
try
{
var afs = await RpcClient.EstimateAllFeeAsync(EstimateSmartFeeMode.Conservative, true, true).ConfigureAwait(false);
AllFeeEstimate = afs;
return afs;
}
catch
{
if (TolerateFailure)
{
// Will be caught by the periodic runner.
// The point is that the result isn't changing to null, so it can still serve the latest fee it knew about.
throw;
}
else
{
// Sometimes we want to report failure so our secondary mechanisms can take over its place.
AllFeeEstimate = null;
return null;
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NBitcoin;
using NBitcoin.RPC;
using WalletWasabi.Bases;
using WalletWasabi.Helpers;
namespace WalletWasabi.BlockchainAnalysis.FeesEstimation
{
public class RpcFeeProvider : PeriodicRunner, IFeeProvider
{
private AllFeeEstimate _allFeeEstimate;
public AllFeeEstimate AllFeeEstimate
{
get => _allFeeEstimate;
private set => RaiseAndSetIfChanged(ref _allFeeEstimate, value);
}
public RPCClient RpcClient { get; set; }
public bool TolerateFailure { get; }
public RpcFeeProvider(TimeSpan period, RPCClient rpcClient, bool tolerateFailure) : base(period, null)
{
RpcClient = Guard.NotNull(nameof(rpcClient), rpcClient);
TolerateFailure = tolerateFailure;
}
public override async Task<object> ActionAsync(CancellationToken cancel)
{
try
{
var afs = await RpcClient.EstimateAllFeeAsync(EstimateSmartFeeMode.Conservative, true, true).ConfigureAwait(false);
AllFeeEstimate = afs;
return afs;
}
catch
{
if (TolerateFailure)
{
// Will be cought by the periodic runner.
// The point is that the result isn't changing to null, so it can still serve the latest fee it knew about.
throw;
}
else
{
// Sometimes we want to report failure so our secondary mechanisms can take over its place.
AllFeeEstimate = null;
return null;
}
}
}
}
}
| mit | C# |
778a78ebdfdd349da81458fbc076e612b8d8952d | Update Lab04.cs | fodrh1201/fodrh1201 | HW140327/Lab04/Lab04.cs | HW140327/Lab04/Lab04.cs | using System;
namespace next
{
public class Circle
{
public int x;
public int y;
public int r;
}
class CircleTest
{
static void Main(string[] args)
{
Circle c1, c2;
string tempstr;
c1 = new Circle();
c2 = new Circle();
Console.WriteLine("원충돌 테스트");
Console.Write("circle1 X? ");
tempstr = Console.ReadLine();
c1.x = Convert.ToInt32(tempstr);
Console.Write("circle1 Y? ");
tempstr = Console.ReadLine();
c1.y = Convert.ToInt32(tempstr);
Console.Write("circle1 R? ");
tempstr = Console.ReadLine();
c1.r = Convert.ToInt32(tempstr);
Console.Write("circle2 X? ");
tempstr = Console.ReadLine();
c2.x = Convert.ToInt32(tempstr);
Console.Write("circle2 Y? ");
tempstr = Console.ReadLine();
c2.y = Convert.ToInt32(tempstr);
Console.Write("circle2 R? ");
tempstr = Console.ReadLine();
c2.r = Convert.ToInt32(tempstr);
double d =
Math.Sqrt(Square(c1.x - c2.x) + Square(c1.y - c2.y));
if (d <= (c1.r + c2.r))
Console.WriteLine("두 원은충돌합니다.");
else
Console.WriteLine("두 원은 충돌하지 않습니다.");
}
static int Square(int n)
{
return n*n;
}
static int Abs(int n)
{
if (n >= 0)
return n;
else
return -n;
}
}
}
| using System;
namespace next
{
public class Circle
{
public int x;
public int y;
public int r;
}
class CircleTest
{
static void Main(string[] args)
{
Circle c1, c2;
string tempstr;
c1 = new Circle();
c2 = new Circle();
Console.WriteLine("원충돌 테스트");
Console.Write("circle1 X? ");
tempstr = Console.ReadLine();
c1.x = Convert.ToInt32(tempstr);
Console.Write("circle1 Y? ");
tempstr = Console.ReadLine();
c1.y = Convert.ToInt32(tempstr);
Console.Write("circle1 R? ");
tempstr = Console.ReadLine();
c1.r = Convert.ToInt32(tempstr);
Console.Write("circle2 X? ");
tempstr = Console.ReadLine();
c2.x = Convert.ToInt32(tempstr);
Console.Write("circle2 Y? ");
tempstr = Console.ReadLine();
c2.y = Convert.ToInt32(tempstr);
Console.Write("circle2 R? ");
tempstr = Console.ReadLine();
c2.r = Convert.ToInt32(tempstr);
double d =
Math.Sqrt(Square(c1.x - c2.x) + Square(c1.y - c2.y));
if (Abs(c1.r - c2.r) <= d && d <= (c1.r + c2.r)) // 선분이 닿은 경우만 충돌로 판정했습니다.
Console.WriteLine("두 원은충돌합니다.");
else
Console.WriteLine("두 원은 충돌하지 않습니다.");
}
static int Square(int n)
{
return n*n;
}
static int Abs(int n)
{
//int result;
if (n >= 0)
return n;
else
return -n;
}
}
}
| mit | C# |
8bf697bfc48966d148a79e39280634e9515c3965 | Add actor json processor | ronsanzone/ImdbKit.net | ImdbKit/ImdbClient.cs | ImdbKit/ImdbClient.cs | using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ImdbKit
{
public class ImdbClient : IImdbClient
{
public ActorSearch testJsonConnection()
{
var processor =
new ActorJsonResponseProcessor("http://www.imdb.com/xml/find?json=1&nr=1&nm=on&q=jeniffer+garner");
processor.ProcessResponse();
return processor.GetHolder() as ActorSearch;
}
}
public class ActorJsonResponseProcessor
{
private ActorSearch _actorSearchHolder;
private Uri _path;
public ActorJsonResponseProcessor(string path)
{
_path = new Uri(path);
}
protected string retrieveResponse(Uri path)
{
var retriever = new JsonResponseRetriever(path);
return retriever.RetrieveResponse();
}
public void ProcessResponse()
{
var response = retrieveResponse(_path);
_actorSearchHolder = JsonConvert.DeserializeObject<ActorSearch>(response);
}
public IJsonHolder GetHolder()
{
return _actorSearchHolder;
}
}
public class JsonResponseRetriever
{
private readonly Uri _path;
public JsonResponseRetriever(Uri path)
{
_path = path;
}
public string RetrieveResponse()
{
var client = new WebClient();
client.Headers.Add("User-Agent", "Nobody");
return client.DownloadString(_path);
}
}
public interface IJsonHolder
{
}
public class ActorSearch : IJsonHolder
{
public List<Actor> name_approx { get; set; }
}
public class Actor
{
public string id { get; set; }
public string title { get; set; }
public string name { get; set; }
public string description { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ImdbKit
{
public class ImdbClient : IImdbClient
{
public ActorSearch testJsonConnection()
{
var client = new WebClient();
client.Headers.Add("User-Agent", "Nobody");
var response =
client.DownloadString(new Uri("http://www.imdb.com/xml/find?json=1&nr=1&nm=on&q=jeniffer+garner"));
var j = JsonConvert.DeserializeObject<ActorSearch>(response);
return j;
}
}
public class ActorSearch
{
public List<Actor> name_approx { get; set; }
}
public class Actor
{
public string id { get; set; }
public string title { get; set; }
public string name { get; set; }
public string description { get; set; }
}
}
| mit | C# |
026f83024f5ddf697369e5e3e3936d66f22601b6 | Make It Rain | TheMagnificentSeven/MakeItRain | Assets/Scripts/MakeItRain.cs | Assets/Scripts/MakeItRain.cs | using UnityEngine;
using System.Collections;
public class MakeItRain : MonoBehaviour
{
private int numObjects = 20;
private float minX = -4f;
private float maxX = 4f;
private GameObject rain;
private GameObject rainClone;
// Use this for initialization
void Start()
{
// Here only for test
Rain();
}
// Update is called once per frame
void Update()
{
}
void Rain()
{
int whichRain = Random.Range(1, 4);
switch (whichRain)
{
case 1:
rain = GameObject.Find("Rain/healObj");
break;
case 2:
rain = GameObject.Find("Rain/safeObj");
break;
case 3:
rain = GameObject.Find("Rain/mediumObj");
break;
default:
rain = GameObject.Find("Rain/dangerousObj");
break;
}
for (int i = 0; i < numObjects; i++)
{
float x_rand = Random.Range(-4f, 4f);
float y_rand = Random.Range(-1f, 1f);
rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y + y_rand, rain.transform.position.z), rain.transform.rotation);
rainClone.GetComponent<Rigidbody2D>().gravityScale = 1;
}
}
}
| using UnityEngine;
using System.Collections;
public class MakeItRain : MonoBehaviour
{
private int numObjects = 10;
private float minX = -4f;
private float maxX = 4f;
private GameObject rain;
private GameObject rainClone;
// Use this for initialization
void Start()
{
// Here only for test
Rain();
}
// Update is called once per frame
void Update()
{
}
void Rain()
{
int whichRain = Random.Range(1, 4);
switch (whichRain)
{
case 1:
rain = GameObject.Find("Rain/healObj");
break;
case 2:
rain = GameObject.Find("Rain/safeObj");
break;
case 3:
rain = GameObject.Find("Rain/mediumObj");
break;
default:
rain = GameObject.Find("Rain/dangerousObj");
break;
}
float x_pos = Random.Range(minX, maxX - rain.GetComponent<BoxCollider2D>().size.x);
for (int i = 0; i < numObjects; i++)
{
rainClone = (GameObject)Instantiate(rain, new Vector3(x_pos, rain.transform.position.y, rain.transform.position.z), rain.transform.rotation);
rainClone.GetComponent<Rigidbody2D>().gravityScale = 1;
}
}
}
| mit | C# |
aeabdcf100f064f737fa8d995aeca3d7927a5142 | Make version 4 digits to fix replacement regex | badescuga/kudu,chrisrpatterson/kudu,sitereactor/kudu,EricSten-MSFT/kudu,shrimpy/kudu,mauricionr/kudu,kali786516/kudu,kenegozi/kudu,kali786516/kudu,shrimpy/kudu,bbauya/kudu,MavenRain/kudu,kenegozi/kudu,sitereactor/kudu,shibayan/kudu,juoni/kudu,badescuga/kudu,barnyp/kudu,oliver-feng/kudu,juvchan/kudu,sitereactor/kudu,juoni/kudu,barnyp/kudu,duncansmart/kudu,MavenRain/kudu,kenegozi/kudu,projectkudu/kudu,puneet-gupta/kudu,juvchan/kudu,YOTOV-LIMITED/kudu,projectkudu/kudu,uQr/kudu,puneet-gupta/kudu,juoni/kudu,duncansmart/kudu,EricSten-MSFT/kudu,EricSten-MSFT/kudu,dev-enthusiast/kudu,kali786516/kudu,barnyp/kudu,juoni/kudu,kali786516/kudu,bbauya/kudu,YOTOV-LIMITED/kudu,chrisrpatterson/kudu,juvchan/kudu,dev-enthusiast/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,puneet-gupta/kudu,badescuga/kudu,shrimpy/kudu,shrimpy/kudu,projectkudu/kudu,mauricionr/kudu,mauricionr/kudu,badescuga/kudu,uQr/kudu,EricSten-MSFT/kudu,bbauya/kudu,oliver-feng/kudu,chrisrpatterson/kudu,projectkudu/kudu,chrisrpatterson/kudu,mauricionr/kudu,dev-enthusiast/kudu,MavenRain/kudu,uQr/kudu,shibayan/kudu,MavenRain/kudu,projectkudu/kudu,bbauya/kudu,EricSten-MSFT/kudu,sitereactor/kudu,shibayan/kudu,juvchan/kudu,shibayan/kudu,barnyp/kudu,duncansmart/kudu,duncansmart/kudu,uQr/kudu,sitereactor/kudu,puneet-gupta/kudu,kenegozi/kudu,dev-enthusiast/kudu,puneet-gupta/kudu,oliver-feng/kudu,juvchan/kudu,oliver-feng/kudu,YOTOV-LIMITED/kudu,shibayan/kudu | Common/CommonAssemblyInfo.cs | Common/CommonAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")]
// If you change this version, make sure to change Build\build.proj accordingly
[assembly: AssemblyVersion("28.0.0.0")]
[assembly: AssemblyFileVersion("28.0.0.0")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Outercurve Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyConfiguration("")]
// If you change this version, make sure to change Build\build.proj accordingly
[assembly: AssemblyVersion("28.0.0")]
[assembly: AssemblyFileVersion("28.0.0")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
| apache-2.0 | C# |
24f101b7ff1688de49ee4560722eab38a1451763 | Fix Toggle button unchecking | hwthomas/xwt,lytico/xwt,akrisiun/xwt,hamekoz/xwt,cra0zy/xwt,residuum/xwt,mminns/xwt,directhex/xwt,iainx/xwt,antmicro/xwt,steffenWi/xwt,sevoku/xwt,mminns/xwt,mono/xwt,TheBrainTech/xwt | Xwt.WPF/Xwt.WPFBackend/ToggleButtonBackend.cs | Xwt.WPF/Xwt.WPFBackend/ToggleButtonBackend.cs | //
// ToggleButtonBackend.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Windows;
using Xwt.Backends;
using SWC = System.Windows.Controls;
using SWCP = System.Windows.Controls.Primitives;
namespace Xwt.WPFBackend
{
public class ToggleButtonBackend
: ButtonBackend, IToggleButtonBackend
{
public ToggleButtonBackend()
:base (new SWCP.ToggleButton())
{
}
public bool Active
{
get { return ToggleButton.IsChecked.HasValue && ToggleButton.IsChecked.Value; }
set { ToggleButton.IsChecked = value; }
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ToggleButtonEvent)
{
switch ((ToggleButtonEvent)eventId)
{
case ToggleButtonEvent.Toggled:
ToggleButton.Checked += OnButtonToggled;
ToggleButton.Unchecked += OnButtonToggled;
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ToggleButtonEvent)
{
switch ((ToggleButtonEvent)eventId)
{
case ToggleButtonEvent.Toggled:
ToggleButton.Checked -= OnButtonToggled;
ToggleButton.Unchecked -= OnButtonToggled;
break;
}
}
}
protected new IToggleButtonEventSink EventSink
{
get { return (IToggleButtonEventSink) base.EventSink; }
}
protected SWCP.ToggleButton ToggleButton
{
get { return (SWCP.ToggleButton) NativeWidget; }
}
private void OnButtonToggled (object s, RoutedEventArgs e)
{
Xwt.Engine.Toolkit.Invoke (EventSink.OnToggled);
}
}
}
| //
// ToggleButtonBackend.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Windows;
using Xwt.Backends;
using SWC = System.Windows.Controls;
using SWCP = System.Windows.Controls.Primitives;
namespace Xwt.WPFBackend
{
public class ToggleButtonBackend
: ButtonBackend, IToggleButtonBackend
{
public ToggleButtonBackend()
:base (new SWCP.ToggleButton())
{
}
public bool Active
{
get { return ToggleButton.IsChecked.HasValue && ToggleButton.IsChecked.Value; }
set { ToggleButton.IsChecked = value; }
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ToggleButtonEvent)
{
switch ((ToggleButtonEvent)eventId)
{
case ToggleButtonEvent.Toggled:
ToggleButton.Checked += OnButtonChecked;
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ToggleButtonEvent)
{
switch ((ToggleButtonEvent)eventId)
{
case ToggleButtonEvent.Toggled:
ToggleButton.Checked -= OnButtonChecked;
break;
}
}
}
protected new IToggleButtonEventSink EventSink
{
get { return (IToggleButtonEventSink) base.EventSink; }
}
protected SWCP.ToggleButton ToggleButton
{
get { return (SWCP.ToggleButton) NativeWidget; }
}
private void OnButtonChecked (object s, RoutedEventArgs e)
{
Xwt.Engine.Toolkit.Invoke (EventSink.OnToggled);
}
}
}
| mit | C# |
cd2ba19bd7a4242bf8e89d555e2994641239f142 | Change summary of server's PATCH_SEND_INFO | HelloKitty/Booma.Proxy | src/Booma.Proxy.Packets.PatchServer/Payloads/Server/PatchingInformationPayload.cs | src/Booma.Proxy.Packets.PatchServer/Payloads/Server/PatchingInformationPayload.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
//0x0C 0x00 0x11 0x00
//PatchingByteLength{4} PatchFileCount{4}
//Tethella implementation: https://github.com/justnoxx/psobb-tethealla/blob/master/patch_server/patch_server.c#L578
//Sylverant implementation: https://github.com/Sylverant/patch_server/blob/master/src/patch_packets.c#L237 and structure https://github.com/Sylverant/patch_server/blob/master/src/patch_packets.h#L106
[WireDataContract]
[PatchServerPacketPayload(PatchNetworkOperationCodes.PATCH_SEND_INFO)]
public sealed class PatchingInformationPayload : PSOBBPatchPacketPayloadServer
{
//0x0C 0x00 Size
//0x11 0x00 Type
//If there is patching information it will send
/// <summary>
/// Indicates the length and size of the patching data.
/// </summary>
[WireMember(1)]
public int PatchingByteLength { get; }
/// <summary>
/// Number of files that need to be patched.
/// </summary>
[WireMember(2)]
public int PatchFileCount { get; }
public PatchingInformationPayload(int patchingByteLength, int patchFileCount)
{
if(patchingByteLength < 0) throw new ArgumentOutOfRangeException(nameof(patchingByteLength));
if(patchFileCount < 0) throw new ArgumentOutOfRangeException(nameof(patchFileCount));
PatchingByteLength = patchingByteLength;
PatchFileCount = patchFileCount;
}
//Serializer ctor
protected PatchingInformationPayload()
: base()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
//0x0C 0x00 0x11 0x00
//PatchingByteLength{4} PatchFileCount{4}
//Tethella implementation: https://github.com/justnoxx/psobb-tethealla/blob/master/patch_server/patch_server.c#L578
//Sylverant implementation: https://github.com/Sylverant/patch_server/blob/master/src/patch_packets.c#L237 and structure https://github.com/Sylverant/patch_server/blob/master/src/patch_packets.h#L106
[WireDataContract]
[PatchServerPacketPayload(PatchNetworkOperationCodes.PATCH_SEND_INFO)]
public sealed class PatchingInformationPayload : PSOBBPatchPacketPayloadServer
{
//0x0C 0x00 Size
//0x11 0x00 Type
//If there is patching information it will send
/// <summary>
/// Indicates the length and size of the patching data.
/// </summary>
[WireMember(1)]
public int PatchingByteLength { get; }
/// <summary>
/// Not 100% sure but looks like the number of files that need to be patched.
/// </summary>
[WireMember(2)]
public int PatchFileCount { get; }
public PatchingInformationPayload(int patchingByteLength, int patchFileCount)
{
if(patchingByteLength < 0) throw new ArgumentOutOfRangeException(nameof(patchingByteLength));
if(patchFileCount < 0) throw new ArgumentOutOfRangeException(nameof(patchFileCount));
PatchingByteLength = patchingByteLength;
PatchFileCount = patchFileCount;
}
//Serializer ctor
protected PatchingInformationPayload()
: base()
{
}
}
}
| agpl-3.0 | C# |
f73142c50f841711baf3a5354a919cdbb51d97de | Remove for loop | peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu | osu.Game.Rulesets.Osu/Difficulty/Skills/Flashlight.cs | osu.Game.Rulesets.Osu/Difficulty/Skills/Flashlight.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Difficulty.Evaluators;
using osu.Game.Rulesets.Osu.Mods;
namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
/// <summary>
/// Represents the skill required to memorise and hit every object in a map with the Flashlight mod enabled.
/// </summary>
public class Flashlight : OsuStrainSkill
{
private readonly bool hasHiddenMod;
public Flashlight(Mod[] mods)
: base(mods)
{
hasHiddenMod = mods.Any(m => m is OsuModHidden);
}
private double skillMultiplier => 0.05;
private double strainDecayBase => 0.15;
protected override double DecayWeight => 1.0;
private double currentStrain;
private double strainDecay(double ms) => Math.Pow(strainDecayBase, ms / 1000);
protected override double CalculateInitialStrain(double time, DifficultyHitObject current) => currentStrain * strainDecay(time - current.Previous(0).StartTime);
protected override double StrainValueAt(DifficultyHitObject current)
{
currentStrain *= strainDecay(current.DeltaTime);
currentStrain += FlashlightEvaluator.EvaluateDifficultyOf(current, hasHiddenMod) * skillMultiplier;
return currentStrain;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Difficulty.Evaluators;
using osu.Game.Rulesets.Osu.Mods;
namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
/// <summary>
/// Represents the skill required to memorise and hit every object in a map with the Flashlight mod enabled.
/// </summary>
public class Flashlight : OsuStrainSkill
{
public Flashlight(Mod[] mods)
: base(mods)
{
}
private double skillMultiplier => 0.05;
private double strainDecayBase => 0.15;
protected override double DecayWeight => 1.0;
private double currentStrain;
private double strainDecay(double ms) => Math.Pow(strainDecayBase, ms / 1000);
protected override double CalculateInitialStrain(double time, DifficultyHitObject current) => currentStrain * strainDecay(time - current.Previous(0).StartTime);
protected override double StrainValueAt(DifficultyHitObject current)
{
currentStrain *= strainDecay(current.DeltaTime);
currentStrain += FlashlightEvaluator.EvaluateDifficultyOf(current, Mods.Any(m => m is OsuModHidden)) * skillMultiplier;
return currentStrain;
}
}
}
| mit | C# |
93029fd5482d4fec1f493bfb83f41417283dcd67 | Remove mouseWheelCheckbox from InputSettings player overlay | naoey/osu,peppy/osu,johnneijzen/osu,DrabWeb/osu,smoogipoo/osu,NeoAdonis/osu,DrabWeb/osu,ppy/osu,naoey/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,NeoAdonis/osu,2yangk23/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,2yangk23/osu,ppy/osu,ZLima12/osu,smoogipooo/osu,smoogipoo/osu,johnneijzen/osu,UselessToucan/osu,DrabWeb/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,peppy/osu,ZLima12/osu | osu.Game/Screens/Play/PlayerSettings/InputSettings.cs | osu.Game/Screens/Play/PlayerSettings/InputSettings.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;
namespace osu.Game.Screens.Play.PlayerSettings
{
public class InputSettings : PlayerSettingsGroup
{
protected override string Title => "Input settings";
private readonly PlayerCheckbox mouseButtonsCheckbox;
public InputSettings()
{
Children = new Drawable[]
{
mouseButtonsCheckbox = new PlayerCheckbox
{
LabelText = "Disable mouse buttons"
}
};
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config) => mouseButtonsCheckbox.Bindable = config.GetBindable<bool>(OsuSetting.MouseDisableButtons);
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;
namespace osu.Game.Screens.Play.PlayerSettings
{
public class InputSettings : PlayerSettingsGroup
{
protected override string Title => "Input settings";
private readonly PlayerCheckbox mouseWheelCheckbox;
private readonly PlayerCheckbox mouseButtonsCheckbox;
public InputSettings()
{
Children = new Drawable[]
{
mouseWheelCheckbox = new PlayerCheckbox
{
LabelText = "Disable mouse wheel"
},
mouseButtonsCheckbox = new PlayerCheckbox
{
LabelText = "Disable mouse buttons"
}
};
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
mouseWheelCheckbox.Bindable = config.GetBindable<bool>(OsuSetting.MouseDisableWheel);
mouseButtonsCheckbox.Bindable = config.GetBindable<bool>(OsuSetting.MouseDisableButtons);
}
}
}
| mit | C# |
86e95a64aa4cc0eaeec8b384ce515e6008c18e7a | Fix text paramater brackets not being removed | Barleytree/NitoriWare,uulltt/NitoriWare,plrusek/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare | Assets/Scripts/Helper/TextHelper.cs | Assets/Scripts/Helper/TextHelper.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Text.RegularExpressions;
public class TextHelper
{
private static Dictionary<string, string> variables;
/// <summary>
/// Gets localized text and checks for redundancies, use this for most purposes
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
public static string getLocalizedText(string key, string defaultValue)
{
if (key.StartsWith("var."))
return getVariable(key, defaultValue);
return LocalizationManager.instance == null ? defaultValue : LocalizationManager.instance.getLocalizedValue(key, defaultValue);
}
/// <summary>
/// Gets localized text with prefix "microgame.[ID]," added automatically
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string getLocalizedMicrogameText(string key, string defaultValue)
{
Scene scene = MicrogameController.instance.gameObject.scene;
return getLocalizedText("microgame." + scene.name.Substring(0, scene.name.Length - 1) + "." + key, defaultValue);
}
/// <summary>
/// Returns the text without displaying warnings when a key isn't found, for debug purpose
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string getLocalizedTextNoWarnings(string key, string defaultValue)
{
return LocalizationManager.instance == null ? defaultValue : LocalizationManager.instance.getLocalizedValueNoWarnings(key, defaultValue);
}
/// <summary>
/// Replaces all instances of text formatted {key} with their appropriate values, works with variables
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string fillInParameters(string text)
{
if (variables == null)
variables = new Dictionary<string, string>();
int tries = 100;
while (true)
{
string match = Regex.Match(text, @"\{[\w\.]+\}").ToString();
if (!string.IsNullOrEmpty(match) && tries > 0)
{
match = match.Replace("{", "").Replace("}", "");
if (match.StartsWith("var."))
text = text.Replace("{" + match + "}", getVariable(match, "(TEXT NOT FOUND)"));
else
text = text.Replace("{" + match + "}", getLocalizedText(match, "(TEXT NOT FOUND)"));
}
else
break;
tries--;
}
return text;
}
public static void setVariable(string key, string value)
{
if (variables.ContainsKey(key))
variables[key] = value;
else
variables.Add(key, value);
}
/// <summary>
/// Returns the text variable with the given key, must be set beforehand or els the default value will be returned. Can contain key parameters formatted {key}
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string getVariable(string key, string defaultValue)
{
return fillInParameters(variables.ContainsKey(key) ? variables[key] : defaultValue);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Text.RegularExpressions;
public class TextHelper
{
private static Dictionary<string, string> variables;
/// <summary>
/// Gets localized text and checks for redundancies, use this for most purposes
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
public static string getLocalizedText(string key, string defaultValue)
{
if (key.StartsWith("var."))
return getVariable(key, defaultValue);
return LocalizationManager.instance == null ? defaultValue : LocalizationManager.instance.getLocalizedValue(key, defaultValue);
}
/// <summary>
/// Gets localized text with prefix "microgame.[ID]," added automatically
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string getLocalizedMicrogameText(string key, string defaultValue)
{
Scene scene = MicrogameController.instance.gameObject.scene;
return getLocalizedText("microgame." + scene.name.Substring(0, scene.name.Length - 1) + "." + key, defaultValue);
}
/// <summary>
/// Returns the text without displaying warnings when a key isn't found, for debug purpose
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string getLocalizedTextNoWarnings(string key, string defaultValue)
{
return LocalizationManager.instance == null ? defaultValue : LocalizationManager.instance.getLocalizedValueNoWarnings(key, defaultValue);
}
/// <summary>
/// Replaces all instances of text formatted {key} with their appropriate values, works with variables
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string fillInParameters(string text)
{
if (variables == null)
variables = new Dictionary<string, string>();
int tries = 100;
while (true)
{
string match = Regex.Match(text, @"\{[\w\.]+\}").ToString();
if (!string.IsNullOrEmpty(match) && tries > 0)
{
match = match.Replace("{", "").Replace("}", "");
if (match.StartsWith("var."))
text = text.Replace(match, getVariable(match, "(TEXT NOT FOUND)"));
else
text = text.Replace(match, getLocalizedText(match, "(TEXT NOT FOUND)"));
}
else
break;
tries--;
}
return text;
}
public static void setVariable(string key, string value)
{
if (variables.ContainsKey(key))
variables[key] = value;
else
variables.Add(key, value);
}
/// <summary>
/// Returns the text variable with the given key, must be set beforehand or els the default value will be returned. Can contain key parameters formatted {key}
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static string getVariable(string key, string defaultValue)
{
return fillInParameters(variables.ContainsKey(key) ? variables[key] : defaultValue);
}
}
| mit | C# |
6d6b9e2ba6b62fe83f87c32887ee33c129da4761 | disable test not passing because of bitpay | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer.Tests/UnitTestPeusa.cs | BTCPayServer.Tests/UnitTestPeusa.cs | using NBitcoin;
using NBitcoin.DataEncoders;
using NBitpayClient;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace BTCPayServer.Tests
{
// Helper class for testing functionality and generating data needed during coding/debuging
public class UnitTestPeusa
{
// Unit test that generates temorary checkout Bitpay page
// https://forkbitpay.slack.com/archives/C7M093Z55/p1508293682000217
// Testnet of Bitpay down
//[Fact]
//public void BitpayCheckout()
//{
// var key = new Key(Encoders.Hex.DecodeData("7b70a06f35562873e3dcb46005ed0fe78e1991ad906e56adaaafa40ba861e056"));
// var url = new Uri("https://test.bitpay.com/");
// var btcpay = new Bitpay(key, url);
// var invoice = btcpay.CreateInvoice(new Invoice()
// {
// Price = 5.0,
// Currency = "USD",
// PosData = "posData",
// OrderId = "cdfd8a5f-6928-4c3b-ba9b-ddf438029e73",
// ItemDesc = "Hello from the otherside"
// }, Facade.Merchant);
// // go to invoice.Url
// Console.WriteLine(invoice.Url);
//}
// Generating Extended public key to use on http://localhost:14142/stores/{storeId}
[Fact]
public void GeneratePubkey()
{
var network = Network.RegTest;
ExtKey masterKey = new ExtKey();
Console.WriteLine("Master key : " + masterKey.ToString(network));
ExtPubKey masterPubKey = masterKey.Neuter();
ExtPubKey pubkey = masterPubKey.Derive(0);
Console.WriteLine("PubKey " + 0 + " : " + pubkey.ToString(network));
}
}
}
| using NBitcoin;
using NBitcoin.DataEncoders;
using NBitpayClient;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace BTCPayServer.Tests
{
// Helper class for testing functionality and generating data needed during coding/debuging
public class UnitTestPeusa
{
// Unit test that generates temorary checkout Bitpay page
// https://forkbitpay.slack.com/archives/C7M093Z55/p1508293682000217
[Fact]
public void BitpayCheckout()
{
var key = new Key(Encoders.Hex.DecodeData("7b70a06f35562873e3dcb46005ed0fe78e1991ad906e56adaaafa40ba861e056"));
var url = new Uri("https://test.bitpay.com/");
var btcpay = new Bitpay(key, url);
var invoice = btcpay.CreateInvoice(new Invoice()
{
Price = 5.0,
Currency = "USD",
PosData = "posData",
OrderId = "cdfd8a5f-6928-4c3b-ba9b-ddf438029e73",
ItemDesc = "Hello from the otherside"
}, Facade.Merchant);
// go to invoice.Url
Console.WriteLine(invoice.Url);
}
// Generating Extended public key to use on http://localhost:14142/stores/{storeId}
[Fact]
public void GeneratePubkey()
{
var network = Network.RegTest;
ExtKey masterKey = new ExtKey();
Console.WriteLine("Master key : " + masterKey.ToString(network));
ExtPubKey masterPubKey = masterKey.Neuter();
ExtPubKey pubkey = masterPubKey.Derive(0);
Console.WriteLine("PubKey " + 0 + " : " + pubkey.ToString(network));
}
}
}
| mit | C# |
be589ef4df09d9c5eb9072d395515ee3b0cb1dbb | Fix Xml documentation compilation warning | jorgeamado/libgit2sharp,shana/libgit2sharp,Zoxive/libgit2sharp,rcorre/libgit2sharp,dlsteuer/libgit2sharp,xoofx/libgit2sharp,OidaTiftla/libgit2sharp,red-gate/libgit2sharp,vivekpradhanC/libgit2sharp,AMSadek/libgit2sharp,ethomson/libgit2sharp,nulltoken/libgit2sharp,jorgeamado/libgit2sharp,Skybladev2/libgit2sharp,rcorre/libgit2sharp,Zoxive/libgit2sharp,whoisj/libgit2sharp,sushihangover/libgit2sharp,psawey/libgit2sharp,psawey/libgit2sharp,mono/libgit2sharp,nulltoken/libgit2sharp,dlsteuer/libgit2sharp,AMSadek/libgit2sharp,PKRoma/libgit2sharp,xoofx/libgit2sharp,red-gate/libgit2sharp,GeertvanHorrik/libgit2sharp,OidaTiftla/libgit2sharp,libgit2/libgit2sharp,sushihangover/libgit2sharp,Skybladev2/libgit2sharp,shana/libgit2sharp,github/libgit2sharp,vivekpradhanC/libgit2sharp,oliver-feng/libgit2sharp,jeffhostetler/public_libgit2sharp,jeffhostetler/public_libgit2sharp,oliver-feng/libgit2sharp,GeertvanHorrik/libgit2sharp,whoisj/libgit2sharp,mono/libgit2sharp,vorou/libgit2sharp,vorou/libgit2sharp,ethomson/libgit2sharp,jamill/libgit2sharp,AArnott/libgit2sharp,AArnott/libgit2sharp,github/libgit2sharp,jamill/libgit2sharp | LibGit2Sharp/FetchOptions.cs | LibGit2Sharp/FetchOptions.cs | using LibGit2Sharp.Handlers;
namespace LibGit2Sharp
{
/// <summary>
/// Collection of parameters controlling Fetch behavior.
/// </summary>
public sealed class FetchOptions
{
/// <summary>
/// Specifies the tag-following behavior of the fetch operation.
/// <para>
/// If not set, the fetch operation will follow the default behavior for the <see cref="Remote"/>
/// based on the remote's <see cref="Remote.TagFetchMode"/> configuration.
/// </para>
/// <para>If neither this property nor the remote `tagopt` configuration is set,
/// this will default to <see cref="F:TagFetchMode.Auto"/> (i.e. tags that point to objects
/// retrieved during this fetch will be retrieved as well).</para>
/// </summary>
public TagFetchMode? TagFetchMode { get; set; }
/// <summary>
/// Delegate that progress updates of the network transfer portion of fetch
/// will be reported through.
/// </summary>
public ProgressHandler OnProgress { get; set; }
/// <summary>
/// Delegate that updates of remote tracking branches will be reported through.
/// </summary>
public UpdateTipsHandler OnUpdateTips { get; set; }
/// <summary>
/// Callback method that transfer progress will be reported through.
/// <para>
/// Reports the client's state regarding the received and processed (bytes, objects) from the server.
/// </para>
/// </summary>
public TransferProgressHandler OnTransferProgress { get; set; }
/// <summary>
/// Credentials to use for username/password authentication.
/// </summary>
public Credentials Credentials { get; set; }
}
}
| using LibGit2Sharp.Handlers;
namespace LibGit2Sharp
{
/// <summary>
/// Collection of parameters controlling Fetch behavior.
/// </summary>
public sealed class FetchOptions
{
/// <summary>
/// Specifies the tag-following behavior of the fetch operation.
/// <para>
/// If not set, the fetch operation will follow the default behavior for the <see cref="Remote"/>
/// based on the remote's <see cref="Remote.TagFetchMode"/> configuration.
/// </para>
/// <para>If neither this property nor the remote `tagopt` configuration is set,
/// this will default to <see cref="TagFetchMode.Auto"/> (i.e. tags that point to objects
/// retrieved during this fetch will be retrieved as well).</para>
/// </summary>
public TagFetchMode? TagFetchMode { get; set; }
/// <summary>
/// Delegate that progress updates of the network transfer portion of fetch
/// will be reported through.
/// </summary>
public ProgressHandler OnProgress { get; set; }
/// <summary>
/// Delegate that updates of remote tracking branches will be reported through.
/// </summary>
public UpdateTipsHandler OnUpdateTips { get; set; }
/// <summary>
/// Callback method that transfer progress will be reported through.
/// <para>
/// Reports the client's state regarding the received and processed (bytes, objects) from the server.
/// </para>
/// </summary>
public TransferProgressHandler OnTransferProgress { get; set; }
/// <summary>
/// Credentials to use for username/password authentication.
/// </summary>
public Credentials Credentials { get; set; }
}
}
| mit | C# |
54363cc27bb1e1354627e71ba6a61468f9579176 | Update to beta1 for next release | bungeemonkee/Configgy | Configgy/Properties/AssemblyInfo.cs | Configgy/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Configgy")]
[assembly: AssemblyDescription("Configgy: Configuration library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("David Love")]
[assembly: AssemblyProduct("Configgy")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values.
// We will increase these values in the following way:
// Major Version : Increased when there is a release that breaks a public api
// Minor Version : Increased for each non-api-breaking release
// Build Number : 0 for alpha versions, 1 for beta versions, 3 for release candidates, 4 for releases
// Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number
[assembly: AssemblyVersion("1.0.1.1")]
[assembly: AssemblyFileVersion("1.0.1.1")]
// This version number will roughly follow semantic versioning : http://semver.org
// The first three numbers will always match the first the numbers of the version above.
[assembly: AssemblyInformationalVersion("1.0.1-beta1")]
| using System.Resources;
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Configgy")]
[assembly: AssemblyDescription("Configgy: Configuration library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("David Love")]
[assembly: AssemblyProduct("Configgy")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values.
// We will increase these values in the following way:
// Major Version : Increased when there is a release that breaks a public api
// Minor Version : Increased for each non-api-breaking release
// Build Number : 0 for alpha versions, 1 for beta versions, 3 for release candidates, 4 for releases
// Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
// This version number will roughly follow semantic versioning : http://semver.org
// The first three numbers will always match the first the numbers of the version above.
[assembly: AssemblyInformationalVersion("1.0.0-alpha1")]
| mit | C# |
ff030eef43255a425233ca256bcac9876c9a5dd9 | Update tests. | willegetz/NoTPK.APIWrapper.ObsidianPortal | NoTPK.APIWrapper.ObsidianPortal/APIWrapper.ObsidianPortal.Tests/API_Users_Tests.cs | NoTPK.APIWrapper.ObsidianPortal/APIWrapper.ObsidianPortal.Tests/API_Users_Tests.cs | using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NoTPK.APIWrapper.ObsidianPortal;
using APIWrapper.ObsidianPortal.Tests.Support;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ApprovalTests.Reporters;
using ApprovalTests;
namespace APIWrapper.ObsidianPortal.Tests
{
[TestClass]
[UseReporter(typeof(DiffReporter))]
public class API_Users_Tests
{
private static string _appId = "";
private static string _appSecret = "";
private static string _token = "";
private static string _tokenSecret = "";
private static XElement _testVariables;
[ClassInitialize]
public static void LoadConstants(TestContext testContext)
{
var configPath = Path.GetFullPath(@"..\..\..\..\..\..\Configs\NoTPK.APIWrapper.ObsidianPortal.Tests.Config.xml");
var configDoc = XDocument.Load(configPath);
var tokens = (from t in configDoc.Descendants("TestTokens") select t).FirstOrDefault();
if (tokens != null)
{
_appId = (string)tokens.Element("AppId");
_appSecret = (string)tokens.Element("AppSecret");
_token = (string)tokens.Element("AccessToken");
_tokenSecret = (string)tokens.Element("AccessTokenSecret");
}
_testVariables = (from v in configDoc.Descendants("TestVariables") select v).FirstOrDefault();
}
[TestMethod]
[Ignore] // Timestamp is created for "updated_at" value whenever a get request is made.
public void Test_Users_Show__LoggedInUser()
{
var result = API_Users.ShowMe(_appId, _appSecret, _token, _tokenSecret).Result;
Approvals.Verify(result);
}
[TestMethod]
public void Test_Users_Show__ById()
{
var userId = (string)_testVariables.Element("UserId");
var result = API_Users.ShowById(_appId, _appSecret, _token, _tokenSecret, userId).Result;
Approvals.Verify(result);
}
[TestMethod]
public void Test_Users_Show__ByName()
{
var userName = (string)_testVariables.Element("UserName");
var result = API_Users.ShowByName(_appId, _appSecret, _token, _tokenSecret, userName).Result;
Approvals.Verify(result);
}
}
}
| using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NoTPK.APIWrapper.ObsidianPortal;
using APIWrapper.ObsidianPortal.Tests.Support;
namespace APIWrapper.ObsidianPortal.Tests
{
[TestClass]
public class API_Users_Tests
{
private static string _appId = "";
private static string _appSecret = "";
private static string _token = "";
private static string _tokenSecret = "";
private static XElement _testVariables;
[ClassInitialize]
public static void LoadConstants(TestContext testContext)
{
var configPath = Path.GetFullPath(@"..\..\..\..\..\..\Configs\NoTPK.APIWrapper.ObsidianPortal.Tests.Config.xml");
var configDoc = XDocument.Load(configPath);
var tokens = (from t in configDoc.Descendants("TestTokens") select t).FirstOrDefault();
if (tokens != null)
{
_appId = (string) tokens.Element("AppId");
_appSecret = (string)tokens.Element("AppSecret");
_token = (string)tokens.Element("AccessToken");
_tokenSecret = (string)tokens.Element("AccessTokenSecret");
}
_testVariables = (from v in configDoc.Descendants("TestVariables") select v).FirstOrDefault();
}
[TestMethod]
[Ignore] // Timestamp is created for "updated_at" value whenever a get request is made.
public async Task Test_Users_Show__LoggedInUser()
{
var approved = Helpers.GetApprovedResults("Show_LoggedInUser");
var result = await API_Users.ShowMe(_appId, _appSecret, _token, _tokenSecret);
Assert.AreEqual(approved, result);
}
[TestMethod]
public async Task Test_Users_Show__ById()
{
var approved = Helpers.GetApprovedResults("Show_UserById");
var userId = (string) _testVariables.Element("UserId");
var result = await API_Users.ShowById(_appId, _appSecret, _token, _tokenSecret, userId);
Assert.AreEqual(approved, result);
}
[TestMethod]
public async Task Test_Users_Show__ByName()
{
var approved = Helpers.GetApprovedResults("Show_UserName");
var userName = (string) _testVariables.Element("UserName");
var result = await API_Users.ShowByName(_appId, _appSecret, _token, _tokenSecret, userName);
Assert.AreEqual(approved, result);
}
}
}
| apache-2.0 | C# |
a617eeed997ca9568c6ff90a90ccf09eeebc3544 | 重构102 | robertoye/CodeGenerator | OraMetaData/SourceUtility.cs | OraMetaData/SourceUtility.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Oracle.DataAccess.Client;
namespace OraMetaData
{
public class SourceUtility
{
public static DataTable GetTableDefinition(string strConn, string strFilter)
{
using (OracleConnection ocn = new OracleConnection(strConn))
{
ocn.Open();
string sqlFMT = @"SELECT * FROM DEPT
{0} {1}
ORDER BY DEPTNO";
string sql = string.Format(sqlFMT, string.IsNullOrEmpty(strFilter) ? "" : "WHERE",
string.IsNullOrEmpty(strFilter) ? "" : strFilter);
OracleCommand ocmd = new OracleCommand(sql, ocn);
DataSet ds = new DataSet();
OracleDataAdapter adapter = new OracleDataAdapter(ocmd);
adapter.Fill(ds);
return ds.Tables[0];
}
}
/// <summary>
///
/// </summary>
/// <param name="strConn"></param>
/// <param name="pName"></param>
/// <param name="prs"></param>
/// <returns></returns>
public static DataSet GetDataSet(string strConn, string pName,OracleParameterCollection prs)
{
using (OracleConnection ocn = new OracleConnection(strConn))
{
ocn.Open();
OracleCommand ocmd = new OracleCommand(pName, ocn);
ocmd.CommandType = CommandType.StoredProcedure;
OracleParameter pra = new OracleParameter();
ocmd.Parameters.Add(par);
DataSet ds = new DataSet();
OracleDataAdapter adapter = new OracleDataAdapter(ocmd);
adapter.Fill(ds);
return ds;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Oracle.DataAccess.Client;
namespace OraMetaData
{
public class SourceUtility
{
public static DataTable GetTableDefinition(string strConn, string strFilter)
{
using (OracleConnection ocn = new OracleConnection(strConn))
{
ocn.Open();
string sqlFMT = @"SELECT * FROM DEPT
{0} {1}
ORDER BY DEPTNO";
string sql = string.Format(sqlFMT, string.IsNullOrEmpty(strFilter) ? "" : "WHERE",
string.IsNullOrEmpty(strFilter) ? "" : strFilter);
OracleCommand ocmd = new OracleCommand(sql, ocn);
DataSet ds = new DataSet();
OracleDataAdapter adapter = new OracleDataAdapter(ocmd);
adapter.Fill(ds);
return ds.Tables[0];
}
}
/// <summary>
///
/// </summary>
/// <param name="strConn"></param>
/// <param name="pName"></param>
/// <param name="prs"></param>
/// <returns></returns>
public static DataSet GetDataSet(string strConn, string pName,OracleParameterCollection prs)
{
using (OracleConnection ocn = new OracleConnection(strConn))
{
ocn.Open();
OracleCommand ocmd = new OracleCommand(pName, ocn);
ocmd.CommandType = CommandType.StoredProcedure;
OracleParameter pra = new OracleParameter();
ocmd.Parameters.Add(par);
DataSet ds = new DataSet();
OracleDataAdapter adapter = new OracleDataAdapter(ocmd);
adapter.Fill(ds);
return ds;
}
}
}
}
| unlicense | C# |
ec28cca51481b208c44e3b6629690465219fa7cd | Bump version to 15.0.4.33402 | HearthSim/HearthDb | HearthDb/Properties/AssemblyInfo.cs | HearthDb/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2019")]
[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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("15.0.4.33402")]
[assembly: AssemblyFileVersion("15.0.4.33402")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HearthDb")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HearthSim")]
[assembly: AssemblyProduct("HearthDb")]
[assembly: AssemblyCopyright("Copyright © HearthSim 2019")]
[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("7ed14243-e02b-4b94-af00-a67a62c282f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("15.0.0.32708")]
[assembly: AssemblyFileVersion("15.0.0.32708")]
| mit | C# |
870f25a658d46e08a56fff49fcd0444928a1dc12 | Fix ExceptionMessageFormat Typo (#523) | paulcbetts/splat | src/Splat/Logging/ConsoleLogger.cs | src/Splat/Logging/ConsoleLogger.cs | // Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System;
using System.ComponentModel;
using System.Globalization;
namespace Splat
{
/// <summary>
/// A logger which will send messages to the console.
/// </summary>
public class ConsoleLogger : ILogger
{
/// <summary>
/// Gets or sets the exception message format.
/// First parameter will be the message, second will be the exception.
/// </summary>
public string ExceptionMessageFormat { get; set; } = "{0} - {1}";
/// <inheritdoc />
public LogLevel Level { get; set; }
/// <inheritdoc />
public void Write([Localizable(false)] string message, LogLevel logLevel)
{
if ((int)logLevel < (int)Level)
{
return;
}
Console.WriteLine(message);
}
/// <inheritdoc />
public void Write(Exception exception, [Localizable(false)] string message, LogLevel logLevel)
{
if ((int)logLevel < (int)Level)
{
return;
}
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, ExceptionMessageFormat, message, exception));
}
/// <inheritdoc />
public void Write([Localizable(false)] string message, [Localizable(false)] Type type, LogLevel logLevel)
{
if ((int)logLevel < (int)Level)
{
return;
}
Console.WriteLine(message);
}
/// <inheritdoc />
public void Write(Exception exception, [Localizable(false)] string message, [Localizable(false)] Type type, LogLevel logLevel)
{
if ((int)logLevel < (int)Level)
{
return;
}
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, ExceptionMessageFormat, message, exception));
}
}
}
| // Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System;
using System.ComponentModel;
using System.Globalization;
namespace Splat
{
/// <summary>
/// A logger which will send messages to the console.
/// </summary>
public class ConsoleLogger : ILogger
{
/// <summary>
/// Gets or sets the exception message format.
/// First parameter will be the message, second will be the exception.
/// </summary>
public string ExceptionMessageFormat { get; set; } = "{0] - {1}";
/// <inheritdoc />
public LogLevel Level { get; set; }
/// <inheritdoc />
public void Write([Localizable(false)] string message, LogLevel logLevel)
{
if ((int)logLevel < (int)Level)
{
return;
}
Console.WriteLine(message);
}
/// <inheritdoc />
public void Write(Exception exception, [Localizable(false)] string message, LogLevel logLevel)
{
if ((int)logLevel < (int)Level)
{
return;
}
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, ExceptionMessageFormat, message, exception));
}
/// <inheritdoc />
public void Write([Localizable(false)] string message, [Localizable(false)] Type type, LogLevel logLevel)
{
if ((int)logLevel < (int)Level)
{
return;
}
Console.WriteLine(message);
}
/// <inheritdoc />
public void Write(Exception exception, [Localizable(false)] string message, [Localizable(false)] Type type, LogLevel logLevel)
{
if ((int)logLevel < (int)Level)
{
return;
}
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, ExceptionMessageFormat, message, exception));
}
}
}
| mit | C# |
d27ada8d05e604289c5d708615f68ee329dabbfa | Throw exception when service is not registered. | BraventIT/LiteMVVMForms | LiteMVVMForms/LiteServiceLocator.cs | LiteMVVMForms/LiteServiceLocator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteMVVMForms
{
public class LiteServiceLocator
{
private static LiteServiceLocator instance;
private LiteServiceLocator()
{
services = new Dictionary<Type, object>();
}
public static LiteServiceLocator Current
{
get { return instance ?? (instance = new LiteServiceLocator()); }
}
/// <summary>
/// List of services
/// </summary>
private readonly Dictionary<Type, object> services;
/// <summary>
/// Gets the first available service
/// </summary>
/// <typeparam name="T">Type of service to get</typeparam>
/// <returns>First available service if there are any, otherwise null</returns>
public T Get<T>() where T : class
{
object service = null;
if (services.TryGetValue(typeof(T), out service))
return service as T;
throw new NotImplementedException($"Implementation not register for this Interface: {typeof(T).Name}");
}
/// <summary>
/// Registers a service provider
/// </summary>
/// <typeparam name="T">Type of the service</typeparam>
/// <param name="service">Service provider</param>
public LiteServiceLocator Register<T>(T service) where T : class
{
var type = typeof(T);
if (this.services.ContainsKey(type))
{
this.services.Remove(type);
}
this.services.Add(type, service);
return this;
}
public LiteServiceLocator Register<T, TImpl>()
where T : class
where TImpl : class, T
{
var service = Activator.CreateInstance(typeof(TImpl)) as T;
return Register<T>(service);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteMVVMForms
{
public class LiteServiceLocator
{
private static LiteServiceLocator instance;
private LiteServiceLocator()
{
services = new Dictionary<Type, object>();
}
public static LiteServiceLocator Current
{
get { return instance ?? (instance = new LiteServiceLocator()); }
}
/// <summary>
/// List of services
/// </summary>
private readonly Dictionary<Type, object> services;
/// <summary>
/// Gets the first available service
/// </summary>
/// <typeparam name="T">Type of service to get</typeparam>
/// <returns>First available service if there are any, otherwise null</returns>
public T Get<T>() where T : class
{
object service = null;
if (services.TryGetValue(typeof(T), out service))
return service as T;
return default(T);
}
/// <summary>
/// Registers a service provider
/// </summary>
/// <typeparam name="T">Type of the service</typeparam>
/// <param name="service">Service provider</param>
public LiteServiceLocator Register<T>(T service) where T : class
{
var type = typeof(T);
if (this.services.ContainsKey(type))
{
this.services.Remove(type);
}
this.services.Add(type, service);
return this;
}
public LiteServiceLocator Register<T, TImpl>()
where T : class
where TImpl : class, T
{
var service = Activator.CreateInstance(typeof(TImpl)) as T;
return Register<T>(service);
}
}
}
| mit | C# |
02b02e0dd57c7e188f046e7a5c50801c67ded2a3 | Update example | 0xd4d/dnlib | Examples/Example5.cs | Examples/Example5.cs | using System;
using System.IO;
using dnlib.DotNet;
using dnlib.PE;
using dnlib.IO;
namespace dnlib.Examples {
/// <summary>
/// Dumps all PE sections to disk
/// </summary>
public class Example5 {
public static void Run() {
string sectionFileName = @"c:\section{0}.bin";
// Open the current mscorlib
var mod = ModuleDefMD.Load(typeof(int).Module);
// Get PE image interface
var peImage = mod.Metadata.PEImage;
// Print some info
Console.WriteLine("Machine: {0}", peImage.ImageNTHeaders.FileHeader.Machine);
Console.WriteLine("Characteristics: {0}", peImage.ImageNTHeaders.FileHeader.Characteristics);
Console.WriteLine("Dumping all sections");
for (int i = 0; i < peImage.ImageSectionHeaders.Count; i++) {
var section = peImage.ImageSectionHeaders[i];
// Create a reader for the whole section
var reader = peImage.CreateReader(section.VirtualAddress, section.SizeOfRawData);
// Write the data to disk
var fileName = string.Format(sectionFileName, i);
Console.WriteLine("Dumping section {0} to file {1}", section.DisplayName, fileName);
File.WriteAllBytes(fileName, reader.ToArray());
}
}
}
}
| using System;
using System.IO;
using dnlib.DotNet;
using dnlib.PE;
using dnlib.IO;
namespace dnlib.Examples {
/// <summary>
/// Dumps all PE sections to disk
/// </summary>
public class Example5 {
public static void Run() {
string sectionFileName = @"c:\section{0}.bin";
// Open the current mscorlib
var mod = ModuleDefMD.Load(typeof(int).Module);
// Get PE image interface
var peImage = mod.Metadata.PEImage;
// Print some info
Console.WriteLine("Machine: {0}", peImage.ImageNTHeaders.FileHeader.Machine);
Console.WriteLine("Characteristics: {0}", peImage.ImageNTHeaders.FileHeader.Characteristics);
Console.WriteLine("Dumping all sections");
for (int i = 0; i < peImage.ImageSectionHeaders.Count; i++) {
var section = peImage.ImageSectionHeaders[i];
// Create a stream for the whole section
var stream = peImage.CreateStream(section.VirtualAddress, section.SizeOfRawData);
// Write the data to disk
var fileName = string.Format(sectionFileName, i);
Console.WriteLine("Dumping section {0} to file {1}", section.DisplayName, fileName);
File.WriteAllBytes(fileName, stream.ReadAllBytes());
}
}
}
}
| mit | C# |
51f74864340f82d6a7382532a9fd524409b523ba | Add (0, 0) constructoro to NotifyingPoint to avoid empty Point exception | charlenni/Mapsui,pauldendulk/Mapsui,charlenni/Mapsui | Mapsui/Geometries/NotifyingPoint.cs | Mapsui/Geometries/NotifyingPoint.cs | using System.ComponentModel;
namespace Mapsui.Geometries
{
class NotifyingPoint : Point, INotifyPropertyChanged
{
public NotifyingPoint() : base(0, 0) // Initialize with 0, 0 because otherwise is EMPTY and will throw when accessed.
{}
public new double X
{
get { return base.X; }
set
{
base.X = value;
OnPropertyChanged("X");
}
}
public new double Y
{
get { return base.Y; }
set
{
base.Y = value;
OnPropertyChanged("Y");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Checks whether this instance is spatially equal to the Point 'o'
/// </summary>
/// <param name="p">Point to compare to</param>
/// <returns></returns>
public override bool Equals(Point p)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
return (p != null) && (p.X == X) && (p.Y == Y) && (IsEmpty() == p.IsEmpty());
// ReSharper restore CompareOfFloatsByEqualityOperator
}
}
} | using System.ComponentModel;
namespace Mapsui.Geometries
{
class NotifyingPoint : Point, INotifyPropertyChanged
{
public new double X
{
get { return base.X; }
set
{
base.X = value;
OnPropertyChanged("X");
}
}
public new double Y
{
get { return base.Y; }
set
{
base.Y = value;
OnPropertyChanged("Y");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Checks whether this instance is spatially equal to the Point 'o'
/// </summary>
/// <param name="p">Point to compare to</param>
/// <returns></returns>
public override bool Equals(Point p)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
return (p != null) && (p.X == X) && (p.Y == Y) && (IsEmpty() == p.IsEmpty());
// ReSharper restore CompareOfFloatsByEqualityOperator
}
}
} | mit | C# |
95ec24a15ebc91fdb79f1d9acd22cfa1a2b1e273 | Improve mouse grabbing on unpause in Spider | uulltt/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare | Assets/Resources/Microgames/Spider/Scripts/SpiderFood.cs | Assets/Resources/Microgames/Spider/Scripts/SpiderFood.cs | using UnityEngine;
using System.Collections;
public class SpiderFood : MonoBehaviour
{
public float grabRadius;
public float initialScale;
public bool grabbed, eaten;
public float particleRate;
public float y;
private SpriteRenderer spriteRenderer;
private ParticleSystem particles;
void Awake ()
{
particles = GetComponent<ParticleSystem>();
particleRate = ParticleHelper.getEmissionRate(particles);
spriteRenderer = GetComponent<SpriteRenderer>();
ParticleHelper.setEmissionRate(particles, 0f);
}
void Update ()
{
Vector3 cursorPosition = CameraHelper.getCursorPosition();
if (!eaten)
{
spriteRenderer.color = Color.white;
if (!grabbed)
{
float distance = ((Vector2)(transform.position - cursorPosition)).magnitude;
if (distance <= grabRadius && Input.GetMouseButtonDown(0))
grabbed = true;
float scale = (1f + (Mathf.Sin(Time.time * 8f) / 5f)) * initialScale;
transform.localScale = new Vector3(scale, scale, 1f);
}
else
{
transform.localScale = Vector3.one * initialScale;
if (!Input.GetMouseButton(0))
grabbed = false;
else
transform.position = new Vector3(cursorPosition.x, cursorPosition.y, transform.position.z);
}
}
else
{
spriteRenderer.color = Color.clear;
if (Random.Range(0f, 1f) <= .55f)
particles.startColor = new Color(1f, .75f, .8f);
else
particles.startColor = new Color(.08f, .025f, 0f);
}
}
}
| using UnityEngine;
using System.Collections;
public class SpiderFood : MonoBehaviour
{
public float grabRadius;
public float initialScale;
public bool grabbed, eaten;
public float particleRate;
public float y;
private SpriteRenderer spriteRenderer;
private ParticleSystem particles;
void Awake ()
{
particles = GetComponent<ParticleSystem>();
particleRate = ParticleHelper.getEmissionRate(particles);
spriteRenderer = GetComponent<SpriteRenderer>();
ParticleHelper.setEmissionRate(particles, 0f);
}
void Update ()
{
Vector3 cursorPosition = CameraHelper.getCursorPosition();
if (!eaten)
{
spriteRenderer.color = Color.white;
if (!grabbed)
{
float distance = ((Vector2)(transform.position - cursorPosition)).magnitude;
if (distance <= grabRadius && Input.GetMouseButtonDown(0))
grabbed = true;
float scale = (1f + (Mathf.Sin(Time.time * 8f) / 5f)) * initialScale;
transform.localScale = new Vector3(scale, scale, 1f);
}
else
{
transform.position = new Vector3(cursorPosition.x, cursorPosition.y, transform.position.z);
transform.localScale = Vector3.one * initialScale;
if (!Input.GetMouseButton(0))
grabbed = false;
}
}
else
{
spriteRenderer.color = Color.clear;
if (Random.Range(0f, 1f) <= .55f)
particles.startColor = new Color(1f, .75f, .8f);
else
particles.startColor = new Color(.08f, .025f, 0f);
}
}
}
| mit | C# |
8b294583842a67805f609cc1605153f917e81203 | Add StayInParentBorder functionality. | Ring-r/GridGraphics | GridGraphics/Grid.cs | GridGraphics/Grid.cs | using System;
using System.Drawing;
namespace GridGraphics
{
class Grid
{
public readonly Anchor AnchorX = new Anchor();
public readonly Anchor AnchorY = new Anchor();
public readonly AnchorGrid AnchorGridX = new AnchorGrid();
public readonly AnchorGrid AnchorGridY = new AnchorGrid();
public Grid()
{
AnchorGridX.SetCount(10, true);
AnchorGridY.SetCount(10, true);
}
public void MoveToCenter()
{
AnchorX.Coef = 0.5f;
AnchorY.Coef = 0.5f;
AnchorGridX.Coef = 0.5f;
AnchorGridY.Coef = 0.5f;
}
public void ScaleToFit()
{
if (AnchorGridX.Count == 0 || AnchorGridY.Count == 0)
return;
var step = Math.Min(AnchorX.Size / AnchorGridX.Count, AnchorY.Size / AnchorGridY.Count);
AnchorGridX.Step = step;
AnchorGridY.Step = step;
}
private readonly Pen pen = Pens.Black;
public void Draw(Graphics graphics)
{
// TODO: Find correct start value closed to min.
var minX = AnchorX.Shift - AnchorGridX.Shift;
minX = StayInBorder(minX, AnchorX.Size - AnchorGridX.Size);
var maxX = minX + AnchorGridX.Size;
var minY = AnchorY.Shift - AnchorGridY.Shift;
minY = StayInBorder(minY, AnchorY.Size - AnchorGridY.Size);
var maxY = minY + AnchorGridY.Size;
var stepX = AnchorGridX.Step;
var stepY = AnchorGridY.Step;
for (var x = minX; x < maxX - stepX / 2; x += stepX)
{
for (var y = minY; y < maxY - stepY / 2; y += stepY)
graphics.DrawRectangle(pen, x, y, stepX, stepY);
}
}
private static float StayInBorder(float value, float size)
{
if (size < 0)
throw new ArgumentOutOfRangeException();
return Math.Min(Math.Max(0, value), size);
}
}
}
| using System;
using System.Drawing;
namespace GridGraphics
{
class Grid
{
public readonly Anchor AnchorX = new Anchor();
public readonly Anchor AnchorY = new Anchor();
public readonly AnchorGrid AnchorGridX = new AnchorGrid();
public readonly AnchorGrid AnchorGridY = new AnchorGrid();
public Grid()
{
AnchorGridX.SetCount(10, true);
AnchorGridY.SetCount(10, true);
}
public void MoveToCenter()
{
AnchorX.Coef = 0.5f;
AnchorY.Coef = 0.5f;
AnchorGridX.Coef = 0.5f;
AnchorGridY.Coef = 0.5f;
}
public void ScaleToFit()
{
if (AnchorGridX.Count == 0 || AnchorGridY.Count == 0)
return;
var step = Math.Min(AnchorX.Size / AnchorGridX.Count, AnchorY.Size / AnchorGridY.Count);
AnchorGridX.Step = step;
AnchorGridY.Step = step;
}
private readonly Pen pen = Pens.Black;
public void Draw(Graphics graphics)
{
// TODO: Find correct start value closed to min.
var minX = AnchorX.Shift - AnchorGridX.Shift;
var maxX = minX + AnchorGridX.Size;
var minY = AnchorY.Shift - AnchorGridY.Shift;
var maxY = minY + AnchorGridY.Size;
var stepX = AnchorGridX.Step;
var stepY = AnchorGridY.Step;
for (var x = minX; x < maxX - stepX / 2; x += stepX)
{
for (var y = minY; y < maxY - stepY / 2; y += stepY)
graphics.DrawRectangle(pen, x, y, stepX, stepY);
}
}
}
}
| unlicense | C# |
ef2624f37e95b9b12262c38672071a5d0dbed58f | Add new file userAuth.cpl/Droid/MainActivity.cs | ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl | userAuth.cpl/Droid/MainActivity.cs | userAuth.cpl/Droid/MainActivity.cs | �
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace userAuth.cpl.Droid
{
[Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new App ());
// Create your apponlication here
}
}
}
| �
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace userAuth.cpl.Droid
{
[Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new App ());
// Create your apponlication here
}
}
}
| mit | C# |
6fffe3075e48c696c1dabf53090a4bea2bdfb6aa | Add xmldoc to `SetImage` | ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework | osu.Framework/Platform/Clipboard.cs | osu.Framework/Platform/Clipboard.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using SixLabors.ImageSharp;
namespace osu.Framework.Platform
{
public abstract class Clipboard
{
public abstract string GetText();
public abstract void SetText(string selectedText);
/// <summary>
/// Copy the image to the clipboard.
/// </summary>
/// <remarks>
/// Currently only supported on Windows.
/// </remarks>
/// <param name="image">The image to copy to the clipboard</param>
/// <returns>Whether the image was successfully copied or not</returns>
public abstract bool SetImage(Image image);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using SixLabors.ImageSharp;
namespace osu.Framework.Platform
{
public abstract class Clipboard
{
public abstract string GetText();
public abstract void SetText(string selectedText);
public abstract bool SetImage(Image image);
}
}
| mit | C# |
9a5b52e07528bb12fd66f54f5ef47a9e600e0031 | Add image format | dirkrombauts/SpecLogLogoReplacer | UI/MainWindow.xaml.cs | UI/MainWindow.xaml.cs | using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO.Abstractions;
using System.Windows;
namespace SpecLogLogoReplacer.UI
{
public partial class MainWindow
{
private readonly IFileSystem fileSystem;
public MainWindow()
{
InitializeComponent();
this.fileSystem = new FileSystem();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var pathToSpecLogFile = this.specLogFilePath.Text;
var pathToNewLogo = this.newLogoPath.Text;
var specLogFile = this.fileSystem.File.ReadAllText(pathToSpecLogFile);
Image newLogo;
using (var stream = this.fileSystem.File.OpenRead(pathToNewLogo))
{
newLogo = Image.FromStream(stream);
}
var patchedSpecLogFile = new LogoReplacer().Replace(specLogFile, newLogo, ImageFormat.Png);
this.fileSystem.File.WriteAllText(pathToSpecLogFile, patchedSpecLogFile);
}
}
}
| using System;
using System.Drawing;
using System.IO.Abstractions;
using System.Windows;
namespace SpecLogLogoReplacer.UI
{
public partial class MainWindow
{
private readonly IFileSystem fileSystem;
public MainWindow()
{
InitializeComponent();
this.fileSystem = new FileSystem();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var pathToSpecLogFile = this.specLogFilePath.Text;
var pathToNewLogo = this.newLogoPath.Text;
var specLogFile = this.fileSystem.File.ReadAllText(pathToSpecLogFile);
Image newLogo;
using (var stream = this.fileSystem.File.OpenRead(pathToNewLogo))
{
newLogo = Image.FromStream(stream);
}
var patchedSpecLogFile = new LogoReplacer().Replace(specLogFile, newLogo);
this.fileSystem.File.WriteAllText(pathToSpecLogFile, patchedSpecLogFile);
}
}
}
| isc | C# |
6ac56c298030a2c5e2027a427bb26e36cfea3ec9 | Update GenerateThumbnailOfWorksheet.cs | asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_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,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Articles/GenerateThumbnailOfWorksheet.cs | Examples/CSharp/Articles/GenerateThumbnailOfWorksheet.cs | using System.IO;
using Aspose.Cells;
using Aspose.Cells.Rendering;
using System.Drawing;
namespace Aspose.Cells.Examples.Articles
{
public class GenerateThumbnailOfWorksheet
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate and open an Excel file
Workbook book = new Workbook(dataDir+ "book1.xlsx");
//Define ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
//Specify the image format
imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
//Set the vertical and horizontal resolution
imgOptions.VerticalResolution = 200;
imgOptions.HorizontalResolution = 200;
//One page per sheet is enabled
imgOptions.OnePagePerSheet = true;
//Get the first worksheet
Worksheet sheet = book.Worksheets[0];
//Render the sheet with respect to specified image/print options
SheetRender sr = new SheetRender(sheet, imgOptions);
//Render the image for the sheet
Bitmap bmp = sr.ToImage(0);
//Create a bitmap
Bitmap thumb = new Bitmap(100, 100);
//Get the graphics for the bitmap
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(thumb);
//Draw the image
gr.DrawImage(bmp, 0, 0, 100, 100);
//Save the thumbnail
thumb.Save(dataDir+ "mythumbnail.out.bmp");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using Aspose.Cells.Rendering;
using System.Drawing;
namespace Aspose.Cells.Examples.Articles
{
public class GenerateThumbnailOfWorksheet
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate and open an Excel file
Workbook book = new Workbook(dataDir+ "book1.xlsx");
//Define ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
//Specify the image format
imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
//Set the vertical and horizontal resolution
imgOptions.VerticalResolution = 200;
imgOptions.HorizontalResolution = 200;
//One page per sheet is enabled
imgOptions.OnePagePerSheet = true;
//Get the first worksheet
Worksheet sheet = book.Worksheets[0];
//Render the sheet with respect to specified image/print options
SheetRender sr = new SheetRender(sheet, imgOptions);
//Render the image for the sheet
Bitmap bmp = sr.ToImage(0);
//Create a bitmap
Bitmap thumb = new Bitmap(100, 100);
//Get the graphics for the bitmap
System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(thumb);
//Draw the image
gr.DrawImage(bmp, 0, 0, 100, 100);
//Save the thumbnail
thumb.Save(dataDir+ "mythumbnail.out.bmp");
}
}
} | mit | C# |
937ea62b06873fa264d7fd83acfa75199c095b14 | Add checks for expected arguments. | peterlanoie/aspnet-mvc-slack | src/shared/WebHookExceptionReporter.cs | src/shared/WebHookExceptionReporter.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using WebHooks = Slack.Webhooks;
namespace Pelasoft.AspNet.Mvc.Slack
{
public static class WebHookExceptionReporter
{
public static void ReportException(Exception ex, WebHookOptions options)
{
if (options == null)
{
throw new NullReferenceException(
"An instance of WebHookOptions must be provided as it contains the details for connecting to the Slack web hook.");
}
if (options.WebhookUrl == null)
{
throw new ArgumentException(
"WebHookOptions.WebhookUrl must contain a value. Please provide the URL to your Slack team webhook.");
}
var client = new WebHooks.SlackClient(options.WebhookUrl);
var message = new WebHooks.SlackMessage();
if(!string.IsNullOrEmpty(options.ChannelName))
{
message.Channel = options.ChannelName;
}
if(!string.IsNullOrEmpty(options.UserName))
{
message.Username = options.UserName;
}
message.IconEmoji = options.IconEmoji ?? WebHooks.Emoji.HeavyExclamationMark;
message.Text = options.Text ?? "An exception has occurred in an application.";
var attachment = new WebHooks.SlackAttachment();
// simple message for unformatted and notification views
attachment.Fallback = string.Format("Web app exception: {0}", ex.Message);
attachment.Color = options.AttachmentColor ?? "danger";
if(!string.IsNullOrEmpty(options.AttachmentTitle))
{
attachment.Title = options.AttachmentTitle;
}
if(!string.IsNullOrEmpty(options.AttachmentTitleLink))
{
attachment.TitleLink = options.AttachmentTitleLink;
}
attachment.MrkdwnIn = new List<string> { "text" };
var textFormat = @"*URL*: %%url%%
*Machine Name*: %%hostname%%
*Type*: %%ex:type%%
*Message*: %%ex:message%%
*Target Site*: %%ex:site%%
*Stack Trace*:
%%ex:stackTrace%%";
attachment.Text = textFormat
.Replace("%%url%%", HttpContext.Current.Request.Url.ToString())
.Replace("%%hostname%%", Environment.MachineName)
.Replace("%%ex:type%%", ex.GetType().ToString())
.Replace("%%ex:message%%", ex.Message)
.Replace("%%ex:site%%", ex.TargetSite.ToString())
.Replace("%%ex:stackTrace%%", ex.StackTrace);
message.Attachments = new List<WebHooks.SlackAttachment>();
message.Attachments.Add(attachment);
client.Post(message);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using WebHooks = Slack.Webhooks;
namespace Pelasoft.AspNet.Mvc.Slack
{
public static class WebHookExceptionReporter
{
public static void ReportException(Exception ex, WebHookOptions options)
{
var client = new WebHooks.SlackClient(options.WebhookUrl);
var message = new WebHooks.SlackMessage();
if(!string.IsNullOrEmpty(options.ChannelName))
{
message.Channel = options.ChannelName;
}
if(!string.IsNullOrEmpty(options.UserName))
{
message.Username = options.UserName;
}
message.IconEmoji = options.IconEmoji ?? WebHooks.Emoji.HeavyExclamationMark;
message.Text = options.Text ?? "An exception has occurred in an application.";
var attachment = new WebHooks.SlackAttachment();
// simple message for unformatted and notification views
attachment.Fallback = string.Format("Web app exception: {0}", ex.Message);
attachment.Color = options.AttachmentColor ?? "danger";
if(!string.IsNullOrEmpty(options.AttachmentTitle))
{
attachment.Title = options.AttachmentTitle;
}
if(!string.IsNullOrEmpty(options.AttachmentTitleLink))
{
attachment.TitleLink = options.AttachmentTitleLink;
}
attachment.MrkdwnIn = new List<string> { "text" };
var textFormat = @"*URL*: %%url%%
*Machine Name*: %%hostname%%
*Type*: %%ex:type%%
*Message*: %%ex:message%%
*Target Site*: %%ex:site%%
*Stack Trace*:
%%ex:stackTrace%%";
attachment.Text = textFormat
.Replace("%%url%%", HttpContext.Current.Request.Url.ToString())
.Replace("%%hostname%%", Environment.MachineName)
.Replace("%%ex:type%%", ex.GetType().ToString())
.Replace("%%ex:message%%", ex.Message)
.Replace("%%ex:site%%", ex.TargetSite.ToString())
.Replace("%%ex:stackTrace%%", ex.StackTrace);
message.Attachments = new List<WebHooks.SlackAttachment>();
message.Attachments.Add(attachment);
client.Post(message);
}
}
}
| mit | C# |
1c8e17cf11158720af08f0cda6e5999b68879815 | Fix the default background parallax being set incorrectly when no screen is present | smoogipooo/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu | osu.Game/Screens/OsuScreenStack.cs | osu.Game/Screens/OsuScreenStack.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Screens;
using osu.Game.Graphics.Containers;
namespace osu.Game.Screens
{
public class OsuScreenStack : ScreenStack
{
[Cached]
private BackgroundScreenStack backgroundScreenStack;
private readonly ParallaxContainer parallaxContainer;
protected float ParallaxAmount => parallaxContainer.ParallaxAmount;
public OsuScreenStack()
{
InternalChild = parallaxContainer = new ParallaxContainer
{
RelativeSizeAxes = Axes.Both,
Child = backgroundScreenStack = new BackgroundScreenStack { RelativeSizeAxes = Axes.Both },
};
ScreenPushed += screenPushed;
ScreenExited += ScreenChanged;
}
private void screenPushed(IScreen prev, IScreen next)
{
if (LoadState < LoadState.Ready)
{
// dependencies must be present to stay in a sane state.
// this is generally only ever hit by test scenes.
Schedule(() => screenPushed(prev, next));
return;
}
// create dependencies synchronously to ensure leases are in a sane state.
((OsuScreen)next).CreateLeasedDependencies((prev as OsuScreen)?.Dependencies ?? Dependencies);
ScreenChanged(prev, next);
}
protected virtual void ScreenChanged(IScreen prev, IScreen next)
{
setParallax(next);
}
private void setParallax(IScreen next) =>
parallaxContainer.ParallaxAmount = ParallaxContainer.DEFAULT_PARALLAX_AMOUNT * (((IOsuScreen)next)?.BackgroundParallaxAmount ?? 1.0f);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Screens;
using osu.Game.Graphics.Containers;
namespace osu.Game.Screens
{
public class OsuScreenStack : ScreenStack
{
[Cached]
private BackgroundScreenStack backgroundScreenStack;
private readonly ParallaxContainer parallaxContainer;
protected float ParallaxAmount => parallaxContainer.ParallaxAmount;
public OsuScreenStack()
{
InternalChild = parallaxContainer = new ParallaxContainer
{
RelativeSizeAxes = Axes.Both,
Child = backgroundScreenStack = new BackgroundScreenStack { RelativeSizeAxes = Axes.Both },
};
ScreenPushed += screenPushed;
ScreenExited += ScreenChanged;
}
private void screenPushed(IScreen prev, IScreen next)
{
if (LoadState < LoadState.Ready)
{
// dependencies must be present to stay in a sane state.
// this is generally only ever hit by test scenes.
Schedule(() => screenPushed(prev, next));
return;
}
// create dependencies synchronously to ensure leases are in a sane state.
((OsuScreen)next).CreateLeasedDependencies((prev as OsuScreen)?.Dependencies ?? Dependencies);
ScreenChanged(prev, next);
}
protected virtual void ScreenChanged(IScreen prev, IScreen next)
{
setParallax(next);
}
private void setParallax(IScreen next) =>
parallaxContainer.ParallaxAmount = ParallaxContainer.DEFAULT_PARALLAX_AMOUNT * ((IOsuScreen)next)?.BackgroundParallaxAmount ?? 1.0f;
}
}
| mit | C# |
5630eb14c2d2a08e426c7c496fd24dbd40c6b865 | Stop service "properly" | TorchAPI/Torch | Torch.Server/TorchService.cs | Torch.Server/TorchService.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Threading;
using NLog;
using Torch.API;
namespace Torch.Server
{
class TorchService : ServiceBase
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
public const string Name = "Torch (SEDS)";
private Initializer _initializer;
private string[] _args;
public TorchService(string[] args)
{
_args = args;
var workingDir = new FileInfo(typeof(TorchService).Assembly.Location).Directory.ToString();
Directory.SetCurrentDirectory(workingDir);
_initializer = new Initializer(workingDir);
ServiceName = Name;
CanHandleSessionChangeEvent = false;
CanPauseAndContinue = false;
CanStop = true;
}
/// <inheritdoc />
protected override void OnStart(string[] _)
{
base.OnStart(_args);
_initializer.Initialize(_args);
_initializer.Run();
}
/// <inheritdoc />
protected override void OnStop()
{
var mre = new ManualResetEvent(false);
Task.Run(() => _initializer.Server.Stop());
if (!mre.WaitOne(TimeSpan.FromMinutes(1)))
Process.GetCurrentProcess().Kill();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using NLog;
using Torch.API;
namespace Torch.Server
{
class TorchService : ServiceBase
{
public const string Name = "Torch (SEDS)";
private TorchServer _server;
private Initializer _initializer;
private string[] _args;
public TorchService(string[] args)
{
_args = args;
var workingDir = new FileInfo(typeof(TorchService).Assembly.Location).Directory.ToString();
Directory.SetCurrentDirectory(workingDir);
_initializer = new Initializer(workingDir);
ServiceName = Name;
CanHandleSessionChangeEvent = false;
CanPauseAndContinue = false;
CanStop = true;
}
/// <inheritdoc />
protected override void OnStart(string[] _)
{
base.OnStart(_args);
_initializer.Initialize(_args);
_initializer.Run();
}
/// <inheritdoc />
protected override void OnStop()
{
_server.Stop();
base.OnStop();
}
}
}
| apache-2.0 | C# |
08dc5e2018c58391b8acc89777a61018391cac5a | Make it disposable | undees/irule,undees/irule | lib/irule.cs | lib/irule.cs | // The code is new, but the idea is from http://wiki.tcl.tk/9563
using System;
using System.Runtime.InteropServices;
namespace Irule
{
public class TclInterp : IDisposable
{
[DllImport("libtcl.dylib")]
protected static extern IntPtr Tcl_CreateInterp();
[DllImport("libtcl.dylib")]
protected static extern int Tcl_Init(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern int Tcl_Eval(IntPtr interp, string script);
[DllImport("libtcl.dylib")]
protected static extern IntPtr Tcl_GetStringResult(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern void Tcl_DeleteInterp(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern void Tcl_Finalize();
private IntPtr interp;
private bool disposed;
public TclInterp()
{
interp = Tcl_CreateInterp();
Tcl_Init(interp);
disposed = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing && interp != IntPtr.Zero)
{
Tcl_DeleteInterp(interp);
Tcl_Finalize();
}
interp = IntPtr.Zero;
disposed = true;
}
}
public string Eval(string text)
{
if (disposed)
{
throw new ObjectDisposedException("Attempt to use disposed Tcl interpreter");
}
Tcl_Eval(interp, text);
var result = Tcl_GetStringResult(interp);
return Marshal.PtrToStringAnsi(result);
}
}
}
| // The code is new, but the idea is from http://wiki.tcl.tk/9563
using System;
using System.Runtime.InteropServices;
namespace Irule
{
public class TclInterp
{
[DllImport("libtcl.dylib")]
protected static extern IntPtr Tcl_CreateInterp();
[DllImport("libtcl.dylib")]
protected static extern int Tcl_Init(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern int Tcl_Eval(IntPtr interp, string script);
[DllImport("libtcl.dylib")]
protected static extern IntPtr Tcl_GetStringResult(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern void Tcl_DeleteInterp(IntPtr interp);
[DllImport("libtcl.dylib")]
protected static extern void Tcl_Finalize();
private IntPtr interp;
private bool disposed;
public TclInterp()
{
interp = Tcl_CreateInterp();
Tcl_Init(interp);
disposed = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing && interp != IntPtr.Zero)
{
Tcl_DeleteInterp(interp);
Tcl_Finalize();
}
interp = IntPtr.Zero;
disposed = true;
}
}
public string Eval(string text)
{
if (disposed)
{
throw new ObjectDisposedException("Attempt to use disposed Tcl interpreter");
}
Tcl_Eval(interp, text);
var result = Tcl_GetStringResult(interp);
return Marshal.PtrToStringAnsi(result);
}
}
}
| mit | C# |
36af868f447d72f29641b61fbac609df837e26b2 | Add missing licence header. | peppy/osu-new,peppy/osu,UselessToucan/osu,Frontear/osuKyzer,ppy/osu,naoey/osu,peppy/osu,Damnae/osu,NeoAdonis/osu,smoogipoo/osu,Drezi126/osu,smoogipoo/osu,DrabWeb/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,2yangk23/osu,naoey/osu,ppy/osu,UselessToucan/osu,ZLima12/osu,ZLima12/osu,Nabile-Rahmani/osu,EVAST9919/osu,EVAST9919/osu,osu-RP/osu-RP,naoey/osu,RedNesto/osu,smoogipooo/osu,DrabWeb/osu,johnneijzen/osu,UselessToucan/osu,DrabWeb/osu,NeoAdonis/osu,nyaamara/osu,tacchinotacchi/osu,NeoAdonis/osu,peppy/osu | osu.Game/Users/UpdateableAvatar.cs | osu.Game/Users/UpdateableAvatar.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Users
{
/// <summary>
/// An avatar which can update to a new user when needed.
/// </summary>
public class UpdateableAvatar : Container
{
private Avatar displayedAvatar;
private User user;
public User User
{
get { return user; }
set
{
if (user?.Id == value?.Id)
return;
user = value;
if (IsLoaded)
updateAvatar();
}
}
protected override void LoadComplete()
{
base.LoadComplete();
updateAvatar();
}
private void updateAvatar()
{
displayedAvatar?.FadeOut(300);
displayedAvatar?.Expire();
Add(displayedAvatar = new Avatar(user, false) { RelativeSizeAxes = Axes.Both });
}
}
} | using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
namespace osu.Game.Users
{
/// <summary>
/// An avatar which can update to a new user when needed.
/// </summary>
public class UpdateableAvatar : Container
{
private Avatar displayedAvatar;
private User user;
public User User
{
get { return user; }
set
{
if (user?.Id == value?.Id)
return;
user = value;
if (IsLoaded)
updateAvatar();
}
}
protected override void LoadComplete()
{
base.LoadComplete();
updateAvatar();
}
private void updateAvatar()
{
displayedAvatar?.FadeOut(300);
displayedAvatar?.Expire();
Add(displayedAvatar = new Avatar(user, false) { RelativeSizeAxes = Axes.Both });
}
}
} | mit | C# |
219c851c75ddea196934372d8bf350a5a5ca4024 | use different name for different unhandled exception | qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox,Wox-launcher/Wox,qianlifeng/Wox | Wox/Helper/ErrorReporting.cs | Wox/Helper/ErrorReporting.cs | using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Threading;
using NLog;
using Wox.Infrastructure.Exception;
namespace Wox.Helper
{
public static class ErrorReporting
{
private static void Report(Exception e, [CallerMemberName] string method = "")
{
var logger = LogManager.GetLogger(method);
logger.Fatal(ExceptionFormatter.ExceptionWithRuntimeInfo(e));
var reportWindow = new ReportWindow(e);
reportWindow.Show();
}
public static void UnhandledExceptionHandleTask(Task t)
{
//handle non-ui sub task exceptions
Report(t.Exception);
}
public static void UnhandledExceptionHandleMain(object sender, UnhandledExceptionEventArgs e)
{
//handle non-ui main thread exceptions
Report((Exception)e.ExceptionObject);
}
public static void DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
//handle ui thread exceptions
Report(e.Exception);
//prevent application exist, so the user can copy prompted error info
e.Handled = true;
}
}
}
| using System;
using System.Threading.Tasks;
using System.Windows.Threading;
using NLog;
using Wox.Infrastructure;
using Wox.Infrastructure.Exception;
namespace Wox.Helper
{
public static class ErrorReporting
{
private static void Report(Exception e)
{
var logger = LogManager.GetLogger("UnHandledException");
logger.Fatal(ExceptionFormatter.ExceptionWithRuntimeInfo(e));
var reportWindow = new ReportWindow(e);
reportWindow.Show();
}
public static void UnhandledExceptionHandleTask(Task t)
{
//handle non-ui sub task exceptions
Report(t.Exception);
}
public static void UnhandledExceptionHandleMain(object sender, UnhandledExceptionEventArgs e)
{
//handle non-ui main thread exceptions
Report((Exception)e.ExceptionObject);
}
public static void DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
//handle ui thread exceptions
Report(e.Exception);
//prevent application exist, so the user can copy prompted error info
e.Handled = true;
}
}
}
| mit | C# |
5c2ea0f417eb027d06100de18e8fe93ab734dabb | Handle nulls. | wasabii/Cogito,wasabii/Cogito | Cogito.Core/UriBuilderExtensions.cs | Cogito.Core/UriBuilderExtensions.cs | using System;
namespace Cogito
{
/// <summary>
/// Various extensions for working with <see cref="UriBuilder"/> instances.
/// </summary>
public static class UriBuilderExtensions
{
/// <summary>
/// Appends the given name and value as query arguments to the <see cref="UriBuilder"/>.
/// </summary>
/// <param name="self"></param>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static UriBuilder AppendQuery(this UriBuilder self, string name, string value)
{
if (self == null)
throw new ArgumentNullException(nameof(self));
if (name == null)
throw new ArgumentNullException(nameof(name));
var p = Uri.EscapeDataString(name) + "=" + Uri.EscapeDataString(value ?? "");
if (self.Query != null &&
self.Query.Length > 1)
self.Query = self.Query.Substring(1) + "&" + p;
else
self.Query = p;
return self;
}
/// <summary>
/// Appends the given name and value query arguments to the <see cref="UriBuilder"/>.
/// </summary>
/// <param name="self"></param>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static UriBuilder AppendQuery(this UriBuilder self, string name, object value)
{
if (self == null)
throw new ArgumentNullException(nameof(self));
if (name == null)
throw new ArgumentNullException(nameof(name));
return AppendQuery(self, name, value?.ToString());
}
}
}
| using System;
namespace Cogito
{
/// <summary>
/// Various extensions for working with <see cref="UriBuilder"/> instances.
/// </summary>
public static class UriBuilderExtensions
{
/// <summary>
/// Appends the given name and value as query arguments to the <see cref="UriBuilder"/>.
/// </summary>
/// <param name="self"></param>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static UriBuilder AppendQuery(this UriBuilder self, string name, string value)
{
if (self == null)
throw new ArgumentNullException(nameof(self));
if (name == null)
throw new ArgumentNullException(nameof(name));
var p = Uri.EscapeDataString(name) + "=" + Uri.EscapeDataString(value ?? "");
if (self.Query != null &&
self.Query.Length > 1)
self.Query = self.Query.Substring(1) + "&" + p;
else
self.Query = p;
return self;
}
/// <summary>
/// Appends the given name and value query arguments to the <see cref="UriBuilder"/>.
/// </summary>
/// <param name="self"></param>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static UriBuilder AppendQuery(this UriBuilder self, string name, object value)
{
if (self == null)
throw new ArgumentNullException(nameof(self));
if (name == null)
throw new ArgumentNullException(nameof(name));
return AppendQuery(self, name, value.ToString());
}
}
}
| mit | C# |
c5a30b0cf09cad5ad6fc7fdd4b745a9a9fddbd30 | Clean up of app | WildGums/LogViewer | src/LogViewer/App.xaml.cs | src/LogViewer/App.xaml.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="App.xaml.cs" company="Orcomp development team">
// Copyright (c) 2008 - 2014 Orcomp development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace LogViewer
{
using System;
using System.Windows;
using System.Windows.Media;
using Catel.IoC;
using Orchestra.Markup;
using Orchestra.Services;
using Orchestra.Views;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
FontImage.RegisterFont("FontAwesome", new FontFamily(new Uri("pack://application:,,,/LogViewer;component/Resources/Fonts/", UriKind.RelativeOrAbsolute), "./#FontAwesome"));
FontImage.DefaultFontFamily = "FontAwesome";
var serviceLocator = ServiceLocator.Default;
var shellService = serviceLocator.ResolveType<IShellService>();
shellService.CreateWithSplash<ShellWindow>();
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Catel.IoC;
using Orchestra.Markup;
using Orchestra.Services;
using Orchestra.Views;
namespace LogViewer
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
FontImage.RegisterFont("FontAwesome", new FontFamily(new Uri("pack://application:,,,/LogViewer;component/Resources/Fonts/", UriKind.RelativeOrAbsolute), "./#FontAwesome"));
FontImage.DefaultFontFamily = "FontAwesome";
var serviceLocator = ServiceLocator.Default;
var shellService = serviceLocator.ResolveType<IShellService>();
shellService.CreateWithSplash<ShellWindow>();
}
}
}
| mit | C# |
b68194fd7788124b042beec16a7dc388c15f8d22 | update about info | lanayotech/vagrant-manager-windows | Lanayo.VagrantManager/Windows/AboutWindow.cs | Lanayo.VagrantManager/Windows/AboutWindow.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lanayo.Vagrant_Manager.Windows {
public partial class AboutWindow : Form {
public AboutWindow() {
InitializeComponent();
}
private void AboutWindow_Load(object sender, EventArgs e) {
string str = "<div style=\"text-align:center;font-family:Arial;font-size:13px;\">Copyright ©{YEAR} Lanayo, LLC<br><br>Vagrant Manager {VERSION}<br><br>For more information visit:<br><a href=\"{URL}\">{URL}</a><br><br>or check us out on GitHub:<br><a href=\"{GITHUB_URL}\">{GITHUB_URL}</a></div>"
.Replace("{YEAR}", DateTime.Now.Year.ToString())
.Replace("{VERSION}", Application.ProductVersion)
.Replace("{URL}", Properties.Settings.Default.AboutUrl)
.Replace("{GITHUB_URL}", Properties.Settings.Default.GithubUrl)
.Replace("\n", "<br>");
WebBrowser.DocumentText = str;
WebBrowser.Navigating += WebBrowser_Navigating;
}
void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
Process.Start(e.Url.AbsoluteUri);
e.Cancel = true;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lanayo.Vagrant_Manager.Windows {
public partial class AboutWindow : Form {
public AboutWindow() {
InitializeComponent();
}
private void AboutWindow_Load(object sender, EventArgs e) {
string str = "<div style=\"text-align:center;font-family:Arial;font-size:13px;\">Copyright ©{YEAR} Lanayo Tech<br><br>Vagrant Manager {VERSION}<br><br>For more information visit:<br><a href=\"{URL}\">{URL}</a><br><br>or check us out on GitHub:<br><a href=\"{GITHUB_URL}\">{GITHUB_URL}</a></div>"
.Replace("{YEAR}", DateTime.Now.Year.ToString())
.Replace("{VERSION}", Application.ProductVersion)
.Replace("{URL}", Properties.Settings.Default.AboutUrl)
.Replace("{GITHUB_URL}", Properties.Settings.Default.GithubUrl)
.Replace("\n", "<br>");
WebBrowser.DocumentText = str;
WebBrowser.Navigating += WebBrowser_Navigating;
}
void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
Process.Start(e.Url.AbsoluteUri);
e.Cancel = true;
}
}
}
| mit | C# |
37e3a47e4fa896f4ada4a7be7b4f87cc07f7fd90 | Delete sender and edit constructor functions | muhammedikinci/FuzzyCore | FuzzyCore/CommandClasses/GetFile.cs | FuzzyCore/CommandClasses/GetFile.cs | using FuzzyCore.Data;
using FuzzyCore.Server;
using System;
using System.IO;
namespace FuzzyCore.Commands
{
public class GetFile
{
ConsoleMessage Message = new ConsoleMessage();
private String FilePath;
private String FileName;
private JsonCommand mCommand;
public GetFile(Data.JsonCommand Command)
{
FilePath = Command.FilePath;
FileName = Command.Text;
this.mCommand = Command;
}
bool FileControl()
{
FileInfo mfileInfo = new FileInfo(FilePath);
return mfileInfo.Exists;
}
public byte[] GetFileBytes()
{
if (FileControl())
{
byte[] file = File.ReadAllBytes(FilePath + "/" + FileName);
return file;
}
return new byte[0];
}
public string GetFileText()
{
if (FileControl())
{
return File.ReadAllText(FilePath + "/" + FileName);
}
return "";
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FuzzyCore.Server;
namespace FuzzyCore.Commands
{
public class GetFile
{
ConsoleMessage Message = new ConsoleMessage();
public void GetFileBytes(Data.JsonCommand Command)
{
try
{
byte[] file = File.ReadAllBytes(Command.FilePath + "\\" + Command.Text);
if (file.Length > 0)
{
SendDataArray(file, Command.Client_Socket);
Message.Write(Command.CommandType,ConsoleMessage.MessageType.SUCCESS);
}
}
catch (Exception ex)
{
Message.Write(ex.Message, ConsoleMessage.MessageType.ERROR);
}
}
public void SendDataArray(byte[] Data, Socket Client)
{
try
{
Thread.Sleep(100);
Client.Send(Data);
}
catch (Exception ex)
{
Message.Write(ex.Message, ConsoleMessage.MessageType.ERROR);
}
}
}
}
| mit | C# |
787a018c6f3d73a24515255b21c6c2554c64fe5f | Add 5 line | Pesh2003/MyFirstDemoInGitHub | HelloSharp/ThisTimeHello/Program.cs | HelloSharp/ThisTimeHello/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThisTimeHello
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Helo Melo :)");
Console.WriteLine("Add another feature to the club :))");
Console.WriteLine("1234567");
Console.WriteLine("This is third ");
Console.WriteLine("% 5 line");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThisTimeHello
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Helo Melo :)");
Console.WriteLine("Add another feature to the club :))");
Console.WriteLine("1234567");
Console.WriteLine("This is third "); }
}
}
| mit | C# |
b3b1c62ce9cb3b676b0df4f353e4aa1b8f18e6ca | Fix urls | mono0926/xxx-server-proto,mono0926/xxx-server-proto,mono0926/xxx-server-proto,mono0926/xxx-server-proto | JoinProto/App_Start/WebApiConfig.cs | JoinProto/App_Start/WebApiConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace JoinProto
{
public static class WebApiConfig
{
#if DEBUG
public const string BaseUrl = "http://localhost:1235/api/";
#else
public const string BaseUrl = "http://joinproto.azurewebsites.net/api/";
#endif
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// 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.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace JoinProto
{
public static class WebApiConfig
{
#if DEBUG
public const string BaseUrl = "http://joinproto.azurewebsites.net/api/";
#else
public const string BaseUrl = "http://localhost:1235/api/";
#endif
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| mit | C# |
df8da304379bafeb89edf9a65ff174a3b75eb07e | Add write retry mechanism into the client. | darkriszty/NetworkCardsGame | EchoClient/Program.cs | EchoClient/Program.cs | using System;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace EchoClient
{
class Program
{
const int MAX_WRITE_RETRY = 3;
const int WRITE_RETRY_DELAY_SECONDS = 3;
static void Main(string[] args)
{
Task main = MainAsync(args);
main.Wait();
}
static async Task MainAsync(string[] args)
{
using (TcpClient client = new TcpClient("::1", 8080))
{
using (NetworkStream stream = client.GetStream())
{
using (StreamReader reader = new StreamReader(stream))
{
using (StreamWriter writer = new StreamWriter(stream) { AutoFlush = true })
{
while (true)
{
Console.WriteLine("What to send?");
string line = Console.ReadLine();
int writeTry = 0;
bool writtenSuccessfully = false;
while (!writtenSuccessfully && writeTry < MAX_WRITE_RETRY)
{
try
{
writeTry++;
await writer.WriteLineAsync(line);
writtenSuccessfully = true;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to send data to server, try {writeTry} / {MAX_WRITE_RETRY}");
if (!writtenSuccessfully && writeTry == MAX_WRITE_RETRY)
{
Console.WriteLine($"Write retry reach, please check your connectivity with the server and try again. Error details: {Environment.NewLine}{ex.Message}");
}
else
{
await Task.Delay(WRITE_RETRY_DELAY_SECONDS * 1000);
}
}
}
if (!writtenSuccessfully)
{
continue;
}
string response = await reader.ReadLineAsync();
Console.WriteLine($"Response from server {response}");
}
}
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace EchoClient
{
class Program
{
static void Main(string[] args)
{
Task main = MainAsync(args);
main.Wait();
}
static async Task MainAsync(string[] args)
{
TcpClient client = new TcpClient("::1", 8080);
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream) { AutoFlush = true };
while (true)
{
Console.WriteLine("What to send?");
string line = Console.ReadLine();
await writer.WriteLineAsync(line);
string response = await reader.ReadLineAsync();
Console.WriteLine($"Response from server {response}");
}
client.Close();
}
}
}
| mit | C# |
ac8757924bec2a23ada39d84c2d99cbca7009ed6 | Make DefaultEffectHandler internal. | nessos/Eff | src/Eff.Core/DefaultEffectHandler.cs | src/Eff.Core/DefaultEffectHandler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Eff.Core
{
internal class DefaultEffectHandler : EffectHandler
{
public override async ValueTask<ValueTuple> Handle<TResult>(IEffect<TResult> effect)
{
return ValueTuple.Create();
}
public override async ValueTask<ValueTuple> Log(ExceptionLog log)
{
return ValueTuple.Create();
}
public override async ValueTask<ValueTuple> Log(ResultLog log)
{
return ValueTuple.Create();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Eff.Core
{
public class DefaultEffectHandler : EffectHandler
{
public override async ValueTask<ValueTuple> Handle<TResult>(IEffect<TResult> effect)
{
return ValueTuple.Create();
}
public override async ValueTask<ValueTuple> Log(ExceptionLog log)
{
return ValueTuple.Create();
}
public override async ValueTask<ValueTuple> Log(ResultLog log)
{
return ValueTuple.Create();
}
}
}
| mit | C# |
11f566be6f11e1882b163b6a9872e8146a2faf8f | Fix loops not always looking like they do in osu!. | Damnae/storybrew | common/Storyboarding/Display/LoopDecorator.cs | common/Storyboarding/Display/LoopDecorator.cs | using StorybrewCommon.Storyboarding.Commands;
using StorybrewCommon.Storyboarding.CommandValues;
using System;
using System.IO;
namespace StorybrewCommon.Storyboarding.Display
{
public class LoopDecorator<TValue> : ITypedCommand<TValue>
where TValue : CommandValue
{
private ITypedCommand<TValue> command;
private double startTime;
private double repeatDuration;
private int repeats;
public OsbEasing Easing { get { throw new InvalidOperationException(); } }
public double StartTime => startTime;
public double EndTime => startTime + RepeatDuration * repeats;
public double Duration => EndTime - StartTime;
public TValue StartValue => command.StartValue;
public TValue EndValue => command.EndValue;
public bool Active => true;
public double RepeatDuration => repeatDuration < 0 ? command.EndTime : repeatDuration;
public LoopDecorator(ITypedCommand<TValue> command, double startTime, double repeatDuration, int repeats)
{
this.command = command;
this.startTime = startTime;
this.repeatDuration = repeatDuration;
this.repeats = repeats;
}
public TValue ValueAtTime(double time)
{
if (time < StartTime) return command.StartValue;
if (EndTime < time) return command.EndValue;
var repeatDuration = RepeatDuration;
var repeatTime = time - StartTime;
var repeated = false;
while (repeatTime > repeatDuration)
{
repeatTime -= repeatDuration;
repeated = true;
}
if (repeatTime < command.StartTime)
if (repeated && repeatTime < command.StartTime) return command.EndValue;
else return command.StartValue;
if (command.EndTime < repeatTime) return command.EndValue;
return command.ValueAtTime(repeatTime);
}
public void WriteOsb(TextWriter writer, ExportSettings exportSettings, int indentation)
{
throw new InvalidOperationException();
}
public override string ToString() => $"loop x{repeats} ({StartTime}s - {EndTime}s)";
}
}
| using StorybrewCommon.Storyboarding.Commands;
using StorybrewCommon.Storyboarding.CommandValues;
using System;
using System.IO;
namespace StorybrewCommon.Storyboarding.Display
{
public class LoopDecorator<TValue> : ITypedCommand<TValue>
where TValue : CommandValue
{
private ITypedCommand<TValue> command;
private double startTime;
private double repeatDuration;
private int repeats;
public OsbEasing Easing { get { throw new InvalidOperationException(); } }
public double StartTime => startTime;
public double EndTime => startTime + RepeatDuration * repeats;
public double Duration => EndTime - StartTime;
public TValue StartValue => command.StartValue;
public TValue EndValue => command.EndValue;
public bool Active => true;
public double RepeatDuration => repeatDuration < 0 ? command.EndTime : repeatDuration;
public LoopDecorator(ITypedCommand<TValue> command, double startTime, double repeatDuration, int repeats)
{
this.command = command;
this.startTime = startTime;
this.repeatDuration = repeatDuration;
this.repeats = repeats;
}
public TValue ValueAtTime(double time)
{
if (time < StartTime) return command.StartValue;
if (EndTime < time) return command.EndValue;
var repeatDuration = RepeatDuration;
var repeatTime = time - StartTime;
while (repeatTime > repeatDuration)
repeatTime -= repeatDuration;
if (repeatTime < command.StartTime) return command.StartValue;
if (command.EndTime < repeatTime) return command.EndValue;
return command.ValueAtTime(repeatTime);
}
public void WriteOsb(TextWriter writer, ExportSettings exportSettings, int indentation)
{
throw new InvalidOperationException();
}
public override string ToString() => $"loop x{repeats} ({StartTime}s - {EndTime}s)";
}
}
| mit | C# |
a9e63bbb58563e015a63dd50b67a1e7dcee52fcd | Check the more specific coercers first | bungeemonkee/Configgy | Configgy/Coercion/AggregateCoercer.cs | Configgy/Coercion/AggregateCoercer.cs | using System.Linq;
using System.Reflection;
namespace Configgy.Coercion
{
/// <summary>
/// A value coercer that simply aggregates the results from multiple other value coercers.
/// </summary>
public class AggregateCoercer : IValueCoercer
{
private readonly IValueCoercer[] _coercers;
/// <summary>
/// Creates a default aggregate coercer that delegates to the following coercers:
/// <list type="number">
/// <item>Any coercers given as property attributes.</item>
/// <item><see cref="GeneralCoercerAttribute"/></item>
/// <item><see cref="TypeCoercerAttribute"/></item>
/// </list>
/// </summary>
public AggregateCoercer()
: this(new TypeCoercerAttribute(), new GeneralCoercerAttribute())
{
}
/// <summary>
/// Creates an aggregate coercer that delegates to any coercers as property attributes then the given coercers.
/// </summary>
/// <param name="coercers">The coerces this aggregate coercer will delegate to.</param>
public AggregateCoercer(params IValueCoercer[] coercers)
{
_coercers = coercers;
}
/// <summary>
/// Coerce the raw string value into the expected result type.
/// </summary>
/// <typeparam name="T">The expected result type after coercion.</typeparam>
/// <param name="value">The raw string value to be coerced.</param>
/// <param name="valueName">The name of the value to be coerced.</param>
/// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
/// <returns>The coerced value or null if the value could not be coerced.</returns>
public object CoerceTo<T>(string value, string valueName, PropertyInfo property)
{
var propertyCoercers = property == null
? Enumerable.Empty<IValueCoercer>()
: property
.GetCustomAttributes(true)
.OfType<IValueCoercer>();
return propertyCoercers
.Union(_coercers)
.Select(c => c.CoerceTo<T>(value, valueName, property))
.Where(r => r != null)
.FirstOrDefault();
}
}
}
| using System.Linq;
using System.Reflection;
namespace Configgy.Coercion
{
/// <summary>
/// A value coercer that simply aggregates the results from multiple other value coercers.
/// </summary>
public class AggregateCoercer : IValueCoercer
{
private readonly IValueCoercer[] _coercers;
/// <summary>
/// Creates a default aggregate coercer that delegates to the following coercers:
/// <list type="number">
/// <item>Any coercers given as property attributes.</item>
/// <item><see cref="GeneralCoercerAttribute"/></item>
/// <item><see cref="TypeCoercerAttribute"/></item>
/// </list>
/// </summary>
public AggregateCoercer()
: this(new GeneralCoercerAttribute(), new TypeCoercerAttribute())
{
}
/// <summary>
/// Creates an aggregate coercer that delegates to any coercers as property attributes then the given coercers.
/// </summary>
/// <param name="coercers">The coerces this aggregate coercer will delegate to.</param>
public AggregateCoercer(params IValueCoercer[] coercers)
{
_coercers = coercers;
}
/// <summary>
/// Coerce the raw string value into the expected result type.
/// </summary>
/// <typeparam name="T">The expected result type after coercion.</typeparam>
/// <param name="value">The raw string value to be coerced.</param>
/// <param name="valueName">The name of the value to be coerced.</param>
/// <param name="property">If this value is directly associated with a property on a <see cref="Config"/> instance this is the reference to that property.</param>
/// <returns>The coerced value or null if the value could not be coerced.</returns>
public object CoerceTo<T>(string value, string valueName, PropertyInfo property)
{
var propertyCoercers = property == null
? Enumerable.Empty<IValueCoercer>()
: property
.GetCustomAttributes(true)
.OfType<IValueCoercer>();
return propertyCoercers
.Union(_coercers)
.Select(c => c.CoerceTo<T>(value, valueName, property))
.Where(r => r != null)
.FirstOrDefault();
}
}
}
| mit | C# |
52dacd7c4530ed182cc3596fff0b718100b4500e | move model validation to filter in Security module, return a 201 from POST | CityofSantaMonica/Orchard.ParkingData,RaghavAbboy/Orchard.ParkingData | Controllers/SensorEventsController.cs | Controllers/SensorEventsController.cs | using System;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using CSM.ParkingData.Models;
using CSM.ParkingData.Services;
using CSM.ParkingData.ViewModels;
using CSM.Security.Filters.Http;
using Orchard.Logging;
namespace CSM.ParkingData.Controllers
{
[EnableCors("*", null, "GET")]
public class SensorEventsController : ApiController
{
private readonly ISensorEventsService _sensorEventsService;
public ILogger Logger { get; set; }
public SensorEventsController(ISensorEventsService sensorEventsService)
{
_sensorEventsService = sensorEventsService;
Logger = NullLogger.Instance;
}
public IHttpActionResult Get(int limit = 1000)
{
var events = _sensorEventsService.QueryViewModels()
.OrderByDescending(s => s.EventTime)
.Take(limit);
return Ok(events);
}
[RequireBasicAuthentication]
[RequirePermissions("ApiWriter")]
[ModelValidationFilter]
public IHttpActionResult Post([FromBody]SensorEventPOST postedSensorEvent)
{
if (postedSensorEvent == null)
{
Logger.Warning("POST to /sensor_events with null model.");
return BadRequest("Incoming data parsed to null entity model.");
}
SensorEvent entity = null;
try
{
entity = _sensorEventsService.AddOrUpdate(postedSensorEvent);
}
catch (Exception ex)
{
Logger.Error(ex, String.Format("Server error on POST to /sensor_events with model:{0}{1}", Environment.NewLine, Request.Content.ReadAsStringAsync().Result));
return InternalServerError(ex);
}
return Created("", entity);
}
}
}
| using System;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using CSM.ParkingData.Services;
using CSM.ParkingData.ViewModels;
using CSM.Security.Filters.Http;
using Orchard.Logging;
namespace CSM.ParkingData.Controllers
{
[EnableCors("*", null, "GET")]
public class SensorEventsController : ApiController
{
private readonly ISensorEventsService _sensorEventsService;
public ILogger Logger { get; set; }
public SensorEventsController(ISensorEventsService sensorEventsService)
{
_sensorEventsService = sensorEventsService;
Logger = NullLogger.Instance;
}
public IHttpActionResult Get(int limit = 1000)
{
var events = _sensorEventsService.QueryViewModels()
.OrderByDescending(s => s.EventTime)
.Take(limit);
return Ok(events);
}
[RequireBasicAuthentication]
[RequirePermissions("ApiWriter")]
public IHttpActionResult Post([FromBody]SensorEventPOST postedSensorEvent)
{
if (postedSensorEvent == null || !ModelState.IsValid)
{
Logger.Warning("POST with invalid model{0}{1}", Environment.NewLine, Request.Content.ReadAsStringAsync().Result);
return BadRequest();
}
try
{
_sensorEventsService.AddOrUpdate(postedSensorEvent);
}
catch (Exception ex)
{
Logger.Error(ex, String.Format("Server error saving POSTed model{0}{1}", Environment.NewLine, Request.Content.ReadAsStringAsync().Result));
return InternalServerError();
}
return Ok();
}
}
}
| mit | C# |
3568e379d3a9470284d030081a28c5858853e96a | add some more functionality to the new keyboard class | ericrrichards/monorpg | src/MonoRpg/MonoRpg.Engine/System.cs | src/MonoRpg/MonoRpg.Engine/System.cs | namespace MonoRpg.Engine {
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
public static class System {
private static GraphicsDeviceManager _graphics;
public static void Init(GraphicsDeviceManager graphics) {
_graphics = graphics;
}
public static int ScreenWidth => _graphics.PreferredBackBufferWidth;
public static int ScreenHeight => _graphics.PreferredBackBufferHeight;
public static Content Content { get; set; }
public static GraphicsDevice Device => _graphics.GraphicsDevice;
public static Renderer Renderer { get; set; }
public static readonly Keyboard Keys= new Keyboard();
}
public class Keyboard {
private KeyboardState CurrentState { get; set; }
private KeyboardState LastState { get; set; }
public Keyboard() {
CurrentState = new KeyboardState();
LastState = new KeyboardState();
}
public void Update() {
LastState = CurrentState;
CurrentState = Microsoft.Xna.Framework.Input.Keyboard.GetState();
}
public bool WasPressed(Keys key) {
return LastState.IsKeyUp(key) && CurrentState.IsKeyDown(key);
}
public bool WasReleased(Keys key) {
return LastState.IsKeyDown(key) && CurrentState.IsKeyUp(key);
}
public bool IsDown(Keys key) {
return CurrentState.IsKeyDown(key);
}
public bool IsUp(Keys key) {
return CurrentState.IsKeyUp(key);
}
}
} | namespace MonoRpg.Engine {
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
public static class System {
private static GraphicsDeviceManager _graphics;
public static void Init(GraphicsDeviceManager graphics) {
_graphics = graphics;
}
public static int ScreenWidth => _graphics.PreferredBackBufferWidth;
public static int ScreenHeight => _graphics.PreferredBackBufferHeight;
public static Content Content { get; set; }
public static GraphicsDevice Device => _graphics.GraphicsDevice;
public static Renderer Renderer { get; set; }
public static readonly Keyboard Keys= new Keyboard();
public class Keyboard {
private KeyboardState CurrentState { get; set; }
private KeyboardState LastState { get; set; }
public Keyboard() {
CurrentState = new KeyboardState();
LastState = new KeyboardState();
}
public void Update() {
LastState = CurrentState;
CurrentState = Microsoft.Xna.Framework.Input.Keyboard.GetState();
}
public bool WasPressed(Keys key) {
return LastState.IsKeyUp(key) && CurrentState.IsKeyDown(key);
}
}
}
} | mit | C# |
4dc5135934ddc9a268d1894fd288a1786b809996 | set app's main page to be the MasterDetailRootPage | wislon/xamforms-template | src/XamForms/XamForms.UI/App.xaml.cs | src/XamForms/XamForms.UI/App.xaml.cs | using Xamarin.Forms;
namespace XamForms.UI
{
public partial class App : Application
{
public App()
{
InitializeComponent();
// The root page of your application
var mdRoot = new MasterDetailRootPage();
MainPage = mdRoot;
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| using Xamarin.Forms;
namespace XamForms.UI
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| mit | C# |
3d2396caa8aefd558b3cbd2560bb360318c5884f | Bump version to 2.4.1 | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | Files/Packaging/GlobalAssemblyInfo.cs | Files/Packaging/GlobalAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Infinnity Solutions")]
[assembly: AssemblyProduct("InfinniPlatform")]
[assembly: AssemblyCopyright("Copyright © Infinnity Solutions 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyConfiguration("")]
// TeamCity File Content Replacer: Add build number
// Look in: */Packaging/GlobalAssemblyInfo.cs
// Find what: ((AssemblyVersion|AssemblyFileVersion)\s*\(\s*@?\")(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<patch>[0-9]+)\.(?<build>[0-9]+)(\"\s*\))
// Replace with: $1$3.$4.$5.\%build.number%$7
[assembly: AssemblyVersion("2.4.1.0")]
[assembly: AssemblyFileVersion("2.4.1.0")]
// TeamCity File Content Replacer: Add VCS hash
// Look in: */Packaging/GlobalAssemblyInfo.cs
// Find what: (AssemblyInformationalVersion\s*\(\s*@?\").*?(\"\s*\))
// Replace with: $1\%build.vcs.number%$2
[assembly: AssemblyInformationalVersion("")] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Infinnity Solutions")]
[assembly: AssemblyProduct("InfinniPlatform")]
[assembly: AssemblyCopyright("Copyright © Infinnity Solutions 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyConfiguration("")]
// TeamCity File Content Replacer: Add build number
// Look in: */Packaging/GlobalAssemblyInfo.cs
// Find what: ((AssemblyVersion|AssemblyFileVersion)\s*\(\s*@?\")(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<patch>[0-9]+)\.(?<build>[0-9]+)(\"\s*\))
// Replace with: $1$3.$4.$5.\%build.number%$7
[assembly: AssemblyVersion("2.4.0.0")]
[assembly: AssemblyFileVersion("2.4.0.0")]
// TeamCity File Content Replacer: Add VCS hash
// Look in: */Packaging/GlobalAssemblyInfo.cs
// Find what: (AssemblyInformationalVersion\s*\(\s*@?\").*?(\"\s*\))
// Replace with: $1\%build.vcs.number%$2
[assembly: AssemblyInformationalVersion("")] | agpl-3.0 | C# |
2aa8d9ed6c8f02464a97949426f1ac218f6a720f | Remove unused guids | dlsteuer/VisualRust,drewet/VisualRust,yacoder/VisualRust,Vbif/VisualRust,drewet/VisualRust,Connorcpu/VisualRust,Muraad/VisualRust,Boddlnagg/VisualRust,dlsteuer/VisualRust,vosen/VisualRust,cmr/VisualRust,yacoder/VisualRust,tempbottle/VisualRust,PistonDevelopers/VisualRust,xilec/VisualRust,vadimcn/VisualRust,Stitchous/VisualRust,Connorcpu/VisualRust,Vbif/VisualRust,Muraad/VisualRust,PistonDevelopers/VisualRust,Stitchous/VisualRust,cmr/VisualRust,vadimcn/VisualRust,Boddlnagg/VisualRust,tempbottle/VisualRust,xilec/VisualRust,vosen/VisualRust | VisualRust/Guids.cs | VisualRust/Guids.cs | using System;
namespace VisualRust
{
static class GuidList
{
public const string guidVisualRustPkgString = "40c1d2b5-528b-4966-a7b1-1974e3568abe";
};
} | // Guids.cs
// MUST match guids.h
using System;
namespace VisualRust
{
static class GuidList
{
public const string guidVisualRustPkgString = "40c1d2b5-528b-4966-a7b1-1974e3568abe";
public const string guidVisualRustCmdSetString = "c2ea7a57-3978-4bff-bcba-dea4c6638cad";
public static readonly Guid guidVisualRustCmdSet = new Guid(guidVisualRustCmdSetString);
};
} | mit | C# |
e4ba647d6e03d02e876b289ccdf88600df6608c5 | Update test to check for 32-bit preferred | secdec/codepulse,secdec/codepulse | dotnet-tracer/main/OpenCover.Test/Console/OutputTests.cs | dotnet-tracer/main/OpenCover.Test/Console/OutputTests.cs | //
// Modified work Copyright 2017 Secure Decisions, a division of Applied Visions, Inc.
//
using System;
using System.Diagnostics;
using System.IO;
using NUnit.Framework;
// ReSharper disable once CheckNamespace
namespace OpenCover.Test.ConsoleEx
{
[TestFixture]
public class OutputTests
{
[Test]
public void OpenCoverConsoleOutputHasPreferred32BitEnabled()
{
OutputHasPreferred32BitEnabled("OpenCover.Console.exe");
}
[Test]
public void CodePulseConsoleOutputHasPreferred32BitEnabled()
{
OutputHasPreferred32BitEnabled("CodePulse.DotNet.Tracer.exe");
}
private void OutputHasPreferred32BitEnabled(string filename)
{
var pi = new ProcessStartInfo
{
FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.1 Tools\corflags.exe"),
Arguments = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename),
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
};
if (!File.Exists(pi.Arguments))
{
Assert.Inconclusive($"Unable to find exe at {pi.Arguments}.");
}
var process = Process.Start(pi);
Assert.IsNotNull(process);
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Console.WriteLine(output);
Assert.IsTrue(output.Contains("32BITREQ : 0"));
Assert.IsTrue(output.Contains("32BITPREF : 1"));
}
}
}
| //
// Modified work Copyright 2017 Secure Decisions, a division of Applied Visions, Inc.
//
using System;
using System.Diagnostics;
using System.IO;
using NUnit.Framework;
// ReSharper disable once CheckNamespace
namespace OpenCover.Test.ConsoleEx
{
[TestFixture]
public class OutputTests
{
[Test]
public void OpenCoverConsoleOutputHasPreferred32BitDisabled()
{
OutputHasPreferred32BitDisabled("OpenCover.Console.exe");
}
[Test]
public void CodePulseConsoleOutputHasPreferred32BitDisabled()
{
OutputHasPreferred32BitDisabled("CodePulse.DotNet.Tracer.exe");
}
private void OutputHasPreferred32BitDisabled(string filename)
{
var pi = new ProcessStartInfo()
{
FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.1 Tools\corflags.exe"),
Arguments = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename),
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
};
if (!File.Exists(pi.Arguments))
{
Assert.Inconclusive($"Unable to find exe at {pi.Arguments}.");
}
var process = Process.Start(pi);
Assert.IsNotNull(process);
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Console.WriteLine(output);
Assert.IsTrue(output.Contains("32BITPREF : 0"));
}
}
}
| apache-2.0 | C# |
eef93c3824a9de836c80f5627539c7335115ed48 | order and view Fix | TheMightyMidgetsTeam/TheMightyMidgetsProject,TheMightyMidgetsTeam/TheMightyMidgetsProject | JobSite/Controllers/HomeController.cs | JobSite/Controllers/HomeController.cs | using JobSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JobSite.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Index()
{
var jobPosts = db.JobPosts.Where(p => p.ExpireDate > System.DateTime.Now).OrderByDescending(x=>x.PublishDate).ToList();
// var jobPosts = db.JobPosts.OrderByDescending(p => p.ExpireDate > System.DateTime.Now).ToList();
var cat = db.Categories.OrderByDescending(p => p.CategoryName).ToArray();
var catDic = new Dictionary<Category, int>();
var ctytDic = new Dictionary<City, int>();
foreach (var c in jobPosts)
{
if (!catDic.ContainsKey(c.Category))
{
catDic.Add(c.Category, 1);
}
else catDic[c.Category]++;
if (!ctytDic.ContainsKey(c.City))
{
ctytDic.Add(c.City, 1);
}
else ctytDic[c.City]++;
}
ViewBag.Category = catDic;
ViewBag.City = ctytDic;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact pageeeee.";
return View();
}
}
} | using JobSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace JobSite.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Index()
{
var jobPosts = db.JobPosts.OrderByDescending(p => p.ExpireDate > System.DateTime.Now).ToList();
var cat = db.Categories.OrderByDescending(p => p.CategoryName).ToArray();
var catDic = new Dictionary<Category, int>();
var ctytDic = new Dictionary<City, int>();
foreach (var c in jobPosts)
{
if (!catDic.ContainsKey(c.Category))
{
catDic.Add(c.Category, 1);
}
else catDic[c.Category]++;
if (!ctytDic.ContainsKey(c.City))
{
ctytDic.Add(c.City, 1);
}
else ctytDic[c.City]++;
}
ViewBag.Category = catDic;
ViewBag.City = ctytDic;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact pageeeee.";
return View();
}
}
} | mit | C# |
3fc968caa65b7b78f5254a4d26cd9e826075c325 | Increment minor -> 0.1.0 | awseward/restivus | AssemblyInfo.sln.cs | AssemblyInfo.sln.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("0.0.1.0")]
[assembly: AssemblyFileVersion("0.0.1.0")]
[assembly: AssemblyInformationalVersion("0.0.1")]
| mit | C# |
2f898b912c34b9e20e06c7c919ca1e01f0c9c38c | Use expression bodied methods for compact code | mysticfall/Alensia | Assets/Alensia/Core/Input/BindingKey.cs | Assets/Alensia/Core/Input/BindingKey.cs | using Alensia.Core.Input.Generic;
using UnityEngine.Assertions;
namespace Alensia.Core.Input
{
public class BindingKey<T> : IBindingKey<T> where T : IInput
{
public string Id { get; }
public BindingKey(string id)
{
Assert.IsNotNull(id, "id != null");
Id = id;
}
public override bool Equals(object obj) => Id.Equals((obj as BindingKey<T>)?.Id);
public override int GetHashCode() => Id.GetHashCode();
}
} | using Alensia.Core.Input.Generic;
using UnityEngine.Assertions;
namespace Alensia.Core.Input
{
public class BindingKey<T> : IBindingKey<T> where T : IInput
{
public string Id { get; }
public BindingKey(string id)
{
Assert.IsNotNull(id, "id != null");
Id = id;
}
public override bool Equals(object obj)
{
var item = obj as BindingKey<T>;
return item != null && Id.Equals(item.Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
} | apache-2.0 | C# |
530beee356a4f41a11e629027930c35081fe5a77 | add remaining implementations of build provider info | cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe | Cake.Recipe/Content/azurepipelines.cake | Cake.Recipe/Content/azurepipelines.cake | ///////////////////////////////////////////////////////////////////////////////
// BUILD PROVIDER
///////////////////////////////////////////////////////////////////////////////
public class AzurePipelinesTagInfo : ITagInfo
{
public AzurePipelinesTagInfo(ITFBuildProvider tfBuild)
{
// at the moment, there is no ability to know is it tag or not
IsTag = tfBuild.Environment.Repository.Branch.StartsWith("refs/tags/");
Name = IsTag
? tfBuild.Environment.Repository.Branch.Substring(10)
: string.Empty;
}
public bool IsTag { get; }
public string Name { get; }
}
public class AzurePipelinesRepositoryInfo : IRepositoryInfo
{
public AzurePipelinesRepositoryInfo(ITFBuildProvider tfBuild)
{
Branch = tfBuild.Environment.Repository.Branch;
Name = tfBuild.Environment.Repository.RepoName;
Tag = new AzurePipelinesTagInfo(tfBuild);
}
public string Branch { get; }
public string Name { get; }
public ITagInfo Tag { get; }
}
public class AzurePipelinesPullRequestInfo : IPullRequestInfo
{
public AzurePipelinesPullRequestInfo(ITFBuildProvider tfBuild)
{
//todo: update to `tfBuild.Environment.PullRequest.IsPullRequest` after upgrade to 0.33.0
IsPullRequest = false;
}
public bool IsPullRequest { get; }
}
public class AzurePipelinesBuildInfo : IBuildInfo
{
public AzurePipelinesBuildInfo(ITFBuildProvider tfBuild)
{
Number = tfBuild.Environment.Build.Number;
}
public string Number { get; }
}
public class AzurePipelinesBuildProvider : IBuildProvider
{
public AzurePipelinesBuildProvider(ITFBuildProvider tfBuild)
{
Build = new AzurePipelinesBuildInfo(tfBuild);
PullRequest = new AzurePipelinesPullRequestInfo(tfBuild);
Repository = new AzurePipelinesRepositoryInfo(tfBuild);
}
public IRepositoryInfo Repository { get; }
public IPullRequestInfo PullRequest { get; }
public IBuildInfo Build { get; }
} | ///////////////////////////////////////////////////////////////////////////////
// BUILD PROVIDER
///////////////////////////////////////////////////////////////////////////////
public class AzurePipelinesBuildInfo : IBuildInfo
{
public AzurePipelinesBuildInfo(ITFBuildProvider tfBuild)
{
Number = tfBuild.Environment.Build.Number;
}
public string Number { get; }
}
public class AzurePipelinesBuildProvider : IBuildProvider
{
public AzurePipelinesBuildProvider(ITFBuildProvider tfBuild)
{
Build = new AzurePipelinesBuildInfo(tfBuild);
}
public IRepositoryInfo Repository { get; }
public IPullRequestInfo PullRequest { get; }
public IBuildInfo Build { get; }
} | mit | C# |
65b1ff23c9213bbb1b3fcc2fd23578f0f7b59f8a | Fix build: react to EF namespace change | OmniSharp/omnisharp-scaffolding,OmniSharp/omnisharp-scaffolding | test/Microsoft.Framework.CodeGeneration.EntityFramework.Test/TestModels/TestModel.cs | test/Microsoft.Framework.CodeGeneration.EntityFramework.Test/TestModels/TestModel.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.Conventions.Internal;
namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels
{
public static class TestModel
{
public static IModel Model
{
get
{
var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet());
builder.Entity<Product>()
.Reference(p => p.ProductCategory)
.InverseCollection(c => c.CategoryProducts)
.ForeignKey(e => e.ProductCategoryId);
return builder.Model;
}
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Metadata.ModelConventions;
namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels
{
public static class TestModel
{
public static IModel Model
{
get
{
var builder = new ModelBuilder(new CoreConventionSetBuilder().CreateConventionSet());
builder.Entity<Product>()
.Reference(p => p.ProductCategory)
.InverseCollection(c => c.CategoryProducts)
.ForeignKey(e => e.ProductCategoryId);
return builder.Model;
}
}
}
} | mit | C# |
14a9d0f7d6efa936986749a09b8b91640086961d | Add comments for F.Decrement | farity/farity | Farity/Decrement.cs | Farity/Decrement.cs | using System;
namespace Farity
{
public static partial class F
{
/// <summary>
/// Decrements a numeric value by 1.
/// </summary>
/// <typeparam name="T">The type of the numeric value.</typeparam>
/// <param name="value">The value to decrement.</param>
/// <returns>The value decremented by 1.</returns>
public static T Decrement<T>(T value)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable => Subtract(value, (T) Convert.ChangeType(1, typeof(T)));
}
} | using System;
namespace Farity
{
public static partial class F
{
public static T Decrement<T>(T value)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable => Subtract(value, (T) Convert.ChangeType(1, typeof(T)));
}
} | mit | C# |
cc820100570cdd8e028fdd0b895f2933e5555df0 | Use type conversion in F.Decrement | farity/farity | Farity/Decrement.cs | Farity/Decrement.cs | using System;
namespace Farity
{
public static partial class F
{
public static T Decrement<T>(T value)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable => Subtract(value, (T) Convert.ChangeType(1, typeof(T)));
}
} | using System;
namespace Farity
{
public static partial class F
{
public static T Decrement<T>(T value)
where T : struct,
IComparable,
IComparable<T>,
IConvertible,
IEquatable<T>,
IFormattable => Subtract(value, (T) (object) -1);
}
} | mit | C# |
157b64ed20aac9a40a7565716cfa32f8a0e59763 | Add null check. | PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto | Source/Eto/Forms/Controls/GridView.cs | Source/Eto/Forms/Controls/GridView.cs | using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
namespace Eto.Forms
{
public interface IGridStore : IDataStore<IGridItem>
{
}
public partial interface IGridView : IGrid
{
IGridStore DataStore { get; set; }
}
public class GridViewCellArgs : EventArgs
{
public GridColumn GridColumn { get; private set; }
public int Row { get; private set; }
public int Column { get; private set; }
public IGridItem Item { get; private set; }
public GridViewCellArgs (GridColumn gridColumn, int row, int column, IGridItem item)
{
this.GridColumn = gridColumn;
this.Row = row;
this.Column = column;
this.Item = item;
}
}
public partial class GridView : Grid
{
IGridView handler;
public GridView ()
: this (Generator.Current)
{
}
public GridView (Generator g)
: this (g, typeof (IGridView))
{
}
protected GridView (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
handler = (IGridView)Handler;
}
public IGridStore DataStore {
get { return handler.DataStore; }
set { handler.DataStore = value; }
}
public override IEnumerable<IGridItem> SelectedItems
{
get
{
if (DataStore == null)
yield break;
if (SelectedRows != null)
foreach (var row in SelectedRows)
yield return DataStore[row];
}
}
}
}
| using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
namespace Eto.Forms
{
public interface IGridStore : IDataStore<IGridItem>
{
}
public partial interface IGridView : IGrid
{
IGridStore DataStore { get; set; }
}
public class GridViewCellArgs : EventArgs
{
public GridColumn GridColumn { get; private set; }
public int Row { get; private set; }
public int Column { get; private set; }
public IGridItem Item { get; private set; }
public GridViewCellArgs (GridColumn gridColumn, int row, int column, IGridItem item)
{
this.GridColumn = gridColumn;
this.Row = row;
this.Column = column;
this.Item = item;
}
}
public partial class GridView : Grid
{
IGridView handler;
public GridView ()
: this (Generator.Current)
{
}
public GridView (Generator g)
: this (g, typeof (IGridView))
{
}
protected GridView (Generator generator, Type type, bool initialize = true)
: base (generator, type, initialize)
{
handler = (IGridView)Handler;
}
public IGridStore DataStore {
get { return handler.DataStore; }
set { handler.DataStore = value; }
}
public override IEnumerable<IGridItem> SelectedItems
{
get
{
if (DataStore == null)
yield break;
foreach (var row in SelectedRows) {
yield return DataStore[row];
}
}
}
}
}
| bsd-3-clause | C# |
f4e449f0305fc91a74707102851259132348d0d2 | Fix #304 | kjac/Archetype,imulus/Archetype,Nicholas-Westby/Archetype,kipusoep/Archetype,kipusoep/Archetype,kipusoep/Archetype,kjac/Archetype,imulus/Archetype,Nicholas-Westby/Archetype,imulus/Archetype,kgiszewski/Archetype,Nicholas-Westby/Archetype,kgiszewski/Archetype,kgiszewski/Archetype,kjac/Archetype | app/Umbraco/Umbraco.Archetype/Models/ArchetypeModel.cs | app/Umbraco/Umbraco.Archetype/Models/ArchetypeModel.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core.Logging;
namespace Archetype.Models
{
/// <summary>
/// Model that represents an entire Archetype.
/// </summary>
[JsonObject]
public class ArchetypeModel : IEnumerable<ArchetypeFieldsetModel>
{
[JsonProperty("fieldsets")]
public IEnumerable<ArchetypeFieldsetModel> Fieldsets { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ArchetypeModel"/> class.
/// </summary>
public ArchetypeModel()
{
Fieldsets = new List<ArchetypeFieldsetModel>();
}
/// <summary>
/// Returns an enumerator that iterates through the collection of fieldsets.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
public IEnumerator<ArchetypeFieldsetModel> GetEnumerator()
{
return this.Fieldsets.Where(f => f.Disabled == false).GetEnumerator();
}
//possibly obsolete?
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Serializes for persistence. This should be used for serialization as it cleans up the JSON before saving.
/// </summary>
/// <returns></returns>
public string SerializeForPersistence()
{
//clean out any properties with a null datatype
foreach (var fieldset in Fieldsets)
{
var properties = fieldset.Properties.ToList();
foreach (var property in fieldset.Properties)
{
if (property.DataTypeGuid == null)
{
properties.Remove(property);
}
}
fieldset.Properties = properties;
}
var json = JObject.Parse(JsonConvert.SerializeObject(this, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
var propertiesToRemove = new String[] { "propertyEditorAlias", "dataTypeId", "dataTypeGuid", "hostContentType", "editorState" };
json.Descendants().OfType<JProperty>()
.Where(p => propertiesToRemove.Contains(p.Name))
.ToList()
.ForEach(x => x.Remove());
return json.ToString(Formatting.None);
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Archetype.Models
{
/// <summary>
/// Model that represents an entire Archetype.
/// </summary>
[JsonObject]
public class ArchetypeModel : IEnumerable<ArchetypeFieldsetModel>
{
[JsonProperty("fieldsets")]
public IEnumerable<ArchetypeFieldsetModel> Fieldsets { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ArchetypeModel"/> class.
/// </summary>
public ArchetypeModel()
{
Fieldsets = new List<ArchetypeFieldsetModel>();
}
/// <summary>
/// Returns an enumerator that iterates through the collection of fieldsets.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
public IEnumerator<ArchetypeFieldsetModel> GetEnumerator()
{
return this.Fieldsets.Where(f => f.Disabled == false).GetEnumerator();
}
//possibly obsolete?
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Serializes for persistence. This should be used for serialization as it cleans up the JSON before saving.
/// </summary>
/// <returns></returns>
public string SerializeForPersistence()
{
var json = JObject.Parse(JsonConvert.SerializeObject(this, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
var propertiesToRemove = new String[] { "propertyEditorAlias", "dataTypeId", "dataTypeGuid", "hostContentType", "editorState" };
json.Descendants().OfType<JProperty>()
.Where(p => propertiesToRemove.Contains(p.Name))
.ToList()
.ForEach(x => x.Remove());
return json.ToString(Formatting.None);
}
}
}
| mit | C# |
48f7684132a4ede7e4c1d16ccc8f227b8169ece8 | Add support for pinch and scroll input. | YesAndGames/YesAndEngine | YesAndEngine/Input/InputListener.cs | YesAndEngine/Input/InputListener.cs | using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
// Place this behavior on a GUI rect transform to listen for input on that space.
public class InputListener : MonoBehaviour,
IPointerDownHandler,
IPointerUpHandler,
IPointerClickHandler,
IDragHandler,
IScrollHandler {
// An event delegate with a PointerEventData argument.
[Serializable]
public class PointerEvent : UnityEvent<PointerEventData> { }
// An event delegate with two Touch arguments.
[Serializable]
public class TwoTouchEvent : UnityEvent<Touch, Touch> { }
// Fires on the frame a pointer goes down.
[SerializeField]
public PointerEvent PointerDown;
// Fires on the frame a pointer goes up.
[SerializeField]
public PointerEvent PointerUp;
// Fires on the frame a click or tap occurs.
[SerializeField]
public PointerEvent PointerClick;
// Fires each frame the listener interprets a drag gesture.
[SerializeField]
public PointerEvent Drag;
// Fires each frame the listener interprets scroll input.
[SerializeField]
public PointerEvent Scroll;
// Fires each frame the listener interprets a pinch or inverse pinch gesture.
[SerializeField]
public TwoTouchEvent Pinch;
// Clean up this event listener and detach events.
public void Dispose () {
if (Drag != null) {
Drag.RemoveAllListeners ();
}
if (Pinch != null) {
Pinch.RemoveAllListeners ();
}
}
// Interpret a pointer down event.
public void OnPointerDown (PointerEventData eventData) {
if (PointerDown != null) {
PointerDown.Invoke (eventData);
}
UpdateTouchInput ();
}
// Interpret a pointer up event.
public void OnPointerUp (PointerEventData eventData) {
if (PointerUp != null) {
PointerUp.Invoke (eventData);
}
UpdateTouchInput ();
}
// Interpret a pointer cllick event.
public void OnPointerClick (PointerEventData eventData) {
if (PointerClick != null) {
PointerClick.Invoke (eventData);
}
UpdateTouchInput ();
}
// Interpret a drag event.
public void OnDrag (PointerEventData eventData) {
if (Drag != null) {
Drag.Invoke (eventData);
}
UpdateTouchInput ();
}
// Interpret a scroll event.
public void OnScroll (PointerEventData eventData) {
if (Scroll != null) {
Scroll.Invoke (eventData);
}
}
// Interpret touch input that isn't fired by Unity input events.
private void UpdateTouchInput () {
// If there is at least one touch on the device...
if (Input.touchCount > 0) {
Touch touchZero = Input.GetTouch (0);
// If there are two touches on the device...
if (Input.touchCount == 2) {
Touch touchOne = Input.GetTouch (1);
// Fire a pinch event.
if (Pinch != null) {
Pinch.Invoke (touchZero, touchOne);
}
}
}
}
}
| using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
// Place this behavior on a GUI rect transform to listen for input on that space.
public class InputListener : MonoBehaviour,
IPointerDownHandler,
IPointerUpHandler,
IPointerClickHandler,
IDragHandler {
// An event delegate with a PointerEventData argument.
[Serializable]
public class PointerEvent : UnityEvent<PointerEventData> { }
// An event delegate with two Touch arguments.
[Serializable]
public class TwoTouchEvent : UnityEvent<Touch, Touch> { }
// Fires on the frame a pointer goes down.
[SerializeField]
public PointerEvent PointerDown;
// Fires on the frame a pointer goes up.
[SerializeField]
public PointerEvent PointerUp;
// Fires on the frame a click or tap occurs.
[SerializeField]
public PointerEvent PointerClick;
// Fires each frame the listener interprets a drag gesture.
[SerializeField]
public PointerEvent Drag;
// Fires each frame the listener interprets a pinch or inverse pinch gesture.
[SerializeField]
public TwoTouchEvent Pinch;
// Clean up this event listener and detach events.
public void Dispose () {
if (Drag != null) {
Drag.RemoveAllListeners ();
}
if (Pinch != null) {
Pinch.RemoveAllListeners ();
}
}
// Interpret a pointer down event.
public void OnPointerDown (PointerEventData eventData) {
if (PointerDown != null) {
PointerDown.Invoke (eventData);
}
UpdateTouchInput ();
}
// Interpret a pointer up event.
public void OnPointerUp (PointerEventData eventData) {
if (PointerUp != null) {
PointerUp.Invoke (eventData);
}
UpdateTouchInput ();
}
// Interpret a pointer cllick event.
public void OnPointerClick (PointerEventData eventData) {
if (PointerClick != null) {
PointerClick.Invoke (eventData);
}
UpdateTouchInput ();
}
// Interpret a drag event.
public void OnDrag (PointerEventData eventData) {
if (Drag != null) {
Drag.Invoke (eventData);
}
UpdateTouchInput ();
}
// Interpret touch input that isn't fired by Unity input events.
private void UpdateTouchInput () {
// If there is at least one touch on the device...
if (Input.touchCount > 0) {
Touch touchZero = Input.GetTouch (0);
// If there are two touches on the device...
if (Input.touchCount == 2) {
Touch touchOne = Input.GetTouch (1);
// Fire a pinch event.
if (Pinch != null) {
Pinch.Invoke (touchZero, touchOne);
}
}
}
}
}
| apache-2.0 | C# |
ea023fc052e97fc024082aa0fff07392ddbf2556 | Update Client.cs | cosential/cosential-client-csharp | Client.cs | Client.cs | using System;
using System.Net;
using RestSharp;
using RestSharp.Authenticators;
namespace Cosential.Integrations.CompassApiClient
{
public class Client
{
private readonly RestClient _client;
public static readonly Uri DefaultUri = new Uri("https://compass.cosential.com/api");
public Client(int firmId, Guid apiKey, string username, string password, Uri host= null)
{
if (host == null) host = DefaultUri;
_client = new RestClient(host)
{
Authenticator = new HttpBasicAuthenticator(username, password)
};
_client.AddDefaultHeader("x-compass-api-key", apiKey.ToString());
_client.AddDefaultHeader("x-compass-firm-id", firmId.ToString());
_client.AddDefaultHeader("Accept", "application/json");
}
public IRestResponse Execute(RestRequest request)
{
var res = _client.Execute(request);
ValidateResponse(res);
return res;
}
public IRestResponse<T> Execute<T>(RestRequest request) where T : new()
{
var res = _client.Execute<T>(request);
ValidateResponse(res);
return res;
}
private static void ValidateResponse(IRestResponse response)
{
if (response.StatusCode != HttpStatusCode.OK) throw new ResponseStatusCodeException(response);
}
}
}
| using System;
using System.Net;
using RestSharp;
using RestSharp.Authenticators;
//ToDo: Create a git hub account for Cosential to host this project as an open source project (along with unit tests)
namespace Cosential.Integrations.CompassApiClient
{
public class Client
{
private readonly RestClient _client;
public static readonly Uri DefaultUri = new Uri("https://compass.cosential.com/api");
public Client(int firmId, Guid apiKey, string username, string password, Uri host= null)
{
if (host == null) host = DefaultUri;
_client = new RestClient(host)
{
Authenticator = new HttpBasicAuthenticator(username, password)
};
_client.AddDefaultHeader("x-compass-api-key", apiKey.ToString());
_client.AddDefaultHeader("x-compass-firm-id", firmId.ToString());
_client.AddDefaultHeader("Accept", "application/json");
}
public IRestResponse Execute(RestRequest request)
{
var res = _client.Execute(request);
ValidateResponse(res);
return res;
}
public IRestResponse<T> Execute<T>(RestRequest request) where T : new()
{
var res = _client.Execute<T>(request);
ValidateResponse(res);
return res;
}
private static void ValidateResponse(IRestResponse response)
{
if (response.StatusCode != HttpStatusCode.OK) throw new ResponseStatusCodeException(response);
}
}
}
| apache-2.0 | C# |
43837a163fef5a1eeab8a41a87e79097c96576b1 | Update Constants.cs | HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II | airesources/CSharp/hlt/Constants.cs | airesources/CSharp/hlt/Constants.cs | /// <summary>
/// Game Constants
/// </summary>
public class Constants {
// Number of units of distance a ship can move in a turn
public const double MaxSpeed = 7.0;
// Radius of a ship from the center
public const double ShipRadius = 0.5;
// Health of a ship when spawned
public const int BaseShipHealth = 255;
// Effetive radius from the ships center where enemy ships will be dealt damage
public const double WeaponRadius = 5.0;
// Damage dealt to enemy ships per turn by a ship
public const double WeaponDamage = 64;
// Radius in which explosions affect other entities
public const double ExplosionRadius = 10;
// Additional Radius from the planet edge at which the ship can dock to the planet
public const double DockRadius = 4;
// Number of turns it takes to dock the ship once the docking command is issued
public const int TurnsToDock = 5;
// Number of turns it takes a single docked ship to produce another ship. This grows linearly with the number of ships
public const int BaseProductivity = 6;
// Radius from the planets edge where new ships will be spawned
public const int SpawnRadius = 2;
}
| /// <summary>
/// Game Constants
/// </summary>
public class Constants {
// Number of units of distance a ship can move in a turn
public const double MaxSpeed = 7.0;
// Radius of a ship from the center
public const double ShipRadius = 0.5;
// Health of a ship when spawned
public const int BaseShipHealth = 255;
// Effetive radius from the ships center where enemy ships will be dealt damage
public const double WeaponRadius = 5.0;
// Damage dealt to enemy ships per turn by a ship
public const double WeaponDamage = 64;
// Additional Radius from the planet edge at which the ship can dock to the planet
public const double DockRadius = 4;
// Number of turns it takes to dock the ship once the docking command is issued
public const int TurnsToDock = 5;
// Number of turns it takes a single docked ship to produce another ship. This grows linearly with the number of ships
public const int BaseProductivity = 12;
// Radius from the planets edge where new ships will be spawned
public const int SpawnRadius = 2;
} | mit | C# |
88cc9c7f42d87bfa85ef316b2fdeafc6504b5cea | Disable shacking | Evorlor/Wok-n-Roll | Assets/Scripts/Core.cs | Assets/Scripts/Core.cs | using UnityEngine;
using System.Collections;
using System;
public class Core : MonoBehaviour {
private bool EnableShackingStyle = false;
private int ShackingTimes = 2;
private int currentShackingTime = 0;
private bool debounced = false;
private IRecipe mRecipe;
private bool started = true;
public float TimeToSkip = -1.0f;
private float timeDuration = 0.0f;
private float ScoreValue = 0.1f;
private float Score = 0.0f;
// Use this for initialization
void Start () {
// TODO: Testing
mRecipe = new RandomRecipe();
}
// Update is called once per frame
void Update () {
if (started && mRecipe != null)
{
Action action = mRecipe.CurrentStep();
if (TimeToSkip >= 0.0f)
{
timeDuration += Time.deltaTime;
if (timeDuration >= TimeToSkip)
{
started = nextStep();
return;
}
}
Debug.Log(action);
if (Control.GetInstance().GetInput(action))
{
if (action == Action.Jump)
{
for (int i = (int)Action.BEGIN + 1; i < (int)Action.SIZE; i++)
{
if (i == (int)Action.Jump)
continue;
if (Control.GetInstance().GetInput((Action)i))
return;
}
Score += ScoreValue;
started = nextStep();
}
else
{
if (debounced || !EnableShackingStyle) {
debounced = false;
currentShackingTime++;
if ((currentShackingTime >= ShackingTimes) || !EnableShackingStyle)
{
currentShackingTime = 0;
Score += ScoreValue;
started = nextStep();
Debug.Log(Score);
}
}
}
} else
{
debounced = true;
}
}
}
public bool IsStarted()
{
return started;
}
private bool nextStep()
{
bool valid = true;
try
{
mRecipe.NextStep();
}
catch (InvalidOperationException)
{
valid = false;
}
return valid;
}
private bool preStep()
{
bool valid = true;
try
{
mRecipe.PreStep();
}
catch (InvalidOperationException)
{
valid = false;
}
return valid;
}
public void SetRecipe(IRecipe recipe)
{
mRecipe = recipe;
}
public void StartCooking()
{
started = true;
}
}
| using UnityEngine;
using System.Collections;
using System;
public class Core : MonoBehaviour {
private bool EnableShackingStyle = true;
private int ShackingTimes = 2;
private int currentShackingTime = 0;
private bool debounced = false;
private IRecipe mRecipe;
private bool started = true;
public float TimeToSkip = -1.0f;
private float timeDuration = 0.0f;
private float ScoreValue = 0.1f;
private float Score = 0.0f;
// Use this for initialization
void Start () {
// TODO: Testing
mRecipe = new RandomRecipe();
}
// Update is called once per frame
void Update () {
if (started && mRecipe != null)
{
Action action = mRecipe.CurrentStep();
if (TimeToSkip >= 0.0f)
{
timeDuration += Time.deltaTime;
if (timeDuration >= TimeToSkip)
{
started = nextStep();
return;
}
}
Debug.Log(action);
if (Control.GetInstance().GetInput(action))
{
if (action == Action.Jump)
{
for (int i = (int)Action.BEGIN + 1; i < (int)Action.SIZE; i++)
{
if (i == (int)Action.Jump)
continue;
if (Control.GetInstance().GetInput((Action)i))
return;
}
Score += ScoreValue;
started = nextStep();
}
else
{
if (debounced || !EnableShackingStyle) {
debounced = false;
currentShackingTime++;
if ((currentShackingTime >= ShackingTimes) || !EnableShackingStyle)
{
currentShackingTime = 0;
Score += ScoreValue;
started = nextStep();
Debug.Log(Score);
}
}
}
} else
{
debounced = true;
}
}
}
public bool IsStarted()
{
return started;
}
private bool nextStep()
{
bool valid = true;
try
{
mRecipe.NextStep();
}
catch (InvalidOperationException)
{
valid = false;
}
return valid;
}
private bool preStep()
{
bool valid = true;
try
{
mRecipe.PreStep();
}
catch (InvalidOperationException)
{
valid = false;
}
return valid;
}
public void SetRecipe(IRecipe recipe)
{
mRecipe = recipe;
}
public void StartCooking()
{
started = true;
}
}
| mit | C# |
bd48da68ac54168543272beb12ebc11def6d8941 | Add nullable | genlu/roslyn,mgoertz-msft/roslyn,davkean/roslyn,wvdd007/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,jmarolf/roslyn,reaction1989/roslyn,mavasani/roslyn,genlu/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,tannergooding/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,tmat/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,stephentoub/roslyn,heejaechang/roslyn,diryboy/roslyn,brettfo/roslyn,aelij/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,tmat/roslyn,diryboy/roslyn,stephentoub/roslyn,gafter/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,physhi/roslyn,tmat/roslyn,davkean/roslyn,brettfo/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,weltkante/roslyn,eriawan/roslyn,reaction1989/roslyn,davkean/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,mavasani/roslyn,stephentoub/roslyn,diryboy/roslyn,gafter/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,eriawan/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,wvdd007/roslyn,aelij/roslyn,sharwell/roslyn,weltkante/roslyn,genlu/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,aelij/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,sharwell/roslyn,tannergooding/roslyn,mavasani/roslyn | src/VisualStudio/Core/Def/Implementation/ProjectTelemetry/IProjectTelemetryService.cs | src/VisualStudio/Core/Def/Implementation/ProjectTelemetry/IProjectTelemetryService.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.
#nullable enable
using System.Threading;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectTelemetry
{
/// <summary>
/// In process service responsible for listening to OOP telemetry notifications.
/// </summary>
internal interface IProjectTelemetryService : IWorkspaceService
{
/// <summary>
/// Called by a host to let this service know that it should start background
/// analysis of the workspace to determine project telemetry.
/// </summary>
void Start(CancellationToken cancellationToken);
}
}
| // 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.
using System.Threading;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectTelemetry
{
/// <summary>
/// In process service responsible for listening to OOP telemetry notifications.
/// </summary>
internal interface IProjectTelemetryService : IWorkspaceService
{
/// <summary>
/// Called by a host to let this service know that it should start background
/// analysis of the workspace to determine project telemetry.
/// </summary>
void Start(CancellationToken cancellationToken);
}
}
| mit | C# |
40b6f0f5c1b457fe2fd84e437e62e76303b1c646 | Bump assembly versions to 2.6.0 | hudl/Mjolnir | Hudl.Mjolnir/Properties/AssemblyInfo.cs | Hudl.Mjolnir/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Hudl.Mjolnir")]
[assembly: AssemblyDescription("Fault tolerance library for protecting against cascading failure. Uses thread pools and circuit breakers to isolate problems and fail fast.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hudl")]
[assembly: AssemblyProduct("Hudl.Mjolnir")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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)]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.Tests")]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.SystemTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b23684-6c4a-4749-b307-5867cbce2dff")]
// Used for NuGet packaging, uses semantic versioning: major.minor.patch-prerelease.
[assembly: AssemblyInformationalVersion("2.6.0")]
// Keep this the same as AssemblyInformationalVersion.
[assembly: AssemblyFileVersion("2.6.0")]
// ONLY change this when the major version changes; never with minor/patch/build versions.
// It'll almost always be the major version followed by three zeroes (e.g. 1.0.0.0).
[assembly: AssemblyVersion("2.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Hudl.Mjolnir")]
[assembly: AssemblyDescription("Fault tolerance library for protecting against cascading failure. Uses thread pools and circuit breakers to isolate problems and fail fast.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hudl")]
[assembly: AssemblyProduct("Hudl.Mjolnir")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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)]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.Tests")]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.SystemTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b23684-6c4a-4749-b307-5867cbce2dff")]
// Used for NuGet packaging, uses semantic versioning: major.minor.patch-prerelease.
[assembly: AssemblyInformationalVersion("2.5.0")]
// Keep this the same as AssemblyInformationalVersion.
[assembly: AssemblyFileVersion("2.5.0")]
// ONLY change this when the major version changes; never with minor/patch/build versions.
// It'll almost always be the major version followed by three zeroes (e.g. 1.0.0.0).
[assembly: AssemblyVersion("2.0.0.0")]
| apache-2.0 | C# |
2396732e42c0bb3e1da3510b4b7c33bdcaa08519 | Bump version to 1.6.0.0 | courtneyklatt/Mjolnir,hudl/Mjolnir | Hudl.Mjolnir/Properties/AssemblyInfo.cs | Hudl.Mjolnir/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Hudl.Mjolnir")]
[assembly: AssemblyDescription("Isolation library for protecting against cascading failure.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hudl")]
[assembly: AssemblyProduct("Hudl.Mjolnir")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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)]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b23684-6c4a-4749-b307-5867cbce2dff")]
// 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.6.0.0")]
[assembly: AssemblyFileVersion("1.6.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Hudl.Mjolnir")]
[assembly: AssemblyDescription("Isolation library for protecting against cascading failure.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hudl")]
[assembly: AssemblyProduct("Hudl.Mjolnir")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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)]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b23684-6c4a-4749-b307-5867cbce2dff")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
| apache-2.0 | C# |
da97633f5cc49aa763894c17be03177202acbf34 | Fix Role enum. | enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api | Infopulse.EDemocracy.Model/Enum/Role.cs | Infopulse.EDemocracy.Model/Enum/Role.cs | namespace Infopulse.EDemocracy.Model.Enum
{
public enum Role
{
Admin = 1,
Moderator = 2,
TeamMember = 3,
User = 4
}
} | namespace Infopulse.EDemocracy.Model.Enum
{
public enum Role
{
Admin,
Moderator
}
} | cc0-1.0 | C# |
1591f4cafd693121545424055748720a48f41f03 | Update copyright year in assembly info | Heufneutje/HeufyAudioRecorder,Heufneutje/AudioSharp | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AudioSharp")]
[assembly: AssemblyCopyright("Copyright (c) 2015-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.3.0")]
[assembly: AssemblyFileVersion("1.4.3.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AudioSharp")]
[assembly: AssemblyCopyright("Copyright (c) 2015-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.3.0")]
[assembly: AssemblyFileVersion("1.4.3.0")]
| mit | C# |
fea31df347fe7012cb117024012b1d38fc24b604 | Add async overloads to HttpTasks | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/IO/HttpTasks.cs | source/Nuke.Common/IO/HttpTasks.cs | // Copyright Matthias Koch, Sebastian Karasek 2018.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Nuke.Common.Tooling;
namespace Nuke.Common.IO
{
[PublicAPI]
public static class HttpTasks
{
[Pure]
public static string HttpDownloadString(
string uri,
Configure<WebClient> clientConfigurator = null,
Action<WebHeaderCollection> headerConfigurator = null,
Action<WebRequest> requestConfigurator = null)
{
return HttpDownloadStringAsync(uri, clientConfigurator, headerConfigurator, requestConfigurator).GetAwaiter().GetResult();
}
[Pure]
public static async Task<string> HttpDownloadStringAsync(
string uri,
Configure<WebClient> clientConfigurator = null,
Action<WebHeaderCollection> headerConfigurator = null,
Action<WebRequest> requestConfigurator = null)
{
WebClient webClient = new CustomWebClient(requestConfigurator);
webClient = clientConfigurator.InvokeSafe(webClient);
headerConfigurator?.Invoke(webClient.Headers);
return await webClient.DownloadStringTaskAsync(new Uri(uri));
}
public static void HttpDownloadFile(
string uri,
string path,
Configure<WebClient> clientConfigurator = null,
Action<WebHeaderCollection> headerConfigurator = null,
Action<WebRequest> requestConfigurator = null)
{
HttpDownloadFileAsync(uri, path, clientConfigurator, headerConfigurator, requestConfigurator).GetAwaiter().GetResult();
}
public static async Task HttpDownloadFileAsync(
string uri,
string path,
Configure<WebClient> clientConfigurator = null,
Action<WebHeaderCollection> headerConfigurator = null,
Action<WebRequest> requestConfigurator = null)
{
var webClient = new WebClient();
webClient = clientConfigurator.InvokeSafe(webClient);
headerConfigurator?.Invoke(webClient.Headers);
FileSystemTasks.EnsureExistingParentDirectory(path);
await webClient.DownloadFileTaskAsync(new Uri(uri), path);
}
private class CustomWebClient : WebClient
{
private readonly Action<WebRequest> _requestConfigurator;
public CustomWebClient(Action<WebRequest> requestConfigurator)
{
_requestConfigurator = requestConfigurator;
}
protected override WebRequest GetWebRequest(Uri address)
{
var webRequest = base.GetWebRequest(address);
_requestConfigurator(webRequest);
return webRequest;
}
}
}
}
| // Copyright Matthias Koch, Sebastian Karasek 2018.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using System.Net;
using JetBrains.Annotations;
using Nuke.Common.Tooling;
namespace Nuke.Common.IO
{
[PublicAPI]
public static class HttpTasks
{
[Pure]
public static string HttpDownloadString(
string uri,
Configure<WebClient> configurator = null,
Action<WebHeaderCollection> headerConfigurator = null)
{
var webClient = new WebClient();
webClient = configurator.InvokeSafe(webClient);
headerConfigurator?.Invoke(webClient.Headers);
return webClient.DownloadString(new Uri(uri));
}
public static void HttpDownloadFile(
string uri,
string path,
Configure<WebClient> configurator = null,
Action<WebHeaderCollection> headerConfigurator = null)
{
var webClient = new WebClient();
webClient = configurator.InvokeSafe(webClient);
headerConfigurator?.Invoke(webClient.Headers);
FileSystemTasks.EnsureExistingParentDirectory(path);
webClient.DownloadFile(new Uri(uri), path);
}
}
}
| mit | C# |
8b48df88a3a1e9a8f1760684eb8de975afeeeed2 | Implement Equatable<CcsProcess> | lou1306/CIV,lou1306/CIV | CIV.Ccs/Processes/PrefixProcess.cs | CIV.Ccs/Processes/PrefixProcess.cs | using System;
using System.Collections.Generic;
using CIV.Interfaces;
namespace CIV.Ccs
{
public class PrefixProcess : CcsProcess
{
public String Label { get; set; }
public CcsProcess Inner { get; set; }
public override bool Equals(CcsProcess other)
{
var otherPrefix = other as PrefixProcess;
return
otherPrefix != null &&
(Label == otherPrefix.Label) &&
Inner.Equals(otherPrefix.Inner);
}
public override IEnumerable<Transition> Transitions()
{
return new List<Transition>{
new Transition{
Label = Label,
Process = Inner
}
};
}
}
}
| using System;
using System.Collections.Generic;
using CIV.Interfaces;
namespace CIV.Ccs
{
public class PrefixProcess : CcsProcess
{
public String Label { get; set; }
public IProcess Inner { get; set; }
public override IEnumerable<Transition> Transitions()
{
return new List<Transition>{
new Transition{
Label = Label,
Process = Inner
}
};
}
}
}
| mit | C# |
004dbdffe73e76293e9bf380fde97b20751222b1 | Tweak minigun projectile's impact sound. | fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game | game/server/weapons/minigun.projectile.sfx.cs | game/server/weapons/minigun.projectile.sfx.cs | //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright notices are in the file named COPYING.
//------------------------------------------------------------------------------
datablock AudioProfile(MinigunProjectileImpactSound)
{
filename = "share/sounds/rotc/debris1.wav";
// filename = "share/sounds/rotc/impact3-1.wav";
// alternate[0] = "share/sounds/rotc/impact3-1.wav";
// alternate[1] = "share/sounds/rotc/impact3-2.wav";
// alternate[2] = "share/sounds/rotc/impact3-3.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(MinigunProjectileFlybySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioCloseLooping3D;
preload = true;
};
datablock AudioProfile(MinigunProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/ricochet1-1.wav";
alternate[0] = "share/sounds/rotc/ricochet1-1.wav";
alternate[1] = "share/sounds/rotc/ricochet1-2.wav";
alternate[2] = "share/sounds/rotc/ricochet1-3.wav";
alternate[3] = "share/sounds/rotc/ricochet1-4.wav";
alternate[4] = "share/sounds/rotc/ricochet1-5.wav";
alternate[5] = "share/sounds/rotc/ricochet1-6.wav";
description = AudioClose3D;
preload = true;
};
| //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright notices are in the file named COPYING.
//------------------------------------------------------------------------------
datablock AudioProfile(MinigunProjectileImpactSound)
{
//filename = "share/sounds/rotc/impact1.wav";
filename = "share/sounds/rotc/impact3-1.wav";
alternate[0] = "share/sounds/rotc/impact3-1.wav";
alternate[1] = "share/sounds/rotc/impact3-2.wav";
alternate[2] = "share/sounds/rotc/impact3-3.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(MinigunProjectileFlybySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioCloseLooping3D;
preload = true;
};
datablock AudioProfile(MinigunProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/ricochet1-1.wav";
alternate[0] = "share/sounds/rotc/ricochet1-1.wav";
alternate[1] = "share/sounds/rotc/ricochet1-2.wav";
alternate[2] = "share/sounds/rotc/ricochet1-3.wav";
alternate[3] = "share/sounds/rotc/ricochet1-4.wav";
alternate[4] = "share/sounds/rotc/ricochet1-5.wav";
alternate[5] = "share/sounds/rotc/ricochet1-6.wav";
description = AudioClose3D;
preload = true;
};
| lgpl-2.1 | C# |
4260eca1f3364fb17924777b21949781cf0a2f56 | Update Program.cs | Mattgyver317/GitTest1,Mattgyver317/GitTest1 | ConsoleApp1/ConsoleApp1/Program.cs | ConsoleApp1/ConsoleApp1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// This code has been edited in GitHub
// code was added in VS
//Code to Call Feature1
//Code to Call Feature3
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// This code has been edited in GitHub
// code was added in VS
//Code to Call Feature1
}
}
}
| mit | C# |
6402cc363e0bbad1545b2f461fd82796056a8b84 | Update Program.cs | mtsuker/GitTest1 | ConsoleApp1/ConsoleApp1/Program.cs | ConsoleApp1/ConsoleApp1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//github change
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
5ca6e1a7c6ea302981303be830b3889115372857 | bump to 1.3.7 | Terradue/DotNetTep,Terradue/DotNetTep | Terradue.Tep/Properties/AssemblyInfo.cs | Terradue.Tep/Properties/AssemblyInfo.cs | /*!
\namespace Terradue.Tep
@{
Terradue.Tep Software Package provides with all the functionalities specific to the TEP.
\xrefitem sw_version "Versions" "Software Package Version" 1.3.7
\xrefitem sw_link "Links" "Software Package List" [Terradue.Tep](https://git.terradue.com/sugar/Terradue.Tep)
\xrefitem sw_license "License" "Software License" [AGPL](https://git.terradue.com/sugar/Terradue.Tep/LICENSE)
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch
\xrefitem sw_req "Require" "Software Dependencies" \ref ServiceStack
\xrefitem sw_req "Require" "Software Dependencies" \ref log4net
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Portal
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Authentication.Umsso
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Cloud
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Github
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Metadata.EarthObservation
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.News
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenNebula
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.GeoJson
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.RdfEO
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.Tumblr
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.Twitter
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Ogc.OwsContext
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Syndication
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.WebService.Model
\ingroup Tep
@}
*/
/*!
\defgroup Tep Tep Modules
@{
This is a super component that encloses all Thematic Exploitation Platform related functional components.
Their main functionnalities are targeted to enhance the basic \ref Core functionalities for the thematic usage of the plaform.
@}
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using NuGet4Mono.Extensions;
[assembly: AssemblyTitle("Terradue.Tep")]
[assembly: AssemblyDescription("Terradue Tep .Net library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Terradue")]
[assembly: AssemblyProduct("Terradue.Tep")]
[assembly: AssemblyCopyright("Terradue")]
[assembly: AssemblyAuthors("Enguerran Boissier")]
[assembly: AssemblyProjectUrl("https://git.terradue.com/sugar/Terradue.Tep")]
[assembly: AssemblyLicenseUrl("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.7")]
[assembly: AssemblyInformationalVersion("1.3.7")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] | /*!
\namespace Terradue.Tep
@{
Terradue.Tep Software Package provides with all the functionalities specific to the TEP.
\xrefitem sw_version "Versions" "Software Package Version" 1.3.6
\xrefitem sw_link "Links" "Software Package List" [Terradue.Tep](https://git.terradue.com/sugar/Terradue.Tep)
\xrefitem sw_license "License" "Software License" [AGPL](https://git.terradue.com/sugar/Terradue.Tep/LICENSE)
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch
\xrefitem sw_req "Require" "Software Dependencies" \ref ServiceStack
\xrefitem sw_req "Require" "Software Dependencies" \ref log4net
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Portal
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Authentication.Umsso
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Cloud
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Github
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Metadata.EarthObservation
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.News
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenNebula
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.GeoJson
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.RdfEO
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.Tumblr
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.Twitter
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Ogc.OwsContext
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Syndication
\xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.WebService.Model
\ingroup Tep
@}
*/
/*!
\defgroup Tep Tep Modules
@{
This is a super component that encloses all Thematic Exploitation Platform related functional components.
Their main functionnalities are targeted to enhance the basic \ref Core functionalities for the thematic usage of the plaform.
@}
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using NuGet4Mono.Extensions;
[assembly: AssemblyTitle("Terradue.Tep")]
[assembly: AssemblyDescription("Terradue Tep .Net library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Terradue")]
[assembly: AssemblyProduct("Terradue.Tep")]
[assembly: AssemblyCopyright("Terradue")]
[assembly: AssemblyAuthors("Enguerran Boissier")]
[assembly: AssemblyProjectUrl("https://git.terradue.com/sugar/Terradue.Tep")]
[assembly: AssemblyLicenseUrl("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.6")]
[assembly: AssemblyInformationalVersion("1.3.6")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] | agpl-3.0 | C# |
4dd3daed8828f49f87f9d4843c2872f2c0384080 | Remove unused usings. | FloodProject/flood,FloodProject/flood,FloodProject/flood | src/Editor/Editor.Client/Editor.cs | src/Editor/Editor.Client/Editor.cs | using Flood.Editor.Client.Gui;
using System;
using Flood.Network;
using Flood.Packages;
using Flood.RPC;
namespace Flood.Editor.Client
{
public sealed class Editor : IDisposable
{
public MainWindow MainWindow { get; private set; }
public Window PaneWindow { get; private set; }
public GwenRenderer GuiRenderer { get; private set; }
public GwenInput GuiInput { get; private set; }
public Engine Engine { get; private set; }
public ServerManager ServerManager { get; private set; }
public Editor()
{
Engine = FloodEngine.GetEngine();
InitializeGui();
ServerManager = new ServerManager();
ServerManager.CreateBuiltinServer();
}
public void Dispose()
{
MainWindow.Dispose();
GuiRenderer.Dispose();
}
void InitializeGui()
{
GuiRenderer = new GwenRenderer();
MainWindow = new MainWindow();
MainWindow.Init(GuiRenderer, "DefaultSkin.png",new Flood.GUI.Font("Vera.ttf",16));
GuiInput = new GwenInput(Engine.InputManager);
GuiInput.Initialize(MainWindow.Canvas);
}
public void Render(RenderBlock rb)
{
GuiRenderer.Clear();
MainWindow.Render();
GuiRenderer.Render(rb);
}
public void Update()
{
}
public void SetSize(int x, int y)
{
MainWindow.Canvas.SetSize(x, y);
}
}
} | using Flood.Editor.Client.Gui;
using System;
using System.IO;
using System.Reflection;
using Flood.Network;
using Flood.Packages;
using Flood.RPC;
namespace Flood.Editor.Client
{
public sealed class Editor : IDisposable
{
public MainWindow MainWindow { get; private set; }
public Window PaneWindow { get; private set; }
public GwenRenderer GuiRenderer { get; private set; }
public GwenInput GuiInput { get; private set; }
public Engine Engine { get; private set; }
public ServerManager ServerManager { get; private set; }
public Editor()
{
Engine = FloodEngine.GetEngine();
InitializeGui();
ServerManager = new ServerManager();
ServerManager.CreateBuiltinServer();
}
public void Dispose()
{
MainWindow.Dispose();
GuiRenderer.Dispose();
}
void InitializeGui()
{
GuiRenderer = new GwenRenderer();
MainWindow = new MainWindow();
MainWindow.Init(GuiRenderer, "DefaultSkin.png",new Flood.GUI.Font("Vera.ttf",16));
GuiInput = new GwenInput(Engine.InputManager);
GuiInput.Initialize(MainWindow.Canvas);
}
public void Render(RenderBlock rb)
{
GuiRenderer.Clear();
MainWindow.Render();
GuiRenderer.Render(rb);
}
public void Update()
{
}
public void SetSize(int x, int y)
{
MainWindow.Canvas.SetSize(x, y);
}
}
} | bsd-2-clause | C# |
2a231695d005fc84a5d0ebd79c8afc4543d3707f | Update link to Update function | DotNetRu/App,DotNetRu/App | DotNetRu.Utils/Config/AppConfig.cs | DotNetRu.Utils/Config/AppConfig.cs | using System.Text;
using DotNetRu.Utils.Helpers;
using Newtonsoft.Json;
namespace DotNetRu.Clients.UI
{
public class AppConfig
{
public string AppCenterAndroidKey { get; set; }
public string AppCenteriOSKey { get; set; }
public string PushNotificationsChannel { get; set; }
public string UpdateFunctionURL { get; set; }
public string TweetFunctionUrl { get; set; }
public static AppConfig GetConfig()
{
#if DEBUG
return new AppConfig()
{
AppCenterAndroidKey = "6f9a7703-8ca4-477e-9558-7e095f7d20aa",
AppCenteriOSKey = "1e7f311f-1055-4ec9-8b00-0302015ab8ae",
PushNotificationsChannel = "AuditUpdateDebug",
UpdateFunctionURL = "https://dotnetruazure.azurewebsites.net/api/Update",
TweetFunctionUrl = "https://dotnettweetservice.azurewebsites.net/api/Tweets"
};
#endif
#pragma warning disable CS0162 // Unreachable code detected
var configBytes = ResourceHelper.ExtractResource("DotNetRu.Utils.Config.config.json");
var configBytesAsString = Encoding.UTF8.GetString(configBytes);
return JsonConvert.DeserializeObject<AppConfig>(configBytesAsString);
#pragma warning restore CS0162 // Unreachable code detected
}
}
}
| using System.Text;
using DotNetRu.Utils.Helpers;
using Newtonsoft.Json;
namespace DotNetRu.Clients.UI
{
public class AppConfig
{
public string AppCenterAndroidKey { get; set; }
public string AppCenteriOSKey { get; set; }
public string PushNotificationsChannel { get; set; }
public string UpdateFunctionURL { get; set; }
public string TweetFunctionUrl { get; set; }
public static AppConfig GetConfig()
{
#if DEBUG
return new AppConfig()
{
AppCenterAndroidKey = "6f9a7703-8ca4-477e-9558-7e095f7d20aa",
AppCenteriOSKey = "1e7f311f-1055-4ec9-8b00-0302015ab8ae",
PushNotificationsChannel = "AuditUpdateDebug",
UpdateFunctionURL = "https://dotnetruapp.azurewebsites.net/api/Update",
TweetFunctionUrl = "https://dotnettweetservice.azurewebsites.net/api/Tweets"
};
#endif
#pragma warning disable CS0162 // Unreachable code detected
var configBytes = ResourceHelper.ExtractResource("DotNetRu.Utils.Config.config.json");
var configBytesAsString = Encoding.UTF8.GetString(configBytes);
return JsonConvert.DeserializeObject<AppConfig>(configBytesAsString);
#pragma warning restore CS0162 // Unreachable code detected
}
}
}
| mit | C# |
716043753213e23e6e245ff16c25eda04671a115 | Remove invalid FileChooserDialog constructor | openmedicus/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,orion75/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,antoniusriha/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,Gankov/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp | gtk/FileChooserDialog.cs | gtk/FileChooserDialog.cs | // Gtk.FileChooserDialog.cs - Gtk FileChooserDialog customizations
//
// Authors: Todd Berman <tberman@off.net>
// Jeroen Zwartepoorte <jeroen@xs4all.nl>
// Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2004 Todd Berman, Jeroen Zwartepoorte
// Copyright (c) 2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace Gtk {
using System;
using System.Runtime.InteropServices;
public partial class FileChooserDialog {
[DllImport ("libgtk-win32-3.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_file_chooser_dialog_new(IntPtr title, IntPtr parent, int action, IntPtr nil);
public FileChooserDialog (string title, Window parent, FileChooserAction action, params object[] button_data) : base (IntPtr.Zero)
{
if (GetType () != typeof (FileChooserDialog)) {
CreateNativeObject (new string[0], new GLib.Value[0]);
Title = title;
if (parent != null)
TransientFor = parent;
Action = action;
} else {
IntPtr native = GLib.Marshaller.StringToPtrGStrdup (title);
Raw = gtk_file_chooser_dialog_new (native, parent == null ? IntPtr.Zero : parent.Handle, (int)action, IntPtr.Zero);
GLib.Marshaller.Free (native);
}
for (int i = 0; i < button_data.Length - 1; i += 2)
AddButton ((string) button_data [i], (int) button_data [i + 1]);
}
}
}
| // Gtk.FileChooserDialog.cs - Gtk FileChooserDialog customizations
//
// Authors: Todd Berman <tberman@off.net>
// Jeroen Zwartepoorte <jeroen@xs4all.nl>
// Mike Kestner <mkestner@novell.com>
//
// Copyright (c) 2004 Todd Berman, Jeroen Zwartepoorte
// Copyright (c) 2005 Novell, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the Lesser GNU General
// Public License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
namespace Gtk {
using System;
using System.Runtime.InteropServices;
public partial class FileChooserDialog {
[DllImport ("libgtk-win32-3.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_file_chooser_dialog_new(IntPtr title, IntPtr parent, int action, IntPtr nil);
public FileChooserDialog (string title, Window parent, FileChooserAction action, params object[] button_data) : base (IntPtr.Zero)
{
if (GetType () != typeof (FileChooserDialog)) {
CreateNativeObject (new string[0], new GLib.Value[0]);
Title = title;
if (parent != null)
TransientFor = parent;
Action = action;
} else {
IntPtr native = GLib.Marshaller.StringToPtrGStrdup (title);
Raw = gtk_file_chooser_dialog_new (native, parent == null ? IntPtr.Zero : parent.Handle, (int)action, IntPtr.Zero);
GLib.Marshaller.Free (native);
}
for (int i = 0; i < button_data.Length - 1; i += 2)
AddButton ((string) button_data [i], (int) button_data [i + 1]);
}
[DllImport ("libgtk-win32-3.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gtk_file_chooser_dialog_new_with_backend(IntPtr title, IntPtr parent, int action, IntPtr backend, IntPtr nil);
public FileChooserDialog (string backend, string title, Window parent, FileChooserAction action, params object[] button_data) : base (IntPtr.Zero)
{
if (GetType () != typeof (FileChooserDialog)) {
CreateNativeObject (new string[] { "file-system-backend" }, new GLib.Value[] { new GLib.Value (backend) } );
Title = title;
if (parent != null)
TransientFor = parent;
Action = action;
} else {
IntPtr ntitle = GLib.Marshaller.StringToPtrGStrdup (title);
IntPtr nbackend = GLib.Marshaller.StringToPtrGStrdup (backend);
Raw = gtk_file_chooser_dialog_new_with_backend (ntitle, parent == null ? IntPtr.Zero : parent.Handle, (int)action, nbackend, IntPtr.Zero);
GLib.Marshaller.Free (ntitle);
GLib.Marshaller.Free (nbackend);
}
for (int i = 0; i < button_data.Length - 1; i += 2)
AddButton ((string) button_data [i], (int) button_data [i + 1]);
}
}
}
| lgpl-2.1 | C# |
7af2e04a49944e7b12849a2af609bbeec1ef2438 | Update example, add long tap | mrxten/XamEffects | src/Test/XamExample/MyPage.xaml.cs | src/Test/XamExample/MyPage.xaml.cs | using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace XamExample {
public partial class MyPage : ContentPage {
public MyPage() {
InitializeComponent();
var c = 0;
XamEffects.TouchEffect.SetColor(plus, Color.White);
XamEffects.Commands.SetTap(plus, new Command(() => {
c++;
counter.Text = $"Touches: {c}";
}));
XamEffects.TouchEffect.SetColor(minus, Color.White);
XamEffects.Commands.SetLongTap(minus, new Command(() => {
c--;
counter.Text = $"Touches: {c}";
}));
}
}
}
| using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace XamExample {
public partial class MyPage : ContentPage {
public MyPage() {
InitializeComponent();
var c = 0;
XamEffects.TouchEffect.SetColor(plus, Color.White);
XamEffects.Commands.SetTap(plus, new Command(() => {
c++;
counter.Text = $"Touches: {c}";
}));
XamEffects.TouchEffect.SetColor(minus, Color.White);
XamEffects.Commands.SetTap(minus, new Command(() => {
c--;
counter.Text = $"Touches: {c}";
}));
}
}
}
| mit | C# |
740f06576c1e9ec694efec00e2ed8d212374e91b | Update copyright (#61) | SonarSource-DotNet/sonarqube-roslyn-sdk,SonarSource-VisualStudio/sonarqube-roslyn-sdk | AssemblyInfo.Shared.cs | AssemblyInfo.Shared.cs | //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
| //-----------------------------------------------------------------------
// <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
| mit | C# |
a2116bdf5dc0458cc275369870f779117124caba | Set Default Font to something that should be on all systems | luiscubal/XwtPlus.TextEditor,cra0zy/XwtPlus.TextEditor | XwtPlus.TextEditor/TextEditorOptions.cs | XwtPlus.TextEditor/TextEditorOptions.cs | using Mono.TextEditor.Highlighting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xwt.Drawing;
namespace XwtPlus.TextEditor
{
public class TextEditorOptions
{
public Font EditorFont = Font.SystemMonospaceFont;
public IndentStyle IndentStyle = IndentStyle.Auto;
public int TabSize = 4;
public Color Background = Colors.White;
public ColorScheme ColorScheme = SyntaxModeService.DefaultColorStyle;
public bool CurrentLineNumberBold = true;
}
}
| using Mono.TextEditor.Highlighting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xwt.Drawing;
namespace XwtPlus.TextEditor
{
public class TextEditorOptions
{
public Font EditorFont = Font.FromName("Consolas 13");
public IndentStyle IndentStyle = IndentStyle.Auto;
public int TabSize = 4;
public Color Background = Colors.White;
public ColorScheme ColorScheme = SyntaxModeService.DefaultColorStyle;
public bool CurrentLineNumberBold = true;
}
}
| mit | C# |
d5663124ea7651642e88934287f736ab4dbac649 | Add token type "Name" | BERef/BibTeXLibrary | BibTeXLibrary/Token.cs | BibTeXLibrary/Token.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BibTeXLibrary
{
internal struct Token
{
public TokenType Type;
public string Value;
public Token(TokenType type, string value = "")
{
Type = type;
Value = value;
Debug.WriteLine(type.ToString() + "\t" + value);
}
}
enum TokenType
{
Start,
Name,
String,
Quotation,
LeftBrace,
RightBrace,
Equal,
Comma,
Concatenation
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BibTeXLibrary
{
internal struct Token
{
public TokenType Type;
public string Value;
public Token(TokenType type, string value = "")
{
Type = type;
Value = value;
Debug.WriteLine(type.ToString() + "\t" + value);
}
}
enum TokenType
{
Start,
String,
Number,
Quotation,
LeftBrace,
RightBrace,
Equal,
Comma,
Concatenation
}
}
| mit | C# |
8952fcefebdd71a3fb1fa0111c2239c21682a5f4 | Remove station bounding sphere | iridinite/shiftdrive | Client/SpaceStation.cs | Client/SpaceStation.cs | /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
namespace ShiftDrive {
internal sealed class SpaceStation : Ship {
public SpaceStation(GameState world) : base(world) {
type = ObjectType.Station;
bounding = 0f;
}
protected override void OnCollision(GameObject other, Vector2 normal, float penetration) {
// no action; station doesn't care about collision
}
public override void Update(float deltaTime) {
// station never moves
throttle = 0f;
facing = 0f;
steering = 0f;
// base update
base.Update(deltaTime);
}
}
}
| /*
** Project ShiftDrive
** (C) Mika Molenkamp, 2016.
*/
using Microsoft.Xna.Framework;
namespace ShiftDrive {
internal sealed class SpaceStation : Ship {
public SpaceStation(GameState world) : base(world) {
type = ObjectType.Station;
bounding = 100f;
}
protected override void OnCollision(GameObject other, Vector2 normal, float penetration) {
// no action; station doesn't care about collision
}
public override void Update(float deltaTime) {
// station never moves
throttle = 0f;
facing = 0f;
steering = 0f;
// base update
base.Update(deltaTime);
}
}
}
| bsd-3-clause | C# |
940ae5f081838fd4238b49bae0e25cce901384e8 | Bump version | pleonex/deblocus,pleonex/deblocus | Deblocus/Properties/AssemblyInfo.cs | Deblocus/Properties/AssemblyInfo.cs | //
// AssemblyInfo.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Deblocus")]
[assembly: AssemblyDescription("A card manager for students.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright (c) 2015 pleonex")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("0.2.0.*")]
| //
// AssemblyInfo.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Deblocus")]
[assembly: AssemblyDescription("A card manager for students.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright (c) 2015 pleonex")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("0.1.0.*")]
| agpl-3.0 | C# |
796449ededb584814c2a4794ae00cdd4b1ab00fd | Fix for flaky test. | JaCraig/BigBookOfDataTypes,JaCraig/BigBookOfDataTypes,JaCraig/BigBookOfDataTypes | test/BigBook.Tests/TaskQueueTests.cs | test/BigBook.Tests/TaskQueueTests.cs | using System.Linq;
using System.Text;
using System.Threading;
using Xunit;
namespace BigBook.Tests
{
public class TaskQueueTests
{
private readonly double EPSILON = 0.0001d;
[Fact]
public void MoreComplexTasks()
{
var Results = new double[100];
var TestObject = new TaskQueue<int>(4, x => { Results[x] = 2 * F(1); return true; });
for (int x = 0; x < 100; ++x)
{
Assert.True(TestObject.Enqueue(x));
}
while (!TestObject.IsComplete)
{
Thread.Sleep(100);
}
Assert.True(Results.All(x => System.Math.Abs(x - 3.14159d) < EPSILON));
}
[Fact]
public void SimpleTasks()
{
var Builder = new StringBuilder();
int[] Temp = { 0, 0, 1, 2, 3 };
object LockObject = new object();
var TestObject = new TaskQueue<int>(4, x =>
{
lock (LockObject)
{
Builder.Append(x); return true;
}
});
for (int x = 0; x < Temp.Length; ++x)
{
Assert.True(TestObject.Enqueue(Temp[x]));
}
while (!TestObject.IsComplete)
{
Thread.Sleep(100);
}
var OrderedString = new string(Builder.ToString().OrderBy(x => x).ToArray());
Assert.Equal("00123", OrderedString);
}
private double F(int i)
{
if (i == 1000)
{
return 1;
}
return 1 + (i / ((2.0 * i) + 1) * F(i + 1));
}
}
} | using System.Linq;
using System.Text;
using System.Threading;
using Xunit;
namespace BigBook.Tests
{
public class TaskQueueTests
{
private readonly double EPSILON = 0.0001d;
[Fact]
public void MoreComplexTasks()
{
var Results = new double[100];
var TestObject = new TaskQueue<int>(4, x => { Results[x] = 2 * F(1); return true; });
for (int x = 0; x < 100; ++x)
{
Assert.True(TestObject.Enqueue(x));
}
while (!TestObject.IsComplete)
{
Thread.Sleep(100);
}
Assert.True(Results.All(x => System.Math.Abs(x - 3.14159d) < EPSILON));
}
[Fact]
public void SimpleTasks()
{
var Builder = new StringBuilder();
int[] Temp = { 0, 0, 1, 2, 3 };
var TestObject = new TaskQueue<int>(4, x => { Builder.Append(x); return true; });
for (int x = 0; x < Temp.Length; ++x)
{
Assert.True(TestObject.Enqueue(Temp[x]));
}
while (!TestObject.IsComplete)
{
Thread.Sleep(100);
}
var OrderedString = new string(Builder.ToString().OrderBy(x => x).ToArray());
Assert.Equal("00123", OrderedString);
}
private double F(int i)
{
if (i == 1000)
{
return 1;
}
return 1 + (i / ((2.0 * i) + 1) * F(i + 1));
}
}
} | apache-2.0 | C# |
8e8fdc7643afa27ffec62094b2d9f5ae6696b453 | Build number removed from the version string, as this creates problems with NuGet dependencies. | thedmi/MayBee,thedmi/Equ,thedmi/Finalist,thedmi/Equ,thedmi/Finalist,thedmi/MiniGuard | Sources/VersionInfo.cs | Sources/VersionInfo.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="VersionInfo.cs" company="Dani Michel">
// Dani Michel 2013
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyCompany("Dani Michel")]
[assembly: System.Reflection.AssemblyCopyright("Copyright © 2014")]
[assembly: System.Reflection.AssemblyVersion("0.8.1")]
[assembly: System.Reflection.AssemblyInformationalVersion("Belt 0.8.1")] | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="VersionInfo.cs" company="Dani Michel">
// Dani Michel 2013
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
[assembly: System.Reflection.AssemblyCompany("Dani Michel")]
[assembly: System.Reflection.AssemblyCopyright("Copyright © 2014")]
[assembly: System.Reflection.AssemblyVersion("0.8.0.*")]
[assembly: System.Reflection.AssemblyInformationalVersion("Belt 0.8.0")] | mit | C# |
938b0222a4083c7e165124de7e9ca092bdf58c32 | update sample | maximrub/Xamarin | Sample/Friends/Friends/App.xaml.cs | Sample/Friends/Friends/App.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Exrin.Abstraction;
using Exrin.Framework;
using Exrin.IOC;
using Friends.Locator;
using Xamarin.Forms;
namespace Friends
{
public partial class App : Application
{
public App(PlatformInitializer i_PlatformInitializer)
{
InitializeComponent();
Exrin.IOC.LightInjectProvider.Init(i_PlatformInitializer, new FormsInitializer());
IInjectionProxy injectionProxy = Bootstrapper.Instance.Init();
INavigationService navigationService = injectionProxy.Get<INavigationService>();
navigationService.Navigate(new StackOptions()
{
StackChoice = eStack.Authentication
});
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Exrin.Abstraction;
using Exrin.Framework;
using Exrin.IOC;
using Friends.Locator;
using Xamarin.Forms;
namespace Friends
{
public partial class App : Application
{
public App(PlatformInitializer i_PlatformInitializer)
{
InitializeComponent();
Exrin.IOC.LightInjectProvider.Init(i_PlatformInitializer, new FormsInitializer());
}
protected override void OnStart()
{
IInjectionProxy injectionProxy = Bootstrapper.Instance.Init();
INavigationService navigationService = injectionProxy.Get<INavigationService>();
navigationService.Navigate(new StackOptions()
{
StackChoice = eStack.Authentication
});
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| mit | C# |
22af0f860a0eb99f0cfc96481d7e6dc1b4a4f1ed | Add non-wrapped example | refactorsaurusrex/FluentConsole | TestConsole/Program.cs | TestConsole/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentConsole.Library;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
FluentConsoleSettings.LineWrapOption = LineWrapOption.Manual;
FluentConsoleSettings.LineWrapWidth = 25;
"This is a really long string, longer than the default width of the Console window buffer, followed by two line breaks. With any luck, this will be displayed as expected!".WriteLine(2);
FluentConsoleSettings.LineWrapOption = LineWrapOption.Auto;
"This is a really long string, longer than the default width of the Console window buffer, followed by two line breaks. With any luck, this will be displayed as expected!".WriteLine(2);
FluentConsoleSettings.LineWrapOption = LineWrapOption.Off;
"This is a really long string, longer than the default width of the Console window buffer, followed by two line breaks. With any luck, this will be displayed as expected!".WriteLine(2);
FluentConsoleSettings.LineWrapOption = LineWrapOption.Auto;
"This is a much shorter string, with zero line breaks.".WriteLine();
"This is a green string with one line break.".WriteLine(ConsoleColor.Green, 1);
"A red string, with zero breaks, and waits after printing".WriteLineWait(ConsoleColor.Red);
"This is a much shorter string, with zero line breaks.".WriteLineWait();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentConsole.Library;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
FluentConsoleSettings.LineWrapOption = LineWrapOption.Manual;
FluentConsoleSettings.LineWrapWidth = 25;
"This is a really long string, longer than the default width of the Console window buffer, followed by two line breaks. With any luck, this will be displayed as expected!".WriteLine(2);
FluentConsoleSettings.LineWrapOption = LineWrapOption.Auto;
"This is a really long string, longer than the default width of the Console window buffer, followed by two line breaks. With any luck, this will be displayed as expected!".WriteLine(2);
"This is a much shorter string, with zero line breaks.".WriteLine();
"This is a green string with one line break.".WriteLine(ConsoleColor.Green, 1);
"A red string, with zero breaks, and waits after printing".WriteLineWait(ConsoleColor.Red);
"This is a much shorter string, with zero line breaks.".WriteLineWait();
}
}
}
| mit | C# |
57516d2fc5b26bda284b550d3acd4af917f5ec93 | Remove unused using | appharbor/appharbor-cli | src/AppHarbor/CommandDispatcher.cs | src/AppHarbor/CommandDispatcher.cs | using System;
using System.Linq;
using Castle.MicroKernel;
namespace AppHarbor
{
public class CommandDispatcher
{
private readonly ITypeNameMatcher _typeNameMatcher;
private readonly IKernel _kernel;
public CommandDispatcher(ITypeNameMatcher typeNameMatcher, IKernel kernel)
{
_typeNameMatcher = typeNameMatcher;
_kernel = kernel;
}
public void Dispatch(string[] args)
{
var matchingType = _typeNameMatcher.GetMatchedType(args.Any() ? args[0] : "help");
var command = (ICommand)_kernel.Resolve(matchingType);
try
{
command.Execute(args.Skip(1).ToArray());
}
catch (CommandException exception)
{
Console.WriteLine(string.Format("Error: {0}", exception.Message));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Castle.MicroKernel;
namespace AppHarbor
{
public class CommandDispatcher
{
private readonly ITypeNameMatcher _typeNameMatcher;
private readonly IKernel _kernel;
public CommandDispatcher(ITypeNameMatcher typeNameMatcher, IKernel kernel)
{
_typeNameMatcher = typeNameMatcher;
_kernel = kernel;
}
public void Dispatch(string[] args)
{
var matchingType = _typeNameMatcher.GetMatchedType(args.Any() ? args[0] : "help");
var command = (ICommand)_kernel.Resolve(matchingType);
try
{
command.Execute(args.Skip(1).ToArray());
}
catch (CommandException exception)
{
Console.WriteLine(string.Format("Error: {0}", exception.Message));
}
}
}
}
| mit | C# |
d8e9ab085fe98d047369477c2a3c76bec69753e2 | Work around an MCG bug (dotnet/corert#6658) | ericstj/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,BrennanConroy/corefx,ptoonen/corefx,ptoonen/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,BrennanConroy/corefx,shimingsg/corefx,BrennanConroy/corefx,ViktorHofer/corefx,wtgodbe/corefx,shimingsg/corefx,ptoonen/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,ViktorHofer/corefx,ptoonen/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ptoonen/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,ericstj/corefx,wtgodbe/corefx,ericstj/corefx,shimingsg/corefx,ptoonen/corefx,ViktorHofer/corefx,wtgodbe/corefx,wtgodbe/corefx | src/Common/src/CoreLib/System/Collections/IEnumerable.cs | src/Common/src/CoreLib/System/Collections/IEnumerable.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.
using System;
using System.Runtime.InteropServices;
namespace System.Collections
{
#if !PROJECTN // Hitting a bug in MCG, see VSO:743654
[Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
[ComVisible(true)]
#endif
public interface IEnumerable
{
// Returns an IEnumerator for this enumerable Object. The enumerator provides
// a simple way to access all the contents of a collection.
IEnumerator GetEnumerator();
}
}
| // 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.
using System;
using System.Runtime.InteropServices;
namespace System.Collections
{
[Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
[ComVisible(true)]
public interface IEnumerable
{
// Returns an IEnumerator for this enumerable Object. The enumerator provides
// a simple way to access all the contents of a collection.
IEnumerator GetEnumerator();
}
}
| mit | C# |
9a347a84d46877f78bf8c57d04aa0fcf78587a4b | rename private variable | rohmano/azure-powershell,mayurid/azure-powershell,zaevans/azure-powershell,yadavbdev/azure-powershell,zhencui/azure-powershell,nemanja88/azure-powershell,juvchan/azure-powershell,TaraMeyer/azure-powershell,praveennet/azure-powershell,seanbamsft/azure-powershell,enavro/azure-powershell,AzureRT/azure-powershell,SarahRogers/azure-powershell,nemanja88/azure-powershell,shuagarw/azure-powershell,yantang-msft/azure-powershell,DeepakRajendranMsft/azure-powershell,tonytang-microsoft-com/azure-powershell,arcadiahlyy/azure-powershell,TaraMeyer/azure-powershell,pankajsn/azure-powershell,atpham256/azure-powershell,naveedaz/azure-powershell,SarahRogers/azure-powershell,AzureRT/azure-powershell,DeepakRajendranMsft/azure-powershell,AzureRT/azure-powershell,PashaPash/azure-powershell,DeepakRajendranMsft/azure-powershell,jasper-schneider/azure-powershell,AzureAutomationTeam/azure-powershell,rhencke/azure-powershell,stankovski/azure-powershell,hungmai-msft/azure-powershell,Matt-Westphal/azure-powershell,praveennet/azure-powershell,hallihan/azure-powershell,stankovski/azure-powershell,seanbamsft/azure-powershell,bgold09/azure-powershell,rohmano/azure-powershell,stankovski/azure-powershell,SarahRogers/azure-powershell,seanbamsft/azure-powershell,hovsepm/azure-powershell,rohmano/azure-powershell,naveedaz/azure-powershell,akurmi/azure-powershell,bgold09/azure-powershell,pomortaz/azure-powershell,atpham256/azure-powershell,hallihan/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,atpham256/azure-powershell,rohmano/azure-powershell,zaevans/azure-powershell,AzureRT/azure-powershell,nickheppleston/azure-powershell,ClogenyTechnologies/azure-powershell,CamSoper/azure-powershell,oaastest/azure-powershell,seanbamsft/azure-powershell,enavro/azure-powershell,Matt-Westphal/azure-powershell,jianghaolu/azure-powershell,nickheppleston/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,stankovski/azure-powershell,CamSoper/azure-powershell,akurmi/azure-powershell,yadavbdev/azure-powershell,enavro/azure-powershell,dulems/azure-powershell,yantang-msft/azure-powershell,shuagarw/azure-powershell,pankajsn/azure-powershell,SarahRogers/azure-powershell,juvchan/azure-powershell,rohmano/azure-powershell,pelagos/azure-powershell,nemanja88/azure-powershell,pomortaz/azure-powershell,pankajsn/azure-powershell,naveedaz/azure-powershell,enavro/azure-powershell,dominiqa/azure-powershell,yoavrubin/azure-powershell,jtlibing/azure-powershell,jianghaolu/azure-powershell,chef-partners/azure-powershell,DeepakRajendranMsft/azure-powershell,AzureRT/azure-powershell,pankajsn/azure-powershell,ClogenyTechnologies/azure-powershell,Matt-Westphal/azure-powershell,CamSoper/azure-powershell,dulems/azure-powershell,arcadiahlyy/azure-powershell,pelagos/azure-powershell,nemanja88/azure-powershell,AzureAutomationTeam/azure-powershell,hallihan/azure-powershell,dominiqa/azure-powershell,oaastest/azure-powershell,dominiqa/azure-powershell,stankovski/azure-powershell,dominiqa/azure-powershell,oaastest/azure-powershell,zhencui/azure-powershell,akurmi/azure-powershell,AzureAutomationTeam/azure-powershell,rhencke/azure-powershell,nickheppleston/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,yoavrubin/azure-powershell,hovsepm/azure-powershell,shuagarw/azure-powershell,krkhan/azure-powershell,akurmi/azure-powershell,jianghaolu/azure-powershell,tonytang-microsoft-com/azure-powershell,rhencke/azure-powershell,kagamsft/azure-powershell,tonytang-microsoft-com/azure-powershell,CamSoper/azure-powershell,jianghaolu/azure-powershell,hallihan/azure-powershell,krkhan/azure-powershell,jasper-schneider/azure-powershell,jtlibing/azure-powershell,CamSoper/azure-powershell,mayurid/azure-powershell,nemanja88/azure-powershell,devigned/azure-powershell,yadavbdev/azure-powershell,alfantp/azure-powershell,ailn/azure-powershell,ailn/azure-powershell,AzureRT/azure-powershell,ailn/azure-powershell,hallihan/azure-powershell,ankurchoubeymsft/azure-powershell,PashaPash/azure-powershell,zhencui/azure-powershell,mayurid/azure-powershell,hovsepm/azure-powershell,zhencui/azure-powershell,haocs/azure-powershell,shuagarw/azure-powershell,juvchan/azure-powershell,alfantp/azure-powershell,bgold09/azure-powershell,krkhan/azure-powershell,jasper-schneider/azure-powershell,hungmai-msft/azure-powershell,DeepakRajendranMsft/azure-powershell,dulems/azure-powershell,ailn/azure-powershell,hovsepm/azure-powershell,nickheppleston/azure-powershell,pomortaz/azure-powershell,arcadiahlyy/azure-powershell,kagamsft/azure-powershell,TaraMeyer/azure-powershell,ailn/azure-powershell,devigned/azure-powershell,oaastest/azure-powershell,yantang-msft/azure-powershell,praveennet/azure-powershell,pomortaz/azure-powershell,pelagos/azure-powershell,yantang-msft/azure-powershell,jianghaolu/azure-powershell,kagamsft/azure-powershell,yoavrubin/azure-powershell,yoavrubin/azure-powershell,oaastest/azure-powershell,chef-partners/azure-powershell,PashaPash/azure-powershell,nickheppleston/azure-powershell,rohmano/azure-powershell,yantang-msft/azure-powershell,chef-partners/azure-powershell,hungmai-msft/azure-powershell,atpham256/azure-powershell,hungmai-msft/azure-powershell,yadavbdev/azure-powershell,jtlibing/azure-powershell,TaraMeyer/azure-powershell,haocs/azure-powershell,AzureAutomationTeam/azure-powershell,krkhan/azure-powershell,seanbamsft/azure-powershell,bgold09/azure-powershell,rhencke/azure-powershell,bgold09/azure-powershell,mayurid/azure-powershell,akurmi/azure-powershell,zhencui/azure-powershell,Matt-Westphal/azure-powershell,jtlibing/azure-powershell,krkhan/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,jasper-schneider/azure-powershell,SarahRogers/azure-powershell,ankurchoubeymsft/azure-powershell,alfantp/azure-powershell,zhencui/azure-powershell,hovsepm/azure-powershell,naveedaz/azure-powershell,Matt-Westphal/azure-powershell,devigned/azure-powershell,ankurchoubeymsft/azure-powershell,shuagarw/azure-powershell,alfantp/azure-powershell,zaevans/azure-powershell,seanbamsft/azure-powershell,ClogenyTechnologies/azure-powershell,ankurchoubeymsft/azure-powershell,kagamsft/azure-powershell,pelagos/azure-powershell,arcadiahlyy/azure-powershell,enavro/azure-powershell,pankajsn/azure-powershell,arcadiahlyy/azure-powershell,alfantp/azure-powershell,zaevans/azure-powershell,devigned/azure-powershell,mayurid/azure-powershell,zaevans/azure-powershell,haocs/azure-powershell,PashaPash/azure-powershell,yantang-msft/azure-powershell,chef-partners/azure-powershell,dulems/azure-powershell,atpham256/azure-powershell,dulems/azure-powershell,pomortaz/azure-powershell,rhencke/azure-powershell,chef-partners/azure-powershell,AzureAutomationTeam/azure-powershell,dominiqa/azure-powershell,kagamsft/azure-powershell,naveedaz/azure-powershell,devigned/azure-powershell,ankurchoubeymsft/azure-powershell,pankajsn/azure-powershell,tonytang-microsoft-com/azure-powershell,PashaPash/azure-powershell,jtlibing/azure-powershell,TaraMeyer/azure-powershell,juvchan/azure-powershell,juvchan/azure-powershell,yadavbdev/azure-powershell,yoavrubin/azure-powershell,tonytang-microsoft-com/azure-powershell,jasper-schneider/azure-powershell,pelagos/azure-powershell,hungmai-msft/azure-powershell,praveennet/azure-powershell,haocs/azure-powershell,haocs/azure-powershell,praveennet/azure-powershell | src/ResourceManager/Network/Commands.NetworkResourceProvider/Common/NetworkBaseClient.cs | src/ResourceManager/Network/Commands.NetworkResourceProvider/Common/NetworkBaseClient.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.WindowsAzure.Commands.Utilities.Common;
namespace Microsoft.Azure.Commands.NetworkResourceProvider
{
public abstract class NetworkBaseClient : AzurePSCmdlet
{
private NetworkClient _networkClient;
public NetworkClient NetworkClient
{
get
{
if (_networkClient == null)
{
_networkClient = new NetworkClient(CurrentContext)
{
VerboseLogger = WriteVerboseWithTimestamp,
ErrorLogger = WriteErrorWithTimestamp,
WarningLogger = WriteWarningWithTimestamp
};
}
return _networkClient;
}
set { _networkClient = value; }
}
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
NetworkResourceManagerProfile.Initialize();
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.WindowsAzure.Commands.Utilities.Common;
namespace Microsoft.Azure.Commands.NetworkResourceProvider
{
public abstract class NetworkBaseClient : AzurePSCmdlet
{
public NetworkClient networkClient;
public NetworkClient NetworkClient
{
get
{
if (networkClient == null)
{
networkClient = new NetworkClient(CurrentContext)
{
VerboseLogger = WriteVerboseWithTimestamp,
ErrorLogger = WriteErrorWithTimestamp,
WarningLogger = WriteWarningWithTimestamp
};
}
return networkClient;
}
set { networkClient = value; }
}
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
NetworkResourceManagerProfile.Initialize();
}
}
}
| apache-2.0 | C# |
3af4f33b5d483898e00fa1503e791176e7e361e6 | Update TestPlainText.cs | lunet-io/markdig | src/Markdig.Tests/TestPlainText.cs | src/Markdig.Tests/TestPlainText.cs | using NUnit.Framework;
namespace Markdig.Tests
{
[TestFixture]
public class TestPlainText
{
[Test]
public void TestPlain()
{
var markdownText = "*Hello*, [world](http://example.com)!";
var expected = "Hello, world!\n";
var actual = Markdown.ToPlainText(markdownText);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(/* markdownText: */ "foo bar", /* expected: */ "foo bar\n")]
[TestCase(/* markdownText: */ "foo\nbar", /* expected: */ "foo\nbar\n")]
[TestCase(/* markdownText: */ "*foo\nbar*", /* expected: */ "foo\nbar\n")]
[TestCase(/* markdownText: */ "[foo\nbar](http://example.com)", /* expected: */ "foo\nbar\n")]
[TestCase(/* markdownText: */ "<http://foo.bar.baz>", /* expected: */ "http://foo.bar.baz\n")]
[TestCase(/* markdownText: */ "# foo bar", /* expected: */ "foo bar\n")]
[TestCase(/* markdownText: */ "# foo\nbar", /* expected: */ "foo\nbar\n")]
[TestCase(/* markdownText: */ "> foo", /* expected: */ "foo\n")]
[TestCase(/* markdownText: */ "> foo\nbar\n> baz", /* expected: */ "foo\nbar\nbaz\n")]
[TestCase(/* markdownText: */ "`foo`", /* expected: */ "foo\n")]
[TestCase(/* markdownText: */ "`foo\nbar`", /* expected: */ "foo bar\n")] // new line within codespan is treated as whitespace (Example317)
[TestCase(/* markdownText: */ "```\nfoo bar\n```", /* expected: */ "foo bar\n")]
[TestCase(/* markdownText: */ "- foo\n- bar\n- baz", /* expected: */ "foo\nbar\nbaz\n")]
[TestCase(/* markdownText: */ "- foo<baz", /* expected: */ "foo<baz\n")]
[TestCase(/* markdownText: */ "- foo<baz", /* expected: */ "foo<baz\n")]
public void TestPlainEnsureNewLine(string markdownText, string expected)
{
var actual = Markdown.ToPlainText(markdownText);
Assert.AreEqual(expected, actual);
}
}
}
| using NUnit.Framework;
namespace Markdig.Tests
{
[TestFixture]
public class TestPlainText
{
[Test]
public void TestPlain()
{
var markdownText = "*Hello*, [world](http://example.com)!";
var expected = "Hello, world!\n";
var actual = Markdown.ToPlainText(markdownText);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(/* markdownText: */ "foo bar", /* expected: */ "foo bar\n")]
[TestCase(/* markdownText: */ "foo\nbar", /* expected: */ "foo\nbar\n")]
[TestCase(/* markdownText: */ "*foo\nbar*", /* expected: */ "foo\nbar\n")]
[TestCase(/* markdownText: */ "[foo\nbar](http://example.com)", /* expected: */ "foo\nbar\n")]
[TestCase(/* markdownText: */ "<http://foo.bar.baz>", /* expected: */ "http://foo.bar.baz\n")]
[TestCase(/* markdownText: */ "# foo bar", /* expected: */ "foo bar\n")]
[TestCase(/* markdownText: */ "# foo\nbar", /* expected: */ "foo\nbar\n")]
[TestCase(/* markdownText: */ "> foo", /* expected: */ "foo\n")]
[TestCase(/* markdownText: */ "> foo\nbar\n> baz", /* expected: */ "foo\nbar\nbaz\n")]
[TestCase(/* markdownText: */ "`foo`", /* expected: */ "foo\n")]
[TestCase(/* markdownText: */ "`foo\nbar`", /* expected: */ "foo bar\n")] // new line within codespan is treated as whitespace (Example317)
[TestCase(/* markdownText: */ "```\nfoo bar\n```", /* expected: */ "foo bar\n")]
[TestCase(/* markdownText: */ "- foo\n- bar\n- baz", /* expected: */ "foo\nbar\nbaz\n")]
public void TestPlainEnsureNewLine(string markdownText, string expected)
{
var actual = Markdown.ToPlainText(markdownText);
Assert.AreEqual(expected, actual);
}
}
}
| bsd-2-clause | C# |
f8e5570e4152b2ac52c859f086a73abb8ec0f3f0 | Fix `Message` equality not passing on equal references | NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu | osu.Game/Online/Chat/Message.cs | osu.Game/Online/Chat/Message.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.Chat
{
public class Message : IComparable<Message>, IEquatable<Message>
{
[JsonProperty(@"message_id")]
public readonly long? Id;
[JsonProperty(@"channel_id")]
public long ChannelId;
[JsonProperty(@"is_action")]
public bool IsAction;
[JsonProperty(@"timestamp")]
public DateTimeOffset Timestamp;
[JsonProperty(@"content")]
public string Content;
[JsonProperty(@"sender")]
public APIUser Sender;
[JsonConstructor]
public Message()
{
}
/// <summary>
/// The text that is displayed in chat.
/// </summary>
public string DisplayContent { get; set; }
/// <summary>
/// The links found in this message.
/// </summary>
/// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks>
public List<Link> Links;
public Message(long? id)
{
Id = id;
}
public int CompareTo(Message other)
{
if (!Id.HasValue)
return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp);
if (!other.Id.HasValue)
return -1;
return Id.Value.CompareTo(other.Id.Value);
}
public virtual bool Equals(Message other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Id.HasValue && Id == other?.Id;
}
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
public override int GetHashCode() => Id.GetHashCode();
public override string ToString() => $"[{ChannelId}] ({Id}) {Sender}: {Content}";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Online.Chat
{
public class Message : IComparable<Message>, IEquatable<Message>
{
[JsonProperty(@"message_id")]
public readonly long? Id;
[JsonProperty(@"channel_id")]
public long ChannelId;
[JsonProperty(@"is_action")]
public bool IsAction;
[JsonProperty(@"timestamp")]
public DateTimeOffset Timestamp;
[JsonProperty(@"content")]
public string Content;
[JsonProperty(@"sender")]
public APIUser Sender;
[JsonConstructor]
public Message()
{
}
/// <summary>
/// The text that is displayed in chat.
/// </summary>
public string DisplayContent { get; set; }
/// <summary>
/// The links found in this message.
/// </summary>
/// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks>
public List<Link> Links;
public Message(long? id)
{
Id = id;
}
public int CompareTo(Message other)
{
if (!Id.HasValue)
return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp);
if (!other.Id.HasValue)
return -1;
return Id.Value.CompareTo(other.Id.Value);
}
public virtual bool Equals(Message other) => Id.HasValue && Id == other?.Id;
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
public override int GetHashCode() => Id.GetHashCode();
public override string ToString() => $"[{ChannelId}] ({Id}) {Sender}: {Content}";
}
}
| mit | C# |
9461441d9882ab53f42722e4ee39f0323604e4bc | Fix Connection Manager | WaelHamze/xrm-ci-framework,WaelHamze/xrm-ci-framework,WaelHamze/xrm-ci-framework | MSDYNV9/Xrm.Framework.CI/Xrm.Framework.CI.Common.IntegrationTests/XrmConnectionManager.cs | MSDYNV9/Xrm.Framework.CI/Xrm.Framework.CI.Common.IntegrationTests/XrmConnectionManager.cs | using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xrm.Framework.CI.Common.IntegrationTests
{
public class XrmConnectionManager
{
#region Constructors
public XrmConnectionManager()
{
}
#endregion
#region Methods
public IOrganizationService CreateConnection()
{
string name = "CrmConnection";
string connectionString = GetConnectionString(name);
return new CrmServiceClient(connectionString);
}
private string GetConnectionString(string name)
{
string value = Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.User);
if (string.IsNullOrEmpty(value))
value = ConfigurationManager.ConnectionStrings[name].ConnectionString;
if (string.IsNullOrEmpty(value))
throw new Exception(name);
return value;
}
#endregion
}
}
| using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xrm.Framework.CI.Common.IntegrationTests
{
public class XrmConnectionManager
{
#region Constructors
public XrmConnectionManager()
{
}
#endregion
#region Methods
public IOrganizationService CreateConnection()
{
string name = "CrmConnection";
//string connectionString = GetConnectionString(name);
string connectionString = "AuthType=Office365;Username=admin@ultradynamics.co.uk;Password=MSDYN365!!;Url=https://ultradynamicsprod.crm11.dynamics.com";
return new CrmServiceClient(connectionString);
}
private string GetConnectionString(string name)
{
string value = Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.User);
if (string.IsNullOrEmpty(value))
value = ConfigurationManager.ConnectionStrings[name].ConnectionString;
if (string.IsNullOrEmpty(value))
throw new Exception(name);
return value;
}
#endregion
}
}
| mit | C# |
921ea26d618761013431abc9a0321d68563dc716 | allow user to passa a interface type instead of concrete class to SoapEndpointExtension methods | DigDes/SoapCore | src/SoapCore/ServiceDescription.cs | src/SoapCore/ServiceDescription.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
namespace SoapCore
{
public class ServiceDescription
{
public Type ServiceType { get; private set; }
public IEnumerable<ContractDescription> Contracts { get; private set; }
public IEnumerable<OperationDescription> Operations => Contracts.SelectMany(c => c.Operations);
public ServiceDescription(Type serviceType)
{
ServiceType = serviceType;
var types = Enumerable.Empty<Type>().Concat(ServiceType.GetInterfaces());
var contracts = new List<ContractDescription>();
if (ServiceType.GetTypeInfo().IsInterface)
{
types = types.Concat(new[] {ServiceType});
}
foreach (var contractType in types)
{
foreach (var serviceContract in contractType.GetTypeInfo().GetCustomAttributes<ServiceContractAttribute>())
{
contracts.Add(new ContractDescription(this, contractType, serviceContract));
}
}
Contracts = contracts;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
namespace SoapCore
{
public class ServiceDescription
{
public Type ServiceType { get; private set; }
public IEnumerable<ContractDescription> Contracts { get; private set; }
public IEnumerable<OperationDescription> Operations => Contracts.SelectMany(c => c.Operations);
public ServiceDescription(Type serviceType)
{
ServiceType = serviceType;
var contracts = new List<ContractDescription>();
foreach (var contractType in ServiceType.GetInterfaces())
{
foreach (var serviceContract in contractType.GetTypeInfo().GetCustomAttributes<ServiceContractAttribute>())
{
contracts.Add(new ContractDescription(this, contractType, serviceContract));
}
}
Contracts = contracts;
}
}
}
| mit | C# |
42b48e906a90e7723a2bba4aca317c4b4769e98a | Fix copyright | gibachan/XmlDict | XmlDict/Properties/AssemblyInfo.cs | XmlDict/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XmlDict")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XmlDict")]
[assembly: AssemblyCopyright("Copyright © 2017 gibachan")]
[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("49919141-c1ed-4f8c-9af2-686102a6e994")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XmlDict")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XmlDict")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("49919141-c1ed-4f8c-9af2-686102a6e994")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
5d36551c3989feec232272394e508e9624d3d200 | Use physics2D instead of player list. | fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/Objects/Research/Artifacts/Effects/TelepaticArtifactEffect.cs | UnityProject/Assets/Scripts/Objects/Research/Artifacts/Effects/TelepaticArtifactEffect.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Random = UnityEngine.Random;
/// <summary>
/// This artifact sends telepatic messages
/// </summary>
public class TelepaticArtifactEffect : ArtifactEffect
{
[Tooltip("How far artifact sends telepatic message")]
public int auraRadius = 10;
public string[] Messages;
public string[] DrasticMessages;
public override void DoEffectTouch(HandApply touchSource)
{
base.DoEffectTouch(touchSource);
Indocrinate(touchSource.Performer);
}
public override void DoEffectAura()
{
base.DoEffectAura();
IndocrinateMessageArea();
}
public override void DoEffectPulse(GameObject pulseSource)
{
base.DoEffectPulse(pulseSource);
IndocrinateMessageArea();
}
private void IndocrinateMessageArea()
{
var objCenter = gameObject.AssumedWorldPosServer().RoundToInt();
var hitMask = LayerMask.GetMask("Players");
var colliders = Physics2D.OverlapCircleAll(new Vector2(objCenter.x, objCenter.y), auraRadius, hitMask);
foreach (var connected in colliders)
{
connected.TryGetComponent<PlayerScript>(out var player);
if (player == null || player.IsDeadOrGhost)
{
Indocrinate(player.gameObject);
}
}
}
private void Indocrinate(GameObject target)
{
if (Random.value > 0.2f)
Chat.AddWarningMsgFromServer(target, Messages.PickRandom());
else
Chat.AddWarningMsgFromServer(target, DrasticMessages.PickRandom());
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Random = UnityEngine.Random;
/// <summary>
/// This artifact sends telepatic messages
/// </summary>
public class TelepaticArtifactEffect : ArtifactEffect
{
[Tooltip("How far artifact sends telepatic message")]
public int auraRadius = 10;
public string[] Messages;
public string[] DrasticMessages;
public override void DoEffectTouch(HandApply touchSource)
{
base.DoEffectTouch(touchSource);
Indocrinate(touchSource.Performer);
}
public override void DoEffectAura()
{
base.DoEffectAura();
IndocrinateMessageArea();
}
public override void DoEffectPulse(GameObject pulseSource)
{
base.DoEffectPulse(pulseSource);
IndocrinateMessageArea();
}
private void IndocrinateMessageArea()
{
var objCenter = gameObject.AssumedWorldPosServer().RoundToInt();
var xMin = objCenter.x - auraRadius;
var yMin = objCenter.y - auraRadius;
var bounds = new BoundsInt(xMin, yMin, 0, 20, 20, 1);
foreach (var connected in PlayerList.Instance.InGamePlayers)
{
var player = connected.Script;
if (player.IsDeadOrGhost == false && bounds.Contains(player.WorldPos))
{
Indocrinate(player.gameObject);
}
}
}
private void Indocrinate(GameObject target)
{
if (Random.value > 0.2f)
Chat.AddWarningMsgFromServer(target, Messages.PickRandom());
else
Chat.AddWarningMsgFromServer(target, DrasticMessages.PickRandom());
}
}
| agpl-3.0 | C# |
34566cac0675f932b011d0dbc467f19459bc2118 | Update AssemblyFileTest.cs | NMSLanX/Natasha | test/NatashaUT/AssemblyFileTest.cs | test/NatashaUT/AssemblyFileTest.cs | using Natasha;
using System;
using System.IO;
using Xunit;
namespace NatashaUT
{
[Trait("程序集编译测试", "文件")]
public class AssemblyFileTest
{
[Fact(DisplayName = "文件部分类编译")]
public void Test1()
{
string path1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File", "TextFile1.txt");
string path2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File", "TestFileModel.cs");
NAssembly assembly = new NAssembly("AsmTestFile");
assembly.AddFile(path1);
assembly.AddFile(path2);
var result = assembly.Complier();
Assert.NotNull(result);
var type = assembly.GetType("TestFileModel");
Assert.NotNull(type);
Assert.Equal("TestFileModel", type.Name);
var @delegate = NFunc<string>.Delegate("return new TestFileModel().Name;", result);
Assert.Equal("aaa",@delegate());
}
}
}
| using Natasha;
using System;
using System.IO;
using Xunit;
namespace NatashaUT
{
[Trait("程序集编译测试", "文件")]
public class AssemblyFileTest
{
[Fact(DisplayName = "文件部分类编译")]
public void Test1()
{
string path1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File", "TextFile1.txt");
string path2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File", "TestFileModel.cs");
NAssembly assembly = new NAssembly("AsmTestFile");
assembly.AddFile(path1);
assembly.AddFile(path2);
var result = assembly.Complier();
Assert.NotNull(result);
var type = assembly.GetType("TestFileModel");
Assert.NotNull(type);
Assert.Equal("TestFileModel", type.Name);
var @delegate = NFunc<string>.Delegate("return new TestFileModel().Name;", result);
Assert.Equal("aaa",@delegate());
}
}
}
| mpl-2.0 | C# |
b44d1744c049129fbc16a98fb1d8617ecc679cfe | Make NotNullConstraintViolationException.New(..) internal | fernandovm/SQLite.Net-PCL,igrali/SQLite.Net-PCL,molinch/SQLite.Net-PCL,mattleibow/SQLite.Net-PCL,igrali/SQLite.Net-PCL,caseydedore/SQLite.Net-PCL,kreuzhofer/SQLite.Net-PCL,oysteinkrog/SQLite.Net-PCL,TiendaNube/SQLite.Net-PCL | src/SQLite.Net/NotNullConstraintViolationException.cs | src/SQLite.Net/NotNullConstraintViolationException.cs | //
// Copyright (c) 2012 Krueger Systems, Inc.
// Copyright (c) 2013 ystein Krog (oystein.krog@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
using System.Linq;
using SQLite.Net.Interop;
namespace SQLite.Net
{
public class NotNullConstraintViolationException : SQLiteException
{
protected NotNullConstraintViolationException(Result r, string message, TableMapping mapping = null, object obj = null)
: base(r, message)
{
if (mapping != null && obj != null)
{
Columns = from c in mapping.Columns
where c.IsNullable == false && c.GetValue(obj) == null
select c;
}
}
public IEnumerable<TableMapping.Column> Columns { get; protected set; }
internal new static NotNullConstraintViolationException New(Result r, string message)
{
return new NotNullConstraintViolationException(r, message);
}
internal static NotNullConstraintViolationException New(Result r, string message, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException(r, message, mapping, obj);
}
internal static NotNullConstraintViolationException New(SQLiteException exception, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException(exception.Result, exception.Message, mapping, obj);
}
}
} | //
// Copyright (c) 2012 Krueger Systems, Inc.
// Copyright (c) 2013 ystein Krog (oystein.krog@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
using System.Linq;
using SQLite.Net.Interop;
namespace SQLite.Net
{
public class NotNullConstraintViolationException : SQLiteException
{
protected NotNullConstraintViolationException(Result r, string message, TableMapping mapping = null, object obj = null)
: base(r, message)
{
if (mapping != null && obj != null)
{
Columns = from c in mapping.Columns
where c.IsNullable == false && c.GetValue(obj) == null
select c;
}
}
public IEnumerable<TableMapping.Column> Columns { get; protected set; }
public new static NotNullConstraintViolationException New(Result r, string message)
{
return new NotNullConstraintViolationException(r, message);
}
public static NotNullConstraintViolationException New(Result r, string message, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException(r, message, mapping, obj);
}
public static NotNullConstraintViolationException New(SQLiteException exception, TableMapping mapping, object obj)
{
return new NotNullConstraintViolationException(exception.Result, exception.Message, mapping, obj);
}
}
} | mit | C# |
9de33b71e41654efef8c7ec0c9f1c9c7cfc0701e | change submit text of signin view | maxtoroq/MvcAccount,ZenHiro/MvcAccount | MvcAccount/Auth/SignInViewModel.cs | MvcAccount/Auth/SignInViewModel.cs | // Copyright 2012 Max Toro Q.
//
// 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.Linq;
using System.Text;
using MvcAccount.Shared;
namespace MvcAccount.Auth {
/// <summary>
/// Holds data for the SignIn view.
/// </summary>
public class SignInViewModel : FormViewModel<SignInInput> {
/// <summary>
/// A link for account recovery.
/// </summary>
public LinkModel AccountRecoveryLink { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="SignInViewModel"/>
/// using the provided input model.
/// </summary>
/// <param name="inputModel">The input model.</param>
public SignInViewModel(SignInInput inputModel)
: base(inputModel) {
this.Title = AccountResources.Views_Auth_SignIn_Title;
this.SubmitText = this.Title;
this.AccountRecoveryLink = new LinkModel(this.Url.Action("", "Password.Reset"), AccountResources.Links_Recovery);
}
}
}
| // Copyright 2012 Max Toro Q.
//
// 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.Linq;
using System.Text;
using MvcAccount.Shared;
namespace MvcAccount.Auth {
/// <summary>
/// Holds data for the SignIn view.
/// </summary>
public class SignInViewModel : FormViewModel<SignInInput> {
/// <summary>
/// A link for account recovery.
/// </summary>
public LinkModel AccountRecoveryLink { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="SignInViewModel"/>
/// using the provided input model.
/// </summary>
/// <param name="inputModel">The input model.</param>
public SignInViewModel(SignInInput inputModel)
: base(inputModel) {
this.Title = AccountResources.Views_Auth_SignIn_Title;
this.AccountRecoveryLink = new LinkModel(this.Url.Action("", "Password.Reset"), AccountResources.Links_Recovery);
}
}
}
| apache-2.0 | C# |
d76625ee2ab3149a751a77e7764affcdb41a3b9d | Implement OxideApi.Authenticate | Skippeh/Oxide.Ext.ServerManager | Oxide.PluginWebApi/Net/OxideApi.cs | Oxide.PluginWebApi/Net/OxideApi.cs | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
namespace Oxide.PluginWebApi.Net
{
public class OxideApi : IDisposable
{
private static readonly CookieContainer cookieContainer = new CookieContainer();
private readonly CookieWebClient webClient;
public static bool Authenticate(string username, string password)
{
using (var webClient = new CookieWebClient(cookieContainer))
{
byte[] responseBytes = webClient.UploadValues("http://oxidemod.org/login/login", "POST", new NameValueCollection
{
{ "login", username },
{ "password", password }
});
string response = Encoding.UTF8.GetString(responseBytes);
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(response);
var rootNode = htmlDoc.DocumentNode;
var content = rootNode.SelectSingleNode("//*[@id=\"content\"]");
if (content.GetAttributeValue("class", "").Contains("error_with_login"))
{
return false;
}
return true;
}
}
public OxideApi()
{
webClient = new CookieWebClient(cookieContainer);
}
public void Dispose()
{
webClient.Dispose();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Oxide.PluginWebApi.Net
{
public class OxideApi : IDisposable
{
private static readonly CookieContainer cookieContainer = new CookieContainer();
private readonly CookieWebClient webClient;
public static bool Authenticate(string username, string password)
{
return false;
}
public OxideApi()
{
webClient = new CookieWebClient(cookieContainer);
}
public void Dispose()
{
webClient.Dispose();
}
}
} | mit | C# |
e6e2a35a663637170b51897b8e18aaafa656f889 | Fix dumb code | leppie/MilkVRLinks | MilkVRLinks/Program.cs | MilkVRLinks/Program.cs | using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
var settings = MilkVRLinks.Properties.Settings.Default;
var searchpattern = settings.SearchPattern;
var baseurl = settings.BaseUrl;
if (args.Length > 0)
{
baseurl = args[0];
if (args.Length > 1)
{
searchpattern = args[1];
}
}
foreach (var f in Directory.GetFiles(".", searchpattern))
{
Video.FromFile(Path.GetFileName(f), baseurl).ToMVRL();
}
}
}
class Video
{
string Url, VideoType, AudioType;
public string Title { get; private set; }
public void ToMVRL()
{
using (var w = new StreamWriter($"{Title}.mvrl", false))
{
w.WriteLine(Url);
w.WriteLine(VideoType);
w.WriteLine(AudioType);
}
}
static readonly Regex vtr = new Regex(@"(180x1[86]0_)?(squished_)?3d[vh]", RegexOptions.Compiled);
public static Video FromFile(string filename, string baseurl)
{
var url = $"{baseurl.TrimEnd('/')}/{filename.Replace(" ", "%20")}";
var fne = Path.GetFileNameWithoutExtension(filename);
var vt = vtr.Match(fne)?.Value;
if (!string.IsNullOrEmpty(vt))
{
fne = fne.Replace(vt, "");
}
fne = fne.TrimEnd('_');
return new Video
{
Title = fne,
Url = url,
VideoType = vt,
AudioType = ""
};
}
} | using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
var settings = MilkVRLinks.Properties.Settings.Default;
var searchpattern = settings.SearchPattern;
var baseurl = settings.BaseUrl;
if (args.Length > 0)
{
baseurl = args[0];
if (args.Length > 1)
{
searchpattern = args[1];
}
}
foreach (var f in Directory.EnumerateFiles(".", searchpattern))
{
Video.FromFile(Path.GetFileName(f), baseurl).ToMVRL();
}
}
}
class Video
{
string Url, VideoType, AudioType;
public string Title { get; private set; }
public void ToMVRL()
{
using (var w = new StreamWriter($"{Title}.mvrl", false))
{
w.WriteLine(Url);
w.WriteLine(VideoType);
w.WriteLine(AudioType);
}
}
static readonly Regex vtr = new Regex(@"(180x1[86]0_)?(squished_)?3d[vh]", RegexOptions.Compiled);
public static Video FromFile(string filename, string baseurl)
{
var url = $"{baseurl.TrimEnd('/')}/{filename.Replace(" ", "%20")}";
var fne = Path.GetFileNameWithoutExtension(filename);
var vt = vtr.Match(fne)?.Value;
if (!string.IsNullOrEmpty(vt))
{
fne = fne.Replace(vt, "");
}
fne = fne.TrimEnd('_');
return new Video
{
Title = fne,
Url = url,
VideoType = vt,
AudioType = ""
};
}
} | mit | C# |
d2bb74acbdddddd1f839a82189bb272c5f5c9b59 | Implement AppModel | sakapon/Tutorials-2016 | XAML/Sort/SortViewerWpf/AppModel.cs | XAML/Sort/SortViewerWpf/AppModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace SortViewerWpf
{
public class AppModel
{
static readonly TimeSpan ComparisonsSpan = TimeSpan.FromSeconds(1 / 1000.0);
public int[] Numbers { get; private set; }
public int ComparisonsCount { get; private set; }
public void BubbleSort(int maxNumber)
{
Numbers = RandomHelper.ShuffleRange(1, maxNumber).ToArray();
ComparisonsCount = 0;
Task.Run(() =>
{
Thread.Sleep(500);
Numbers.QuickSort((x1, x2) =>
{
Thread.Sleep(ComparisonsSpan);
ComparisonsCount++;
return x1.CompareTo(x2);
});
});
}
}
public static class RandomHelper
{
static readonly Random Random = new Random();
public static IEnumerable<int> ShuffleRange(int start, int count)
{
var l = Enumerable.Range(start, count).ToList();
while (l.Count > 0)
{
var index = Random.Next(l.Count);
yield return l[index];
l.RemoveAt(index);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SortViewerWpf
{
public class AppModel
{
}
public static class RandomHelper
{
static readonly Random Random = new Random();
public static IEnumerable<int> ShuffleRange(int start, int count)
{
var l = Enumerable.Range(start, count).ToList();
while (l.Count > 0)
{
var index = Random.Next(l.Count);
yield return l[index];
l.RemoveAt(index);
}
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.