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 |
|---|---|---|---|---|---|---|---|---|
3bf0c4e4e8c05b731ec8772ae353907ce9454663 | Convert InternetExplorer to a Browser subclass | freenet/wintray,freenet/wintray | Browsers/InternetExplorer.cs | Browsers/InternetExplorer.cs | using System;
using System.Diagnostics;
using Microsoft.Win32;
namespace FreenetTray.Browsers
{
class InternetExplorer: Browser
{
private static string IERegistryKey = @"Software\Microsoft\Internet Explorer";
public InternetExplorer()
{
// See https://support.microsoft.com/kb/969393
// NOTE: this is intentionally looking for the 32bit version, because it's very rare
// for anyone to launch IE 64-bit on purpose. However, since we're running it in
// private browsing mode and don't need plugins anyway, should we always prefer it?
RegistryKey hive = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
RegistryKey key = hive.OpenSubKey(IERegistryKey);
if (key == null) {
var value = key.GetValue("version") as string;
if (value != null) {
_version = new Version(value);
}
}
// TODO: Also check for existence of executable?
_isInstalled = _version != null;
// See https://en.wikipedia.org/wiki/Internet_Explorer_8#InPrivate
_isUsable = _version >= new Version(8, 0);
// See http://msdn.microsoft.com/en-us/library/ie/hh826025%28v=vs.85%29.aspx
_args = "-private ";
_path = "iexplore.exe";
_name = "Internet Explorer";
}
}
}
| using System;
using System.Diagnostics;
using Microsoft.Win32;
namespace FreenetTray.Browsers
{
class InternetExplorer : IBrowser
{
private readonly Version _version;
private readonly bool _isInstalled;
public InternetExplorer()
{
// See https://support.microsoft.com/kb/969393
var value = Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer", "version", null);
if (value != null)
{
_version = new Version((string)value);
}
// TODO: Also check for existence of executable?
_isInstalled = _version != null;
}
public bool Open(Uri target)
{
if (!IsAvailable())
{
return false;
}
// See http://msdn.microsoft.com/en-us/library/ie/hh826025%28v=vs.85%29.aspx
Process.Start("iexplore.exe", "-private " + target);
return true;
}
public bool IsAvailable()
{
// See https://en.wikipedia.org/wiki/Internet_Explorer_8#InPrivate
return _isInstalled && _version >= new Version(8, 0);
}
public string GetName()
{
return "Internet Explorer";
}
}
}
| mit | C# |
f8c9ab1ccc5898f6ef002ba882c7e1984fe133e3 | Update UsingExcelPredefinedStyles.cs | asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/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,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Formatting/ApproachesToFormatData/UsingExcelPredefinedStyles.cs | Examples/CSharp/Formatting/ApproachesToFormatData/UsingExcelPredefinedStyles.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Formatting.ApproachesToFormatData
{
public class UsingExcelPredefinedStyles
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiate a new Workbook.
Workbook workbook = new Workbook();
//Create a style object based on a predefined Excel 2007 style.
Style style = workbook.Styles.CreateBuiltinStyle(BuiltinStyleType.Accent1);
//Input a value to A1 cell.
workbook.Worksheets[0].Cells["A1"].PutValue("Test");
//Apply the style to the cell.
workbook.Worksheets[0].Cells["A1"].SetStyle(style);
//Save the Excel 2007 file.
workbook.Save(dataDir + "book1.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Formatting.ApproachesToFormatData
{
public class UsingExcelPredefinedStyles
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiate a new Workbook.
Workbook workbook = new Workbook();
//Create a style object based on a predefined Excel 2007 style.
Style style = workbook.Styles.CreateBuiltinStyle(BuiltinStyleType.Accent1);
//Input a value to A1 cell.
workbook.Worksheets[0].Cells["A1"].PutValue("Test");
//Apply the style to the cell.
workbook.Worksheets[0].Cells["A1"].SetStyle(style);
//Save the Excel 2007 file.
workbook.Save(dataDir + "book1.out.xlsx");
}
}
} | mit | C# |
48c4d30eb792dd4d2ade244bbc6e399e63604ca3 | Remove unneeded properties from Statement class | lpatalas/NhLogAnalyzer | NhLogAnalyzer/Infrastructure/Statement.cs | NhLogAnalyzer/Infrastructure/Statement.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NhLogAnalyzer.Infrastructure
{
public class Statement
{
private readonly int id;
public int Id
{
get { return id; }
}
private readonly string fullSql;
public string FullSql
{
get { return fullSql; }
}
private readonly string shortSql;
public string ShortSql
{
get { return shortSql; }
}
public string StackTrace
{
get { return string.Empty; }
}
private readonly DateTime timestamp;
public DateTime Timestamp
{
get { return timestamp; }
}
public Statement(int id, string fullSql, string shortSql, DateTime timestamp)
{
this.id = id;
this.fullSql = fullSql;
this.shortSql = shortSql;
this.timestamp = timestamp;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NhLogAnalyzer.Infrastructure
{
public class Statement
{
private readonly int id;
public int Id
{
get { return id; }
}
private readonly string fullSql;
public string FullSql
{
get { return fullSql; }
}
private readonly string shortSql;
public string ShortSql
{
get { return shortSql; }
}
public string SqlText
{
get { return string.Empty; }
}
public string StackTrace
{
get { return string.Empty; }
}
private readonly DateTime timestamp;
public DateTime Timestamp
{
get { return timestamp; }
}
public string SingleLineSqlText
{
get { return string.Empty; }
}
public Statement(int id, string fullSql, string shortSql, DateTime timestamp)
{
this.id = id;
this.fullSql = fullSql;
this.shortSql = shortSql;
this.timestamp = timestamp;
}
private static readonly Regex whitespaceRegex = new Regex(@"[ \t\r\n]+");
private static string CreateSingleLineSqlText(string sqlText)
{
var trimmedSql = sqlText.Trim();
return whitespaceRegex.Replace(trimmedSql, " ");
}
}
}
| mit | C# |
90d42bced8ed9610a33df6ddfe6ca4449c86c573 | add decoding info for 3DNow.s.cs | zuloloxi/capstone,NeilBryant/capstone,sephiroth99/capstone,AmesianX/capstone,techvoltage/capstone,bowlofstew/capstone,nplanel/capstone,bSr43/capstone,NeilBryant/capstone,pyq881120/capstone,sephiroth99/capstone,nplanel/capstone,8l/capstone,dynm/capstone,sephiroth99/capstone,dynm/capstone,bigendiansmalls/capstone,dynm/capstone,code4bones/capstone,krytarowski/capstone,pyq881120/capstone,bughoho/capstone,pranith/capstone,AmesianX/capstone,techvoltage/capstone,capturePointer/capstone,code4bones/capstone,xia0pin9/capstone,AmesianX/capstone,pranith/capstone,pranith/capstone,zuloloxi/capstone,krytarowski/capstone,bughoho/capstone,zuloloxi/capstone,bSr43/capstone,bSr43/capstone,07151129/capstone,pyq881120/capstone,8l/capstone,bughoho/capstone,bowlofstew/capstone,bigendiansmalls/capstone,NeilBryant/capstone,krytarowski/capstone,sephiroth99/capstone,dynm/capstone,fvrmatteo/capstone,fvrmatteo/capstone,pranith/capstone,zneak/capstone,techvoltage/capstone,nplanel/capstone,8l/capstone,xia0pin9/capstone,krytarowski/capstone,zuloloxi/capstone,07151129/capstone,angelabier1/capstone,bowlofstew/capstone,sephiroth99/capstone,sigma-random/capstone,sigma-random/capstone,nplanel/capstone,zneak/capstone,sigma-random/capstone,AmesianX/capstone,8l/capstone,fvrmatteo/capstone,dynm/capstone,dynm/capstone,bughoho/capstone,bughoho/capstone,bigendiansmalls/capstone,8l/capstone,bowlofstew/capstone,techvoltage/capstone,zuloloxi/capstone,nplanel/capstone,pombredanne/capstone,bughoho/capstone,krytarowski/capstone,bSr43/capstone,angelabier1/capstone,zneak/capstone,techvoltage/capstone,pombredanne/capstone,capturePointer/capstone,07151129/capstone,xia0pin9/capstone,pranith/capstone,07151129/capstone,sephiroth99/capstone,bigendiansmalls/capstone,pombredanne/capstone,code4bones/capstone,bigendiansmalls/capstone,NeilBryant/capstone,8l/capstone,angelabier1/capstone,zneak/capstone,xia0pin9/capstone,NeilBryant/capstone,AmesianX/capstone,AmesianX/capstone,pyq881120/capstone,pombredanne/capstone,zneak/capstone,angelabier1/capstone,krytarowski/capstone,sigma-random/capstone,07151129/capstone,sigma-random/capstone,nplanel/capstone,pyq881120/capstone,zneak/capstone,fvrmatteo/capstone,bSr43/capstone,capturePointer/capstone,NeilBryant/capstone,angelabier1/capstone,zuloloxi/capstone,pombredanne/capstone,bowlofstew/capstone,pombredanne/capstone,07151129/capstone,pombredanne/capstone,07151129/capstone,techvoltage/capstone,xia0pin9/capstone,pranith/capstone,NeilBryant/capstone,xia0pin9/capstone,sigma-random/capstone,capturePointer/capstone,angelabier1/capstone,pyq881120/capstone,bSr43/capstone,fvrmatteo/capstone,bigendiansmalls/capstone,bughoho/capstone,capturePointer/capstone,bigendiansmalls/capstone,zneak/capstone,AmesianX/capstone,pranith/capstone,techvoltage/capstone,fvrmatteo/capstone,sigma-random/capstone,code4bones/capstone,8l/capstone,bowlofstew/capstone,code4bones/capstone,nplanel/capstone,dynm/capstone,angelabier1/capstone,sephiroth99/capstone,capturePointer/capstone,zuloloxi/capstone,capturePointer/capstone,code4bones/capstone,fvrmatteo/capstone,bowlofstew/capstone,xia0pin9/capstone,krytarowski/capstone,pyq881120/capstone,bSr43/capstone,code4bones/capstone | suite/MC/X86/3DNow.s.cs | suite/MC/X86/3DNow.s.cs | # CS_ARCH_X86, CS_MODE_32, CS_OPT_SYNTAX_ATT
0x0f,0x0f,0xca,0xbf = pavgusb %mm2, %mm1
0x67,0x0f,0x0f,0x5c,0x16,0x09,0xbf = pavgusb 9(%esi,%edx), %mm3
0x0f,0x0f,0xca,0x1d = pf2id %mm2, %mm1
0x67,0x0f,0x0f,0x5c,0x16,0x09,0x1d = pf2id 9(%esi,%edx), %mm3
0x0f,0x0f,0xca,0xae = pfacc %mm2, %mm1
0x0f,0x0f,0xca,0x9e = pfadd %mm2, %mm1
0x0f,0x0f,0xca,0xb0 = pfcmpeq %mm2, %mm1
0x0f,0x0f,0xca,0x90 = pfcmpge %mm2, %mm1
0x0f,0x0f,0xca,0xa0 = pfcmpgt %mm2, %mm1
0x0f,0x0f,0xca,0xa4 = pfmax %mm2, %mm1
0x0f,0x0f,0xca,0x94 = pfmin %mm2, %mm1
0x0f,0x0f,0xca,0xb4 = pfmul %mm2, %mm1
0x0f,0x0f,0xca,0x96 = pfrcp %mm2, %mm1
0x0f,0x0f,0xca,0xa6 = pfrcpit1 %mm2, %mm1
0x0f,0x0f,0xca,0xb6 = pfrcpit2 %mm2, %mm1
0x0f,0x0f,0xca,0xa7 = pfrsqit1 %mm2, %mm1
0x0f,0x0f,0xca,0x97 = pfrsqrt %mm2, %mm1
0x0f,0x0f,0xca,0x9a = pfsub %mm2, %mm1
0x0f,0x0f,0xca,0xaa = pfsubr %mm2, %mm1
0x0f,0x0f,0xca,0x0d = pi2fd %mm2, %mm1
0x0f,0x0f,0xca,0xb7 = pmulhrw %mm2, %mm1
0x0f,0x0e = femms
0x0f,0x0d,0x00 = // CHECK: prefetchw (%rax) # encoding: [0x0f,0x0d,0x08]
0x0f,0x0f,0xca,0x1c = pf2iw %mm2, %mm1
0x0f,0x0f,0xca,0x0c = pi2fw %mm2, %mm1
0x0f,0x0f,0xca,0x8a = pfnacc %mm2, %mm1
0x0f,0x0f,0xca,0x8e = pfpnacc %mm2, %mm1
0x0f,0x0f,0xca,0xbb = pswapd %mm2, %mm1
| 0x0f,0x0f,0xca,0xbf = pavgusb %mm2, %mm1
0x67,0x0f,0x0f,0x5c,0x16,0x09,0xbf = pavgusb 9(%esi,%edx), %mm3
0x0f,0x0f,0xca,0x1d = pf2id %mm2, %mm1
0x67,0x0f,0x0f,0x5c,0x16,0x09,0x1d = pf2id 9(%esi,%edx), %mm3
0x0f,0x0f,0xca,0xae = pfacc %mm2, %mm1
0x0f,0x0f,0xca,0x9e = pfadd %mm2, %mm1
0x0f,0x0f,0xca,0xb0 = pfcmpeq %mm2, %mm1
0x0f,0x0f,0xca,0x90 = pfcmpge %mm2, %mm1
0x0f,0x0f,0xca,0xa0 = pfcmpgt %mm2, %mm1
0x0f,0x0f,0xca,0xa4 = pfmax %mm2, %mm1
0x0f,0x0f,0xca,0x94 = pfmin %mm2, %mm1
0x0f,0x0f,0xca,0xb4 = pfmul %mm2, %mm1
0x0f,0x0f,0xca,0x96 = pfrcp %mm2, %mm1
0x0f,0x0f,0xca,0xa6 = pfrcpit1 %mm2, %mm1
0x0f,0x0f,0xca,0xb6 = pfrcpit2 %mm2, %mm1
0x0f,0x0f,0xca,0xa7 = pfrsqit1 %mm2, %mm1
0x0f,0x0f,0xca,0x97 = pfrsqrt %mm2, %mm1
0x0f,0x0f,0xca,0x9a = pfsub %mm2, %mm1
0x0f,0x0f,0xca,0xaa = pfsubr %mm2, %mm1
0x0f,0x0f,0xca,0x0d = pi2fd %mm2, %mm1
0x0f,0x0f,0xca,0xb7 = pmulhrw %mm2, %mm1
0x0f,0x0e = femms
0x0f,0x0d,0x00 = // CHECK: prefetchw (%rax) # encoding: [0x0f,0x0d,0x08]
0x0f,0x0f,0xca,0x1c = pf2iw %mm2, %mm1
0x0f,0x0f,0xca,0x0c = pi2fw %mm2, %mm1
0x0f,0x0f,0xca,0x8a = pfnacc %mm2, %mm1
0x0f,0x0f,0xca,0x8e = pfpnacc %mm2, %mm1
0x0f,0x0f,0xca,0xbb = pswapd %mm2, %mm1
| bsd-3-clause | C# |
5dd483a46548f9aad7844edc4467e5cb596ccd0b | fix author empty issue | CVBDL/RALibraryServer | RaLibrary.BookApiProxy/Douban/DoubanBooksOpenApi.cs | RaLibrary.BookApiProxy/Douban/DoubanBooksOpenApi.cs | using Newtonsoft.Json;
using RaLibrary.BookApiProxy.Exceptions;
using RaLibrary.BookApiProxy.Models;
using RaLibrary.Utilities;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
namespace RaLibrary.BookApiProxy.Douban
{
public class DoubanBooksOpenApi : IBooksOpenApi
{
#region Fields
private static readonly string s_baseRequestUri = ConfigurationManager.AppSettings.Get("DoubanBooksApiEndpoint");
private static readonly HttpClient s_httpClient = new HttpClient();
#endregion Fields
public async Task<BookDetailsDto> QueryIsbnAsync(Isbn isbn)
{
string requestUri = s_baseRequestUri + isbn.NormalizedValue;
HttpResponseMessage response = await s_httpClient.GetAsync(requestUri);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
throw new BookNotFoundException();
}
string responseBody = await response.Content.ReadAsStringAsync();
DoubanBook book = JsonConvert.DeserializeObject<DoubanBook>(responseBody);
string authors = string.Empty;
if (book.author!=null && book.author.Length > 0)
{
authors = string.Join(",", book.author);
}
ushort? pageCount = null;
if (!string.IsNullOrWhiteSpace(book.pages))
{
pageCount = ushort.Parse(book.pages);
}
return new BookDetailsDto()
{
ISBN10 = book.isbn10,
ISBN13 = book.isbn13,
Title = book.title,
Subtitle = book.subtitle,
Authors = authors,
Publisher = book.publisher,
PublishedDate = book.pubdate,
Description = book.summary,
ThumbnailLink = book.images.medium,
PageCount = pageCount
};
}
}
}
| using Newtonsoft.Json;
using RaLibrary.BookApiProxy.Exceptions;
using RaLibrary.BookApiProxy.Models;
using RaLibrary.Utilities;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
namespace RaLibrary.BookApiProxy.Douban
{
public class DoubanBooksOpenApi : IBooksOpenApi
{
#region Fields
private static readonly string s_baseRequestUri = ConfigurationManager.AppSettings.Get("DoubanBooksApiEndpoint");
private static readonly HttpClient s_httpClient = new HttpClient();
#endregion Fields
public async Task<BookDetailsDto> QueryIsbnAsync(Isbn isbn)
{
string requestUri = s_baseRequestUri + isbn.NormalizedValue;
HttpResponseMessage response = await s_httpClient.GetAsync(requestUri);
try
{
response.EnsureSuccessStatusCode();
}
catch
{
throw new BookNotFoundException();
}
string responseBody = await response.Content.ReadAsStringAsync();
DoubanBook book = JsonConvert.DeserializeObject<DoubanBook>(responseBody);
string authors = string.Empty;
if (!string.IsNullOrWhiteSpace(authors))
{
authors = string.Join(",", book.author);
}
ushort? pageCount = null;
if (!string.IsNullOrWhiteSpace(book.pages))
{
pageCount = ushort.Parse(book.pages);
}
return new BookDetailsDto()
{
ISBN10 = book.isbn10,
ISBN13 = book.isbn13,
Title = book.title,
Subtitle = book.subtitle,
Authors = authors,
Publisher = book.publisher,
PublishedDate = book.pubdate,
Description = book.summary,
ThumbnailLink = book.images.medium,
PageCount = pageCount
};
}
}
}
| mit | C# |
c14a022d76a076531541285e67a9f9b842f355ed | Remove worthless comment | EasyPeasyLemonSqueezy/MadCat | MadCat/NutEngine/Camera/Camera2D.cs | MadCat/NutEngine/Camera/Camera2D.cs | using Microsoft.Xna.Framework;
namespace NutEngine.Camera
{
public abstract class Camera2D
{
public abstract Matrix2D Transform { get; }
public Vector2 Position { get; set; }
public float Rotation { get; set; }
public float Zoom { get; set; }
public Vector2 Frame { get; set; }
public Vector2 Origin { get; set; }
public Camera2D(Vector2 frame)
{
Frame = frame;
Origin = frame / 2;
}
}
}
| using Microsoft.Xna.Framework;
namespace NutEngine.Camera
{
public abstract class Camera2D
{
/// TODO: Считать матрицу без 5 умножений
/// и делать это по-разному в унаследованных камерах
public abstract Matrix2D Transform { get; }
public Vector2 Position { get; set; }
public float Rotation { get; set; }
public float Zoom { get; set; }
public Vector2 Frame { get; set; }
public Vector2 Origin { get; set; }
public Camera2D(Vector2 frame)
{
Frame = frame;
Origin = frame / 2;
}
}
}
| mit | C# |
dc860f3edf2108f72e4f866aeb9b6793c5e4174c | Update exportTxt.cs | Gytaco/RevitAPI,Gytaco/RevitAPI | Macros/CS/ImportExport/exportTxt.cs | Macros/CS/ImportExport/exportTxt.cs | /*
This code exports a delimited tab text file of some parameters from Walls.
*/
//This code requires the following reference
using System.IO;
public void exportTxt()
{
//assigns doc to the active document in use - default
Document doc = this.ActiveUIDocument.Document;
//a string that stores the files location
string location = @"C:\data.txt";
//creates a private IEnumerable that accepts string DataTypes only
IEnumerable<string> Result;
//creates a string list object
List<string> list = new List<string>();
//Basic collection for walls
ICollection<Element> elem = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
.WhereElementIsNotElementType().ToElements();
//string header for the text file
string header = ("WallID\tName\tComments");
//adds the header to the top of the list
list.Add(header);
//foreach statement to get access to the data or elements
foreach (Element e in elem)
{
//gets all the wall instance Id's, names and comments and formats them with tabs
list.Add(e.Id.ToString() + "\t" + e.Name.ToString() + "\t" + e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString());
}
//get the completed list into the Ienumerable
Result = list;
//writes all the information to the text file
File.WriteAllLines(location, Result);
//Dialog to show results
TaskDialog.Show("List of Instances", "Export Successful");
}
| /*
This code exports a delimited tab text file of some parameters from Walls.
*/
//This code requires the following reference
using System.IO;
public void exportTxt()
{
//assigns doc to the active document in use - default
Document doc = this.ActiveUIDocument.Document;
//a string that stores the files location
string location = @"C:\Users\Gytaco\Desktop\data.txt";
//creates a private IEnumerable that accepts string DataTypes only
IEnumerable<string> Result;
//creates a string list object
List<string> list = new List<string>();
//Basic collection for walls
ICollection<Element> elem = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
.WhereElementIsNotElementType().ToElements();
//string header for the text file
string header = ("WallID\tName\tComments");
//adds the header to the top of the list
list.Add(header);
//foreach statement to get access to the data or elements
foreach (Element e in elem)
{
//gets all the wall instance Id's, names and comments and formats them with tabs
list.Add(e.Id.ToString() + "\t" + e.Name.ToString() + "\t" + e.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).AsString());
}
//get the completed list into the Ienumerable
Result = list;
//writes all the information to the text file
File.WriteAllLines(location, Result);
//Dialog to show results
TaskDialog.Show("List of Instances", "Export Successful");
}
| mit | C# |
a0ef35a38c8abc3d201827af1366953d54134968 | Bump version | stratisproject/NStratis | NBitcoin/Properties/AssemblyInfo.cs | NBitcoin/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NStratis")]
[assembly: AssemblyDescription("Implementation of stratis protocol")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AO-IS")]
[assembly: AssemblyProduct("NStratis")]
[assembly: AssemblyCopyright("Copyright © AO-IS 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("NBitcoin.Tests")]
// 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)]
// 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("3.0.2.13")]
[assembly: AssemblyFileVersion("3.0.2.13")]
[assembly: AssemblyInformationalVersion("3.0.2.13")]
| using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NStratis")]
[assembly: AssemblyDescription("Implementation of stratis protocol")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AO-IS")]
[assembly: AssemblyProduct("NStratis")]
[assembly: AssemblyCopyright("Copyright © AO-IS 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("NBitcoin.Tests")]
// 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)]
// 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("3.0.2.12")]
[assembly: AssemblyFileVersion("3.0.2.12")]
[assembly: AssemblyInformationalVersion("3.0.2.12")]
| mit | C# |
555a986d9edbb93d06f98e7488b7a948a1288d2e | Create State property | jnnfrlocke/VendingMachineNew,jnnfrlocke/VendingMachineNew,jnnfrlocke/VendingMachineNew | Models/Machines.cs | Models/Machines.cs | using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.ComponentModel.DataAnnotations;
namespace VendingMachineNew.Models
{
public class Machines
{
[Key]
public int Id { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
} | using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.ComponentModel.DataAnnotations;
namespace VendingMachineNew.Models
{
public class Machines
{
[Key]
public int Id { get; set; }
public string Address { get; set; }
public string City { get; set; }
}
} | mit | C# |
f17ac8e797c17ed64851f9b89123ac9a6e4a7cc9 | Add test for Int64.Parse | tgiphil/Cosmos,zarlo/Cosmos,trivalik/Cosmos,zarlo/Cosmos,jp2masa/Cosmos,trivalik/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,jp2masa/Cosmos,jp2masa/Cosmos,CosmosOS/Cosmos,fanoI/Cosmos,trivalik/Cosmos,CosmosOS/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,fanoI/Cosmos,zarlo/Cosmos,fanoI/Cosmos | Tests/Cosmos.Compiler.Tests.Bcl/System/Int64Test.cs | Tests/Cosmos.Compiler.Tests.Bcl/System/Int64Test.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Cosmos.TestRunner;
namespace Cosmos.Compiler.Tests.Bcl.System
{
class Int64Test
{
public static void Execute()
{
Int64 value;
String result;
String expectedResult;
value = Int64.MaxValue;
result = value.ToString();
expectedResult = "9223372036854775807";
Assert.IsTrue((result == expectedResult), "Int64.ToString doesn't work");
// Now let's try to concat to a String using '+' operator
result = "The Maximum value of an Int64 is " + value;
expectedResult = "The Maximum value of an Int64 is 9223372036854775807";
Assert.IsTrue((result == expectedResult), "String concat (Int64) doesn't work");
// Now let's try to use '$ instead of '+'
result = $"The Maximum value of an Int64 is {value}";
// Actually 'expectedResult' should be the same so...
Assert.IsTrue((result == expectedResult), "String format (Int64) doesn't work");
// Now let's Get the HashCode of a value
int resultAsInt = value.GetHashCode();
// actually the Hash Code of a Int64 is the value interpolated with XOR to obtain an Int32... so not the same of 'value'!
int expectedResultAsInt = (unchecked((int)((long)value)) ^ (int)(value >> 32));
Assert.IsTrue((resultAsInt == expectedResultAsInt), "Int64.GetHashCode() doesn't work");
// Let's try to convert a Long in a ULong
Int64 val2 = 42;
UInt64 val2AsULong = (ulong)val2;
Assert.IsTrue((val2AsULong == 42), "Int64 to UInt64 conversion does not work");
val2 = long.Parse("42");
Assert.IsTrue(val2 == 42, "Parsing Int64 doesn't work.");
#if false
// Now let's try ToString() again but printed in hex (this test fails for now!)
result = value.ToString("X2");
expectedResult = "0x7FFFFFFFFFFFFFFF";
Assert.IsTrue((result == expectedResult), "Int64.ToString(X2) doesn't work");
#endif
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Cosmos.TestRunner;
namespace Cosmos.Compiler.Tests.Bcl.System
{
class Int64Test
{
public static void Execute()
{
Int64 value;
String result;
String expectedResult;
value = Int64.MaxValue;
result = value.ToString();
expectedResult = "9223372036854775807";
Assert.IsTrue((result == expectedResult), "Int64.ToString doesn't work");
// Now let's try to concat to a String using '+' operator
result = "The Maximum value of an Int64 is " + value;
expectedResult = "The Maximum value of an Int64 is 9223372036854775807";
Assert.IsTrue((result == expectedResult), "String concat (Int64) doesn't work");
// Now let's try to use '$ instead of '+'
result = $"The Maximum value of an Int64 is {value}";
// Actually 'expectedResult' should be the same so...
Assert.IsTrue((result == expectedResult), "String format (Int64) doesn't work");
// Now let's Get the HashCode of a value
int resultAsInt = value.GetHashCode();
// actually the Hash Code of a Int64 is the value interpolated with XOR to obtain an Int32... so not the same of 'value'!
int expectedResultAsInt = (unchecked((int)((long)value)) ^ (int)(value >> 32));
Assert.IsTrue((resultAsInt == expectedResultAsInt), "Int64.GetHashCode() doesn't work");
// Let's try to convert a Long in a ULong
Int64 val2 = 42;
UInt64 val2AsULong = (ulong)val2;
Assert.IsTrue((val2AsULong == 42), "Int64 to UInt64 conversion does not work");
#if false
// Now let's try ToString() again but printed in hex (this test fails for now!)
result = value.ToString("X2");
expectedResult = "0x7FFFFFFFFFFFFFFF";
Assert.IsTrue((result == expectedResult), "Int64.ToString(X2) doesn't work");
#endif
}
}
}
| bsd-3-clause | C# |
aa04d21ccf2149c5be2460284374803028229a45 | Add async transaction tests. | mysql-net/MySqlConnector,gitsno/MySqlConnector,gitsno/MySqlConnector,mysql-net/MySqlConnector | tests/SideBySide.New/Transaction.cs | tests/SideBySide.New/Transaction.cs | using System;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using Xunit;
namespace SideBySide
{
public class Transaction : IClassFixture<TransactionFixture>
{
public Transaction(TransactionFixture database)
{
m_database = database;
m_connection = m_database.Connection;
}
[Fact]
public void NestedTransactions()
{
using (m_connection.BeginTransaction())
{
Assert.Throws<InvalidOperationException>(() => m_connection.BeginTransaction());
}
}
[Fact]
public void Commit()
{
m_connection.Execute("delete from transactions.test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions.test values(1), (2)", transaction: trans);
trans.Commit();
}
var results = m_connection.Query<int>(@"select value from transactions.test order by value;");
Assert.Equal(new[] { 1, 2 }, results);
}
#if !BASELINE
[Fact]
public async Task CommitAsync()
{
await m_connection.ExecuteAsync("delete from transactions.test").ConfigureAwait(false);
using (var trans = await m_connection.BeginTransactionAsync().ConfigureAwait(false))
{
await m_connection.ExecuteAsync("insert into transactions.test values(1), (2)", transaction: trans).ConfigureAwait(false);
await trans.CommitAsync().ConfigureAwait(false);
}
var results = await m_connection.QueryAsync<int>(@"select value from transactions.test order by value;").ConfigureAwait(false);
Assert.Equal(new[] { 1, 2 }, results);
}
#endif
[Fact]
public void Rollback()
{
m_connection.Execute("delete from transactions.test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions.test values(1), (2)", transaction: trans);
trans.Rollback();
}
var results = m_connection.Query<int>(@"select value from transactions.test order by value;");
Assert.Equal(new int[0], results);
}
#if !BASELINE
[Fact]
public async Task RollbackAsync()
{
await m_connection.ExecuteAsync("delete from transactions.test").ConfigureAwait(false);
using (var trans = await m_connection.BeginTransactionAsync().ConfigureAwait(false))
{
await m_connection.ExecuteAsync("insert into transactions.test values(1), (2)", transaction: trans).ConfigureAwait(false);
await trans.RollbackAsync().ConfigureAwait(false);
}
var results = await m_connection.QueryAsync<int>(@"select value from transactions.test order by value;").ConfigureAwait(false);
Assert.Equal(new int[0], results);
}
#endif
[Fact]
public void NoCommit()
{
m_connection.Execute("delete from transactions.test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions.test values(1), (2)", transaction: trans);
}
var results = m_connection.Query<int>(@"select value from transactions.test order by value;");
Assert.Equal(new int[0], results);
}
readonly TransactionFixture m_database;
readonly MySqlConnection m_connection;
}
}
| using System;
using Dapper;
using MySql.Data.MySqlClient;
using Xunit;
namespace SideBySide
{
public class Transaction : IClassFixture<TransactionFixture>
{
public Transaction(TransactionFixture database)
{
m_database = database;
m_connection = m_database.Connection;
}
[Fact]
public void NestedTransactions()
{
using (m_connection.BeginTransaction())
{
Assert.Throws<InvalidOperationException>(() => m_connection.BeginTransaction());
}
}
[Fact]
public void Commit()
{
m_connection.Execute("delete from transactions.test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions.test values(1), (2)", transaction: trans);
trans.Commit();
}
var results = m_connection.Query<int>(@"select value from transactions.test order by value;");
Assert.Equal(new[] { 1, 2 }, results);
}
[Fact]
public void Rollback()
{
m_connection.Execute("delete from transactions.test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions.test values(1), (2)", transaction: trans);
trans.Rollback();
}
var results = m_connection.Query<int>(@"select value from transactions.test order by value;");
Assert.Equal(new int[0], results);
}
[Fact]
public void NoCommit()
{
m_connection.Execute("delete from transactions.test");
using (var trans = m_connection.BeginTransaction())
{
m_connection.Execute("insert into transactions.test values(1), (2)", transaction: trans);
}
var results = m_connection.Query<int>(@"select value from transactions.test order by value;");
Assert.Equal(new int[0], results);
}
readonly TransactionFixture m_database;
readonly MySqlConnection m_connection;
}
}
| mit | C# |
19a3c959923328c8b91e4653ee003b101f60c770 | Update InspectCode to 2019.3 | 2yangk23/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu-new,EVAST9919/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu,2yangk23/osu | build/InspectCode.cake | build/InspectCode.cake | #addin "nuget:?package=CodeFileSanity&version=0.0.33"
#addin "nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2019.3.0"
#tool "nuget:?package=NVika.MSBuild&version=1.0.1"
var nVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First();
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "CodeAnalysis");
var configuration = Argument("configuration", "Release");
var rootDirectory = new DirectoryPath("..");
var sln = rootDirectory.CombineWithFilePath("osu.sln");
var desktopSlnf = rootDirectory.CombineWithFilePath("osu.Desktop.slnf");
///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////
// windows only because both inspectcode and nvika depend on net45
Task("InspectCode")
.WithCriteria(IsRunningOnWindows())
.Does(() => {
InspectCode(desktopSlnf, new InspectCodeSettings {
CachesHome = "inspectcode",
OutputFile = "inspectcodereport.xml",
ArgumentCustomization = arg => {
if (AppVeyor.IsRunningOnAppVeyor) // Don't flood CI output
arg.Append("--verbosity:WARN");
return arg;
},
});
int returnCode = StartProcess(nVikaToolPath, $@"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors");
if (returnCode != 0)
throw new Exception($"inspectcode failed with return code {returnCode}");
});
Task("CodeFileSanity")
.Does(() => {
ValidateCodeSanity(new ValidateCodeSanitySettings {
RootDirectory = rootDirectory.FullPath,
IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor
});
});
Task("CodeAnalysis")
.IsDependentOn("CodeFileSanity")
.IsDependentOn("InspectCode");
RunTarget(target); | #addin "nuget:?package=CodeFileSanity&version=0.0.33"
#addin "nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2019.2.1"
#tool "nuget:?package=NVika.MSBuild&version=1.0.1"
var nVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First();
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "CodeAnalysis");
var configuration = Argument("configuration", "Release");
var rootDirectory = new DirectoryPath("..");
var sln = rootDirectory.CombineWithFilePath("osu.sln");
var desktopSlnf = rootDirectory.CombineWithFilePath("osu.Desktop.slnf");
///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////
// windows only because both inspectcode and nvika depend on net45
Task("InspectCode")
.WithCriteria(IsRunningOnWindows())
.Does(() => {
InspectCode(desktopSlnf, new InspectCodeSettings {
CachesHome = "inspectcode",
OutputFile = "inspectcodereport.xml",
ArgumentCustomization = arg => {
if (AppVeyor.IsRunningOnAppVeyor) // Don't flood CI output
arg.Append("--verbosity:WARN");
return arg;
},
});
int returnCode = StartProcess(nVikaToolPath, $@"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors");
if (returnCode != 0)
throw new Exception($"inspectcode failed with return code {returnCode}");
});
Task("CodeFileSanity")
.Does(() => {
ValidateCodeSanity(new ValidateCodeSanitySettings {
RootDirectory = rootDirectory.FullPath,
IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor
});
});
Task("CodeAnalysis")
.IsDependentOn("CodeFileSanity")
.IsDependentOn("InspectCode");
RunTarget(target); | mit | C# |
2d873e72c5995a68127aba84132aba91aebb7ef2 | add lastActivity field to Person (also type and nickName) [Issue 6] | darrenparkinson/SparkDotNet | Models/Person.cs | Models/Person.cs | using System;
using Newtonsoft.Json;
namespace SparkDotNet {
public class Person
{
public string id { get; set; }
public string[] emails { get; set; }
public string displayName { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string avatar { get; set; }
public string orgId { get; set; }
public string[] roles { get; set; }
public string[] licenses { get; set; }
public DateTime created { get; set; }
public string timeZone { get; set; }
public string status { get; set; }
public DateTime lastActivity {get; set;}
public string type {get; set;}
public string nickName {get; set;}
public override string ToString() {
return JsonConvert.SerializeObject(this);
}
}
} | using System;
using Newtonsoft.Json;
namespace SparkDotNet {
public class Person
{
public string id { get; set; }
public string[] emails { get; set; }
public string displayName { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string avatar { get; set; }
public string orgId { get; set; }
public string[] roles { get; set; }
public string[] licenses { get; set; }
public DateTime created { get; set; }
public string timeZone { get; set; }
public string status { get; set; }
public override string ToString() {
return JsonConvert.SerializeObject(this);
}
}
} | mit | C# |
470714854afc48f04143d5f25d2c25c6723745cb | Update Skills.cs | datanets/kask-kiosk,datanets/kask-kiosk | Models/Skills.cs | Models/Skills.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Empty.Models
{
public class Skills
{
public int Skill_ID { get; set; }
public string Skill_Name { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Empty.Models
{
public class Skills
{
public int skill_ID { get; set; }
public string skillName { get; set; }
}
} | mit | C# |
7c56c11e5a08feee2a0f689fc4d902c97cb93d55 | Add helper method | mbrit/MetroLog,mbrit/MetroLog,onovotny/MetroLog,thomasgalliker/MetroLog,mbrit/MetroLog,onovotny/MetroLog,onovotny/MetroLog,thomasgalliker/MetroLog,thomasgalliker/MetroLog | MetroLog/ILogManager.cs | MetroLog/ILogManager.cs | using System.IO;
using MetroLog.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MetroLog
{
public interface ILogManager
{
LoggingConfiguration DefaultConfiguration { get; }
ILogger GetLogger<T>(LoggingConfiguration config = null);
ILogger GetLogger(Type type, LoggingConfiguration config = null);
ILogger GetLogger(string name, LoggingConfiguration config = null);
event EventHandler<LoggerEventArgs> LoggerCreated;
/// <summary>
/// Returns a zip archive stream of the logs folder
/// </summary>
/// <returns>Null if no file logger is attached</returns>
Task<Stream> GetCompressedLogs();
}
/// <summary>
/// Marker interface for enabling the Log() mixin
/// </summary>
public interface ICanLog
{
}
public static class LogManagerMixins
{
public static ILogger Log<T>(this T This, LoggingConfiguration config = null) where T : ICanLog
{
return LogManagerFactory.DefaultLogManager.GetLogger<T>(config);
}
}
}
| using System.IO;
using MetroLog.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MetroLog
{
public interface ILogManager
{
LoggingConfiguration DefaultConfiguration { get; }
ILogger GetLogger<T>(LoggingConfiguration config = null);
ILogger GetLogger(Type type, LoggingConfiguration config = null);
ILogger GetLogger(string name, LoggingConfiguration config = null);
event EventHandler<LoggerEventArgs> LoggerCreated;
/// <summary>
/// Returns a zip archive stream of the logs folder
/// </summary>
/// <returns>Null if no file logger is attached</returns>
Task<Stream> GetCompressedLogs();
}
}
| mit | C# |
3cbe5d7ddc0ef42b0dd3605183b923ccc71a1bd0 | Fix fading: reset opacity afterwards | Procrat/orpheus | Assets/Scripts/Ghost.cs | Assets/Scripts/Ghost.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ghost : MonoBehaviour
{
public float floatSpeed;
public GameObject playerManager;
private bool gonnaPossess = false;
private GameObject possessee = null;
private Vector2 possessPath;
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "enemy") {
playerManager.GetComponent<PlayerManager>().BeginPossess(other.gameObject);
}
else
if(other.gameObject.name == "Lady")
{
playerManager.GetComponent<PlayerManager>().Win();
}
}
private void FixedUpdate ()
{
if (gonnaPossess) {
MoveTowards();
} else {
FloatUp();
}
}
private void FloatUp() {
transform.Translate (floatSpeed * Vector2.up);
}
public void GoAndPossess(GameObject possessee)
{
gonnaPossess = true;
this.possessee = possessee;
possessPath = possessee.transform.position - transform.position;
}
private void MoveTowards()
{
Vector2 direction = possessee.transform.position - transform.position;
Vector2 moveVector = Vector2.ClampMagnitude(direction, floatSpeed);
if (moveVector.magnitude < floatSpeed - 0.0001)
{
Debug.Log("Actually possessing...");
gonnaPossess = false;
this.GetComponent<SpriteRenderer>().material.color = new Color(1, 1, 1, 1);
playerManager.GetComponent<PlayerManager>().ActuallyPossess(possessee);
}
else
{
float fadeFactor = direction.magnitude / possessPath.magnitude;
this.GetComponent<SpriteRenderer>().material.color = new Color(1, 1, 1, fadeFactor);
transform.Translate(moveVector);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ghost : MonoBehaviour
{
public float floatSpeed;
public GameObject playerManager;
private bool gonnaPossess = false;
private GameObject possessee = null;
private Vector2 possessPath;
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "enemy") {
playerManager.GetComponent<PlayerManager>().BeginPossess(other.gameObject);
}
else
if(other.gameObject.name == "Lady")
{
playerManager.GetComponent<PlayerManager>().Win();
}
}
private void FixedUpdate ()
{
if (gonnaPossess) {
MoveTowards();
} else {
FloatUp();
}
}
private void FloatUp() {
transform.Translate (floatSpeed * Vector2.up);
}
public void GoAndPossess(GameObject possessee)
{
gonnaPossess = true;
this.possessee = possessee;
possessPath = possessee.transform.position - transform.position;
}
private void MoveTowards()
{
Vector2 direction = possessee.transform.position - transform.position;
Vector2 moveVector = Vector2.ClampMagnitude(direction, floatSpeed);
float fadeFactor = direction.magnitude / possessPath.magnitude;
this.GetComponent<SpriteRenderer>().material.color = new Color(1, 1, 1, fadeFactor);
if (moveVector.magnitude < floatSpeed - 0.0001)
{
Debug.Log("Actually possessing...");
gonnaPossess = false;
playerManager.GetComponent<PlayerManager>().ActuallyPossess(possessee);
}
else
{
transform.Translate(moveVector);
}
}
}
| mit | C# |
949b53d10729c4819cec7ee3ee9e6a0b13dd3323 | Update TitleEstimateController.cs | bigfont/webapi-cors | CORS/Controllers/TitleEstimateController.cs | CORS/Controllers/TitleEstimateController.cs | using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors;
namespace CORS.Controllers
{
public class TitleEstimateController : ApiController
{
public class EstimateQuery
{
public string username { get; set; }
}
public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
{
// All the values in "query" are null or zero
// Do some stuff with query if there were anything to do
if(query != null && query.username != null)
{
return Ok(query.username);
}
else
{
return Ok("Add a username!");
}
}
}
}
| public class TitleEstimateController : ApiController
{
public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query)
{
// All the values in "query" are null or zero
// Do some stuff with query if there were anything to do
}
}
public class EstimateQuery
{
// Various fields
}
| mit | C# |
9ddfbf051e648d5da7816ccfb3817266f6455e56 | Allow VisualStudioExperimentationService to initialize on a background thread | gafter/roslyn,genlu/roslyn,panopticoncentral/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,AlekseyTs/roslyn,diryboy/roslyn,tmat/roslyn,dotnet/roslyn,jmarolf/roslyn,physhi/roslyn,mavasani/roslyn,dotnet/roslyn,nguerrera/roslyn,heejaechang/roslyn,jmarolf/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn,DustinCampbell/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,agocke/roslyn,diryboy/roslyn,jcouv/roslyn,jasonmalinowski/roslyn,swaroop-sridhar/roslyn,swaroop-sridhar/roslyn,abock/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,tmat/roslyn,VSadov/roslyn,abock/roslyn,brettfo/roslyn,AlekseyTs/roslyn,genlu/roslyn,brettfo/roslyn,aelij/roslyn,panopticoncentral/roslyn,sharwell/roslyn,jcouv/roslyn,VSadov/roslyn,KirillOsenkov/roslyn,aelij/roslyn,MichalStrehovsky/roslyn,VSadov/roslyn,davkean/roslyn,genlu/roslyn,jasonmalinowski/roslyn,DustinCampbell/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,tannergooding/roslyn,physhi/roslyn,dotnet/roslyn,heejaechang/roslyn,reaction1989/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,weltkante/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,MichalStrehovsky/roslyn,bartdesmet/roslyn,sharwell/roslyn,reaction1989/roslyn,nguerrera/roslyn,mavasani/roslyn,brettfo/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,jcouv/roslyn,stephentoub/roslyn,reaction1989/roslyn,bartdesmet/roslyn,weltkante/roslyn,tmat/roslyn,bartdesmet/roslyn,sharwell/roslyn,eriawan/roslyn,tannergooding/roslyn,abock/roslyn,ErikSchierboom/roslyn,gafter/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,swaroop-sridhar/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,agocke/roslyn,wvdd007/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,agocke/roslyn,KevinRansom/roslyn,wvdd007/roslyn,nguerrera/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,gafter/roslyn,davkean/roslyn,davkean/roslyn,eriawan/roslyn,aelij/roslyn | src/VisualStudio/Core/Def/Experimentation/VisualStudioExperimentationService.cs | src/VisualStudio/Core/Def/Experimentation/VisualStudioExperimentationService.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Composition;
using System.Reflection;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.Internal.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Experimentation
{
[ExportWorkspaceService(typeof(IExperimentationService), ServiceLayer.Host), Shared]
internal class VisualStudioExperimentationService : ForegroundThreadAffinitizedObject, IExperimentationService
{
private readonly object _experimentationServiceOpt;
private readonly MethodInfo _isCachedFlightEnabledInfo;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioExperimentationService(IThreadingContext threadingContext, SVsServiceProvider serviceProvider)
: base(threadingContext)
{
object experimentationServiceOpt = null;
MethodInfo isCachedFlightEnabledInfo = null;
threadingContext.JoinableTaskFactory.Run(async () =>
{
await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync();
try
{
experimentationServiceOpt = serviceProvider.GetService(typeof(SVsExperimentationService));
if (experimentationServiceOpt != null)
{
isCachedFlightEnabledInfo = experimentationServiceOpt.GetType().GetMethod(
"IsCachedFlightEnabled", BindingFlags.Public | BindingFlags.Instance);
}
}
catch
{
}
});
_experimentationServiceOpt = experimentationServiceOpt;
_isCachedFlightEnabledInfo = isCachedFlightEnabledInfo;
}
public bool IsExperimentEnabled(string experimentName)
{
ThisCanBeCalledOnAnyThread();
if (_isCachedFlightEnabledInfo != null)
{
try
{
return (bool)_isCachedFlightEnabledInfo.Invoke(_experimentationServiceOpt, new object[] { experimentName });
}
catch
{
}
}
return false;
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Composition;
using System.Reflection;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.Internal.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.Experimentation
{
[ExportWorkspaceService(typeof(IExperimentationService), ServiceLayer.Host), Shared]
internal class VisualStudioExperimentationService : ForegroundThreadAffinitizedObject, IExperimentationService
{
private readonly object _experimentationServiceOpt;
private readonly MethodInfo _isCachedFlightEnabledInfo;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioExperimentationService(IThreadingContext threadingContext, SVsServiceProvider serviceProvider)
: base(threadingContext, assertIsForeground: true)
{
try
{
_experimentationServiceOpt = serviceProvider.GetService(typeof(SVsExperimentationService));
if (_experimentationServiceOpt != null)
{
_isCachedFlightEnabledInfo = _experimentationServiceOpt.GetType().GetMethod(
"IsCachedFlightEnabled", BindingFlags.Public | BindingFlags.Instance);
}
}
catch
{
}
}
public bool IsExperimentEnabled(string experimentName)
{
ThisCanBeCalledOnAnyThread();
if (_isCachedFlightEnabledInfo != null)
{
try
{
return (bool)_isCachedFlightEnabledInfo.Invoke(_experimentationServiceOpt, new object[] { experimentName });
}
catch
{
}
}
return false;
}
}
}
| mit | C# |
2bdd2da769bad5c9ddbc707645cde558bf95a576 | Fix comment typo | ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot.github.io,ukahoot/ukahoot,ukahoot/ukahoot | tokenserver/src/Util.cs | tokenserver/src/Util.cs | using System;
using System.Text;
namespace UKahoot {
public static class Util {
public const string TOKEN_ENDPOINT = "https://kahoot.it/reserve/session/";
public const string ENDPOINT_URI = "https://kahoot.it/";
public const string ENDPOINT_HOST = "kahoot.it";
public static byte[] GetBytes(string txt) {
return Encoding.ASCII.GetBytes(txt);
}
public static class Responses {
public static byte[] InvalidMethod = GetBytes("<html><body><h1>Invalid HTTP Method</h1></body></html>");
public static byte[] RequestError = GetBytes("<html><body><h1>Request Processing Error</h1></body></html>");
public static byte[] InvalidQueryString = GetBytes("<html><body><h1>Invalid Query String</h1></body></html>");
public static byte[] InvalidRequest = GetBytes("<html><body><h1>Invalid Request</h1></body></html>");
}
public static int GetKahootTime() {
var TimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (int)TimeSpan.TotalSeconds;
}
public static string GetTokenRequestUri(int PID) {
return TOKEN_ENDPOINT + "/" + PID + "/?" + GetKahootTime();
}
public static string GetTokenResponse(string TokenHeader, string ResponseBody) {
// Replace and escape quotes to make valid JSON
ResponseBody = ResponseBody.Replace("\\\"", "%ESCAPED_QUOT%");
ResponseBody = ResponseBody.Replace("\"", "\\\"");
ResponseBody = ResponseBody.Replace("%ESCAPED_QUOT%", "\\\"");
// Build the JSON string
StringBuilder TokenBuilder = new StringBuilder("");
TokenBuilder.Append("{\"tokenHeader\":\"");
TokenBuilder.Append(TokenHeader);
TokenBuilder.Append("\"");
TokenBuilder.Append(",\"responseBody\":");
TokenBuilder.Append("\"");
TokenBuilder.Append(ResponseBody);
TokenBuilder.Append("\"}");
return TokenBuilder.ToString();
}
public static string GetErrorResponse(string ResponseCode) {
StringBuilder ErrorBuilder = new StringBuilder("");
ErrorBuilder.Append("{'error':true,");
ErrorBuilder.Append("'responseCode':");
ErrorBuilder.Append("'");
ErrorBuilder.Append(ResponseCode);
ErrorBuilder.Append("'}");
return ErrorBuilder.ToString();
}
}
} | using System;
using System.Text;
namespace UKahoot {
public static class Util {
public const string TOKEN_ENDPOINT = "https://kahoot.it/reserve/session/";
public const string ENDPOINT_URI = "https://kahoot.it/";
public const string ENDPOINT_HOST = "kahoot.it";
public static byte[] GetBytes(string txt) {
return Encoding.ASCII.GetBytes(txt);
}
public static class Responses {
public static byte[] InvalidMethod = GetBytes("<html><body><h1>Invalid HTTP Method</h1></body></html>");
public static byte[] RequestError = GetBytes("<html><body><h1>Request Processing Error</h1></body></html>");
public static byte[] InvalidQueryString = GetBytes("<html><body><h1>Invalid Query String</h1></body></html>");
public static byte[] InvalidRequest = GetBytes("<html><body><h1>Invalid Request</h1></body></html>");
}
public static int GetKahootTime() {
var TimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
return (int)TimeSpan.TotalSeconds;
}
public static string GetTokenRequestUri(int PID) {
return TOKEN_ENDPOINT + "/" + PID + "/?" + GetKahootTime();
}
public static string GetTokenResponse(string TokenHeader, string ResponseBody) {
// Replace and escape quotes to make valid JSONd
ResponseBody = ResponseBody.Replace("\\\"", "%ESCAPED_QUOT%");
ResponseBody = ResponseBody.Replace("\"", "\\\"");
ResponseBody = ResponseBody.Replace("%ESCAPED_QUOT%", "\\\"");
// Build the JSON string
StringBuilder TokenBuilder = new StringBuilder("");
TokenBuilder.Append("{\"tokenHeader\":\"");
TokenBuilder.Append(TokenHeader);
TokenBuilder.Append("\"");
TokenBuilder.Append(",\"responseBody\":");
TokenBuilder.Append("\"");
TokenBuilder.Append(ResponseBody);
TokenBuilder.Append("\"}");
return TokenBuilder.ToString();
}
public static string GetErrorResponse(string ResponseCode) {
StringBuilder ErrorBuilder = new StringBuilder("");
ErrorBuilder.Append("{'error':true,");
ErrorBuilder.Append("'responseCode':");
ErrorBuilder.Append("'");
ErrorBuilder.Append(ResponseCode);
ErrorBuilder.Append("'}");
return ErrorBuilder.ToString();
}
}
} | mit | C# |
c7e473e2203e9c5ecea6d12c8e272f34cf93f07b | Set StateId in DataTokens so ShieldDecode works because StateId was in the data when ShieldEncode was called | grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation | NavigationMvc/RouteConfig.cs | NavigationMvc/RouteConfig.cs | using System.Web.Mvc;
using System.Web.Routing;
namespace Navigation.Mvc
{
public class RouteConfig
{
public static void AddStateRoutes()
{
if (StateInfoConfig.Dialogs == null)
return;
string controller, action;
Route route;
using (RouteTable.Routes.GetWriteLock())
{
foreach (Dialog dialog in StateInfoConfig.Dialogs)
{
foreach (State state in dialog.States)
{
controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty;
action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty;
if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0)
{
state.StateHandler = new MvcStateHandler();
route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route);
route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route);
route.Defaults["controller"] = controller;
route.Defaults["action"] = action;
route.DataTokens = new RouteValueDictionary() { { NavigationSettings.Config.StateIdKey, state.Id } };
route.RouteHandler = new MvcStateRouteHandler(state);
}
}
}
}
}
}
}
| using System.Web.Mvc;
using System.Web.Routing;
namespace Navigation.Mvc
{
public class RouteConfig
{
public static void AddStateRoutes()
{
if (StateInfoConfig.Dialogs == null)
return;
string controller, action;
Route route;
using (RouteTable.Routes.GetWriteLock())
{
foreach (Dialog dialog in StateInfoConfig.Dialogs)
{
foreach (State state in dialog.States)
{
controller = state.Attributes["controller"] != null ? state.Attributes["controller"].Trim() : string.Empty;
action = state.Attributes["action"] != null ? state.Attributes["action"].Trim() : string.Empty;
if (controller.Length != 0 && action.Length != 0 && state.Route.Length != 0)
{
state.StateHandler = new MvcStateHandler();
route = RouteTable.Routes.MapRoute("Mvc" + state.Id, state.Route);
route.Defaults = StateInfoConfig.GetRouteDefaults(state, state.Route);
route.Defaults["controller"] = controller;
route.Defaults["action"] = action;
route.RouteHandler = new MvcStateRouteHandler(state);
}
}
}
}
}
}
}
| apache-2.0 | C# |
d397882f8d7d4029509e64fc08844b60552b9513 | Add more functionality to the EthernetFrame class | shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg,shutej/tapcfg | trunk/src/bindings/EthernetFrame.cs | trunk/src/bindings/EthernetFrame.cs |
using System;
namespace TAPCfg {
public class EthernetFrame {
private byte[] data;
private byte[] src = new byte[6];
private byte[] dst = new byte[6];
private int etherType;
public EthernetFrame(byte[] data) {
this.data = data;
Array.Copy(data, 0, dst, 0, 6);
Array.Copy(data, 6, src, 0, 6);
etherType = (data[12] << 8) | data[13];
}
public byte[] Data {
get { return data; }
}
public int Length {
get { return data.Length; }
}
public byte[] SourceAddress {
get { return src; }
}
public byte[] DestinationAddress {
get { return dst; }
}
public int EtherType {
get { return etherType; }
}
public byte[] Payload {
get {
byte[] ret = new byte[data.Length - 14];
Array.Copy(data, 14, ret, 0, ret.Length);
return ret;
}
}
}
}
|
namespace TAPCfg {
public class EthernetFrame {
private byte[] data;
public EthernetFrame(byte[] data) {
this.data = data;
}
public byte[] Data {
get {
return data;
}
}
}
}
| lgpl-2.1 | C# |
768d695ee381741cc39bc0be6a779d09bde8ec59 | Remove "(UTC)" | mayuki/PlatformStatusTracker,mayuki/PlatformStatusTracker,mayuki/PlatformStatusTracker | PlatformStatusTracker/PlatformStatusTracker.Web/Views/Home/Changes.cshtml | PlatformStatusTracker/PlatformStatusTracker.Web/Views/Home/Changes.cshtml | @using System.Globalization
@using System.Text
@using PlatformStatusTracker.Core.Data
@using PlatformStatusTracker.Core.Model
@model PlatformStatusTracker.Web.ViewModels.Home.ChangesViewModel
@{
ViewBag.Title = Model.Date.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo) + " - Changes";
}
<article>
<h1>@Model.Date.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo)</h1>
@Html.Partial("Partial/ChangeSets", Model.ChangeSets)
</article>
| @using System.Globalization
@using System.Text
@using PlatformStatusTracker.Core.Data
@using PlatformStatusTracker.Core.Model
@model PlatformStatusTracker.Web.ViewModels.Home.ChangesViewModel
@{
ViewBag.Title = Model.Date.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo) + " - Changes";
}
<article>
<h1>@Model.Date.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo) (UTC)</h1>
@Html.Partial("Partial/ChangeSets", Model.ChangeSets)
</article>
| mit | C# |
ed4111f3c1eccfc5b49d17f75c3fc266d407a431 | fix assy properties | AndyPook/Slack | SlackAPI/Properties/AssemblyInfo.cs | SlackAPI/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("Pook.SlackAPI")]
[assembly: AssemblyDescription("A simple Slack integration library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pook")]
[assembly: AssemblyProduct("Pook.SlackAPI")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("d67d593d-29d1-47b8-950c-80baac8af01c")]
// 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("Artesian.SlackAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Artesian.SlackAPI")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("d67d593d-29d1-47b8-950c-80baac8af01c")]
// 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# |
dbdf8d44f5c7b21f35c8324083902f5bd8dcd8bd | Update hostname from dev to sandbox | Payoneer-Escrow/payoneer-escrow-csharp-dotnet | PayoneerEscrow/Api/Client.cs | PayoneerEscrow/Api/Client.cs | namespace PayoneerEscrow.Api {
/// <summary>
/// Class Client
/// </summary>
public class Client {
///////////////////////////////////////////////////////////////////////
// PROPERTIES ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <summary>
/// The authenticator object that handles authenticating requests made to the API.
/// </summary>
protected Authenticator authenticator;
/// <summary>
/// A flag to tell the client to make requests to the sandbox environment.
/// </summary>
protected bool use_sandbox;
///////////////////////////////////////////////////////////////////////
// CONSTRUCTOR ///////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <summary>
/// Construct a new client for making requests to the Payoneer Escrow API.
/// </summary>
/// <param name="api_key">Your API key.</param>
/// <param name="api_secret">Your API secret.</param>
/// <param name="sandbox">Use the sandbox environment?</param>
public Client(string api_key, string api_secret, bool sandbox = false) {
this.authenticator = new Authenticator(api_key, api_secret);
this.use_sandbox = sandbox;
}
///////////////////////////////////////////////////////////////////////
// PUBLIC ////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <summary>
/// <para>
/// Get an Accounts resource object to make requests to:
/// /accounts
/// </para>
/// <para>
/// Example call to get all accounts:
/// Function call: client.Accounts().All();
/// Makes request to: /accounts
/// </para>
/// <para>
/// Example call to get a single account:
/// Function call: client.Accounts().Get(account_id);
/// Makes request to: /accounts/{account_id}
/// </para>
/// <para>
/// Example call to create a new account:
/// Function call: client.Accounts().Create(data);
/// Makes request to: /accounts
/// </para>
/// <para>
/// Example call to update an existing account:
/// Function call: client.Accounts().Update(account_id, data);
/// Makes request to: /accounts/{account_id}
/// </para>
/// </summary>
/// <returns>Returns an Accounts resource object.</returns>
public Resource.Accounts Accounts() {
return new Resource.Accounts(
this.GetApiHostname(),
this.authenticator,
"");
}
///////////////////////////////////////////////////////////////////////
// PROTECTED /////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <summary>
/// Get the Payoneer Escrow application hostname to use for requests.
/// </summary>
/// <returns>Returns the Payoneer Escrow hostname to use for requests.</returns>
protected string GetApiHostname() {
if (this.use_sandbox) {
return "https://sandbox.armorpayments.com";
}
return "https://pay.payoneer.com";
}
}
}
| namespace PayoneerEscrow.Api {
/// <summary>
/// Class Client
/// </summary>
public class Client {
///////////////////////////////////////////////////////////////////////
// PROPERTIES ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <summary>
/// The authenticator object that handles authenticating requests made to the API.
/// </summary>
protected Authenticator authenticator;
/// <summary>
/// A flag to tell the client to make requests to the sandbox environment.
/// </summary>
protected bool use_sandbox;
///////////////////////////////////////////////////////////////////////
// CONSTRUCTOR ///////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <summary>
/// Construct a new client for making requests to the Payoneer Escrow API.
/// </summary>
/// <param name="api_key">Your API key.</param>
/// <param name="api_secret">Your API secret.</param>
/// <param name="sandbox">Use the sandbox environment?</param>
public Client(string api_key, string api_secret, bool sandbox = false) {
this.authenticator = new Authenticator(api_key, api_secret);
this.use_sandbox = sandbox;
}
///////////////////////////////////////////////////////////////////////
// PUBLIC ////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <summary>
/// <para>
/// Get an Accounts resource object to make requests to:
/// /accounts
/// </para>
/// <para>
/// Example call to get all accounts:
/// Function call: client.Accounts().All();
/// Makes request to: /accounts
/// </para>
/// <para>
/// Example call to get a single account:
/// Function call: client.Accounts().Get(account_id);
/// Makes request to: /accounts/{account_id}
/// </para>
/// <para>
/// Example call to create a new account:
/// Function call: client.Accounts().Create(data);
/// Makes request to: /accounts
/// </para>
/// <para>
/// Example call to update an existing account:
/// Function call: client.Accounts().Update(account_id, data);
/// Makes request to: /accounts/{account_id}
/// </para>
/// </summary>
/// <returns>Returns an Accounts resource object.</returns>
public Resource.Accounts Accounts() {
return new Resource.Accounts(
this.GetApiHostname(),
this.authenticator,
"");
}
///////////////////////////////////////////////////////////////////////
// PROTECTED /////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
/// <summary>
/// Get the Payoneer Escrow application hostname to use for requests.
/// </summary>
/// <returns>Returns the Payoneer Escrow hostname to use for requests.</returns>
protected string GetApiHostname() {
if (this.use_sandbox) {
return "http://dev.armorpayments.com";
}
return "https://pay.payoneer.com";
}
}
}
| mit | C# |
a966a17aed94b11b4b1b117daf1d285208758c20 | fix MissingIntPtrCtorException | Dynalon/banshee-osx,GNOME/banshee,stsundermann/banshee,arfbtwn/banshee,dufoli/banshee,GNOME/banshee,Dynalon/banshee-osx,ixfalia/banshee,arfbtwn/banshee,babycaseny/banshee,dufoli/banshee,arfbtwn/banshee,Carbenium/banshee,stsundermann/banshee,babycaseny/banshee,babycaseny/banshee,Dynalon/banshee-osx,babycaseny/banshee,GNOME/banshee,Dynalon/banshee-osx,Dynalon/banshee-osx,dufoli/banshee,Dynalon/banshee-osx,ixfalia/banshee,dufoli/banshee,Carbenium/banshee,Carbenium/banshee,stsundermann/banshee,dufoli/banshee,Carbenium/banshee,arfbtwn/banshee,dufoli/banshee,stsundermann/banshee,GNOME/banshee,Carbenium/banshee,ixfalia/banshee,stsundermann/banshee,babycaseny/banshee,dufoli/banshee,babycaseny/banshee,Dynalon/banshee-osx,stsundermann/banshee,ixfalia/banshee,dufoli/banshee,GNOME/banshee,babycaseny/banshee,GNOME/banshee,arfbtwn/banshee,Carbenium/banshee,ixfalia/banshee,babycaseny/banshee,Dynalon/banshee-osx,arfbtwn/banshee,arfbtwn/banshee,stsundermann/banshee,arfbtwn/banshee,ixfalia/banshee,stsundermann/banshee,ixfalia/banshee,GNOME/banshee,ixfalia/banshee,GNOME/banshee | src/Extensions/Banshee.Audiobook/Banshee.Audiobook/AudiobookGrid.cs | src/Extensions/Banshee.Audiobook/Banshee.Audiobook/AudiobookGrid.cs | //
// AudiobookGrid.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, 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;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Data;
using Hyena.Data.Gui;
using Banshee.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Collection.Gui;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Sources.Gui;
using Banshee.Web;
namespace Banshee.Audiobook
{
public class AudiobookGrid : SearchableListView<AlbumInfo>
{
private AudiobookLibrarySource library;
public AudiobookGrid ()
{
var layout = new DataViewLayoutGrid () {
ChildAllocator = () => new DataViewChildAlbum () {
ImageSize = 180
},
View = this
};
ViewLayout = layout;
RowActivated += (o, a) => library.Actions["AudiobookOpen"].Activate ();
}
protected AudiobookGrid (IntPtr raw) : base ()
{
}
public void SetLibrary (AudiobookLibrarySource library)
{
SetModel (library.BooksModel);
this.library = library;
}
public override bool SelectOnRowFound {
get { return true; }
}
protected override bool OnPopupMenu ()
{
library.Actions["AudiobookBookPopup"].Activate ();
return true;
}
}
}
| //
// AudiobookGrid.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, 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;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Data;
using Hyena.Data.Gui;
using Banshee.Widgets;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Collection.Gui;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Banshee.Sources.Gui;
using Banshee.Web;
namespace Banshee.Audiobook
{
public class AudiobookGrid : SearchableListView<AlbumInfo>
{
private AudiobookLibrarySource library;
public AudiobookGrid ()
{
var layout = new DataViewLayoutGrid () {
ChildAllocator = () => new DataViewChildAlbum () {
ImageSize = 180
},
View = this
};
ViewLayout = layout;
RowActivated += (o, a) => library.Actions["AudiobookOpen"].Activate ();
}
public void SetLibrary (AudiobookLibrarySource library)
{
SetModel (library.BooksModel);
this.library = library;
}
public override bool SelectOnRowFound {
get { return true; }
}
protected override bool OnPopupMenu ()
{
library.Actions["AudiobookBookPopup"].Activate ();
return true;
}
}
}
| mit | C# |
2ae30d206d8ac4ea938d659405883fd528184920 | Drop relay fee to 0.001 DCR/kB. | decred/Paymetheus,jrick/Paymetheus | Paymetheus.Decred/Wallet/TransactionFees.cs | Paymetheus.Decred/Wallet/TransactionFees.cs | // Copyright (c) 2016 The btcsuite developers
// Copyright (c) 2016 The Decred developers
// Licensed under the ISC license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
namespace Paymetheus.Decred.Wallet
{
public static class TransactionFees
{
public static readonly Amount DefaultFeePerKb = (long)1e5;
public static Amount FeeForSerializeSize(Amount feePerKb, int txSerializeSize)
{
if (feePerKb < 0)
throw Errors.RequireNonNegative(nameof(feePerKb));
if (txSerializeSize < 0)
throw Errors.RequireNonNegative(nameof(txSerializeSize));
var fee = feePerKb * txSerializeSize / 1000;
if (fee == 0 && feePerKb > 0)
fee = feePerKb;
if (!TransactionRules.IsSaneOutputValue(fee))
throw new TransactionRuleException($"Fee of {fee} is invalid");
return fee;
}
public static Amount ActualFee(Transaction tx, Amount totalInput)
{
if (tx == null)
throw new ArgumentNullException(nameof(tx));
if (totalInput < 0)
throw Errors.RequireNonNegative(nameof(totalInput));
var totalOutput = tx.Outputs.Sum(o => o.Amount);
return totalInput - totalOutput;
}
public static Amount EstimatedFeePerKb(Transaction tx, Amount totalInput)
{
if (tx == null)
throw new ArgumentNullException(nameof(tx));
if (totalInput < 0)
throw Errors.RequireNonNegative(nameof(totalInput));
var estimatedSize = Transaction.EstimateSerializeSize(tx.Inputs.Length, tx.Outputs, false);
var actualFee = ActualFee(tx, totalInput);
return actualFee * 1000 / estimatedSize;
}
}
} | // Copyright (c) 2016 The btcsuite developers
// Copyright (c) 2016 The Decred developers
// Licensed under the ISC license. See LICENSE file in the project root for full license information.
using Paymetheus.Decred.Script;
using System;
using System.Linq;
namespace Paymetheus.Decred.Wallet
{
public static class TransactionFees
{
public static readonly Amount DefaultFeePerKb = 1000000;
public static Amount FeeForSerializeSize(Amount feePerKb, int txSerializeSize)
{
if (feePerKb < 0)
throw Errors.RequireNonNegative(nameof(feePerKb));
if (txSerializeSize < 0)
throw Errors.RequireNonNegative(nameof(txSerializeSize));
var fee = feePerKb * txSerializeSize / 1000;
if (fee == 0 && feePerKb > 0)
fee = feePerKb;
if (!TransactionRules.IsSaneOutputValue(fee))
throw new TransactionRuleException($"Fee of {fee} is invalid");
return fee;
}
public static Amount ActualFee(Transaction tx, Amount totalInput)
{
if (tx == null)
throw new ArgumentNullException(nameof(tx));
if (totalInput < 0)
throw Errors.RequireNonNegative(nameof(totalInput));
var totalOutput = tx.Outputs.Sum(o => o.Amount);
return totalInput - totalOutput;
}
public static Amount EstimatedFeePerKb(Transaction tx, Amount totalInput)
{
if (tx == null)
throw new ArgumentNullException(nameof(tx));
if (totalInput < 0)
throw Errors.RequireNonNegative(nameof(totalInput));
var estimatedSize = Transaction.EstimateSerializeSize(tx.Inputs.Length, tx.Outputs, false);
var actualFee = ActualFee(tx, totalInput);
return actualFee * 1000 / estimatedSize;
}
}
} | isc | C# |
7a4a9acf58b1ac1cea610b8f738f08d4492b2bec | fix ValueAsync | geeklearningio/gl-dotnet-domain | src/GeekLearning.Domain/MaybeExtensions.cs | src/GeekLearning.Domain/MaybeExtensions.cs | namespace GeekLearning.Domain
{
using System.Threading.Tasks;
public static class MaybeExtensions
{
public async static Task<T> ValueAsync<T>(this Task<Maybe<T>> maybeTask) where T : class
{
return (await maybeTask).Value;
}
}
}
| namespace GeekLearning.Domain
{
using System.Threading.Tasks;
public static class MaybeExtensions
{
public async static Task<Maybe<T>> ValueAsync<T>(this Task<Maybe<T>> maybeTask) where T : class
{
return (await maybeTask).Value;
}
}
}
| mit | C# |
7526f217510a2d141528f74279b49ea4dd4f191e | Use auto-version for AssemblyFileVersion in develop builds to facilitate installers | l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,PowerOfCode/Eto | Source/Shared/GlobalAssemblyInfo.cs | Source/Shared/GlobalAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Picoe Software Solutions Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.99.0.0")]
[assembly: AssemblyFileVersion("1.99.*")]
[assembly: AssemblyInformationalVersion("1.99.0")]
| using System.Reflection;
[assembly: AssemblyCompany("Picoe Software Solutions Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2010-2014 by Curtis Wensley, 2012-2014 by Vivek Jhaveri and contributors")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.99.0.0")]
[assembly: AssemblyFileVersion("1.99.0.0")]
[assembly: AssemblyInformationalVersion("1.99.0")]
| bsd-3-clause | C# |
1c5756ba2b994f1737341e77dea2e6cff0625d0a | add reference to Package for instructions | Willster419/RelicModManager,Willster419/RelhaxModpack,Willster419/RelhaxModpack | RelhaxModpack/RelhaxModpack/Installer/Instruction.cs | RelhaxModpack/RelhaxModpack/Installer/Instruction.cs | using RelhaxModpack.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RelhaxModpack.Installer
{
public abstract class Instruction : XmlDatabaseComponent
{
public Instruction() : base()
{
}
public Instruction(Instruction instructionToCopy) : base(instructionToCopy)
{
}
public abstract string[] PropertiesToSerialize();
public abstract string RootObjectPath { get; }
public string SchemaVersionLocal { get; set; }
/// <summary>
/// A single string with the filename of the processingNativeFile (needed for tracing work instructions after installation)
/// </summary>
public string NativeProcessingFile { get; set; } = string.Empty;
/// <summary>
/// the actual name of the original patch before processed
/// </summary>
public string ActualPatchName { get; set; } = string.Empty;
public DatabasePackage Package { get; set; }
public virtual string DumpInfoToLog
{
get
{
return string.Format("{0}={1}, {1}={2}", nameof(NativeProcessingFile), NativeProcessingFile, nameof(ActualPatchName), ActualPatchName);
}
}
public abstract bool InstructionsEqual(Instruction instructionToCompare);
}
}
| using RelhaxModpack.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RelhaxModpack.Installer
{
public abstract class Instruction : XmlDatabaseComponent
{
public Instruction() : base()
{
}
public Instruction(Instruction instructionToCopy) : base(instructionToCopy)
{
}
public abstract string[] PropertiesToSerialize();
public abstract string RootObjectPath { get; }
public string SchemaVersionLocal { get; set; }
/// <summary>
/// A single string with the filename of the processingNativeFile (needed for tracing work instructions after installation)
/// </summary>
public string NativeProcessingFile { get; set; } = string.Empty;
/// <summary>
/// the actual name of the original patch before processed
/// </summary>
public string ActualPatchName { get; set; } = string.Empty;
public virtual string DumpInfoToLog
{
get
{
return string.Format("{0}={1}, {1}={2}", nameof(NativeProcessingFile), NativeProcessingFile, nameof(ActualPatchName), ActualPatchName);
}
}
public abstract bool InstructionsEqual(Instruction instructionToCompare);
}
}
| apache-2.0 | C# |
b338f40249e45d89c4134cc61fb076b487de75db | Fix bug with non-HTML responses | OlsonDev/PersonalWebApp,OlsonDev/PersonalWebApp | Middleware/StripWhitespaceMiddleware.cs | Middleware/StripWhitespaceMiddleware.cs | using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace PersonalWebApp.Middleware {
public class StripWhitespaceMiddleware {
private readonly RequestDelegate _next;
public StripWhitespaceMiddleware(RequestDelegate next) {
_next = next;
}
public async Task Invoke(HttpContext context) {
var body = context.Response.Body;
using (var intercept = new MemoryStream()) {
context.Response.Body = intercept;
await _next.Invoke(context);
var contentType = context.Response.ContentType ?? "";
if (contentType.StartsWith("text/html")) {
intercept.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(intercept)) {
var responseBody = await reader.ReadToEndAsync();
var stripped = Regex.Replace(responseBody, @">\s+<", "><");
var bytes = Encoding.UTF8.GetBytes(stripped);
await body.WriteAsync(bytes, 0, bytes.Length);
}
} else {
intercept.Seek(0, SeekOrigin.Begin);
await intercept.CopyToAsync(body);
}
}
}
}
} | using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace PersonalWebApp.Middleware {
public class StripWhitespaceMiddleware {
private readonly RequestDelegate _next;
public StripWhitespaceMiddleware(RequestDelegate next) {
_next = next;
}
public async Task Invoke(HttpContext context) {
var body = context.Response.Body;
using (var intercept = new MemoryStream()) {
context.Response.Body = intercept;
await _next.Invoke(context);
var contentType = context.Response.ContentType ?? "";
if (contentType.StartsWith("text/html")) {
intercept.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(intercept)) {
var responseBody = await reader.ReadToEndAsync();
var stripped = Regex.Replace(responseBody, @">\s+<", "><");
var bytes = Encoding.UTF8.GetBytes(stripped);
await body.WriteAsync(bytes, 0, bytes.Length);
}
} else {
await intercept.CopyToAsync(body);
}
}
}
}
} | mit | C# |
5ce17caa0ad3fe82a10cc003f4d5e481816d37bd | Include missing views AddNews and EditNews in project. | razsilev/Sv_Naum,razsilev/Sv_Naum,razsilev/Sv_Naum | Source/SvNaum.Web/App_Start/FilterConfig.cs | Source/SvNaum.Web/App_Start/FilterConfig.cs | using System.Web;
using System.Web.Mvc;
namespace SvNaum.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| using System.Web;
using System.Web.Mvc;
namespace SvNaum.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//filters.Add(new HandleErrorAttribute());
}
}
}
| mit | C# |
6b424ac2137e95dc793517e2e0b085744564e7a7 | Add support for building from the command line. | adbre/cab42,adbre/cab42 | CAB42/Program.cs | CAB42/Program.cs | namespace C42A
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
using C42A.CAB42;
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static int Main(string[] args)
{
if (args.Length > 0 && args[0] == "build")
{
AllocConsole();
if (args.Length != 2) Console.WriteLine("cab42.exe build PATH");
try
{
Build(args[1]);
}
catch (Exception error)
{
Console.Error.WriteLine(error.ToString());
return 1;
}
return 0;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var f = new global::C42A.CAB42.Windows.Forms.CAB42())
{
if (args != null && args.Length > 0)
{
if (args.Length == 1)
{
f.OpenFileOnShow = args[0];
}
}
Application.Run(f);
}
return 0;
}
private static void Build(string file)
{
var buildProject = ProjectInfo.Open(file);
using (var buildContext = new CabwizBuildContext())
{
var tasks = buildProject.CreateBuildTasks();
var feedback = new BuildFeedbackBase(Console.Out);
buildContext.Build(tasks, feedback);
}
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
}
}
| namespace C42A
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static int Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using (var f = new global::C42A.CAB42.Windows.Forms.CAB42())
{
if (args != null && args.Length > 0)
{
if (args.Length == 1)
{
f.OpenFileOnShow = args[0];
}
}
Application.Run(f);
}
return 0;
}
}
}
| apache-2.0 | C# |
70961c3b57c6544d59943b2466cdf6be703ef865 | Update Assembly Version | SolrNetLight/SolrNetLight | SolrNetLight/Properties/AssemblyInfo.cs | SolrNetLight/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SolRNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SolRNet")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.3")]
[assembly: AssemblyFileVersion("0.1.0.3")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SolRNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SolRNet")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.2")]
[assembly: AssemblyFileVersion("0.1.0.2")]
| apache-2.0 | C# |
1e1a07bfe26a9cc983a285793d5cc6d32d328e3d | add PasswordEntry.PlaceholderText sample | sevoku/xwt | TestApps/Samples/Samples/PasswordEntries.cs | TestApps/Samples/Samples/PasswordEntries.cs | //
// PasswordEntry.cs
//
// Author:
// Bojan Rajkovic <brajkovic@xamarin.com>
//
// Copyright (c) 2013 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;
using Xwt;
namespace Samples
{
public class PasswordEntries : VBox
{
public PasswordEntries ()
{
PasswordEntry te1 = new PasswordEntry ();
te1.PlaceholderText = "Enter Password ...";
PackStart (te1);
Button b = new Button ("Show password");
Label l = new Label ();
b.Clicked += (sender, e) => {
l.Text = ("Password is: " + te1.Password);
};
PackStart (b);
PackStart (l);
}
}
}
| //
// PasswordEntry.cs
//
// Author:
// Bojan Rajkovic <brajkovic@xamarin.com>
//
// Copyright (c) 2013 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;
using Xwt;
namespace Samples
{
public class PasswordEntries : VBox
{
public PasswordEntries ()
{
PasswordEntry te1 = new PasswordEntry ();
PackStart (te1);
Button b = new Button ("Show password");
Label l = new Label ();
b.Clicked += (sender, e) => {
l.Text = ("Password is: " + te1.Password);
};
PackStart (b);
PackStart (l);
}
}
}
| mit | C# |
cc3d7f696917dd87d16a237385dfe1576f97aee6 | Add full sample | aloisdg/edx-csharp | edX/Module1/Program.cs | edX/Module1/Program.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Module1
{
class Program
{
/// <summary>
/// Facebook allow 71 gender options
/// </summary>
public enum Gender
{
Male,
Female,
Other
}
public enum SchoolStatus
{
Student,
Professor,
Other
}
/// <summary>
/// AddressLine3 is required for some countries like France
/// </summary>
public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
public abstract class APerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Birthdate { get; set; }
public Address Address { get; set; }
public Gender Gender { get; set; }
public abstract SchoolStatus SchoolStatus { get; }
}
public class Student : APerson
{
public override SchoolStatus SchoolStatus { get { return SchoolStatus.Student; }}
}
public class Professor : APerson
{
public override SchoolStatus SchoolStatus { get { return SchoolStatus.Professor; }}
}
public class Degree
{
public string Name { get; set; }
public string FullName { get; set; }
public int CreditsRequired { get; set; }
}
public class University
{
public string Name { get; set; }
public string FullName { get; set; }
public Address Adress { get; set; }
public IEnumerable<Degree> Degrees { get; set; }
public IEnumerable<Student> Students { get; set; }
public IEnumerable<Professor> Professors { get; set; }
}
static void Main(string[] args)
{
var hogwarts = new University
{
Name = "Hogwarts",
FullName = "Hogwarts School of Witchcraft and Wizardry",
Adress = new Address { Country = "Scotland"},
Degrees = new Collection<Degree>
{
new Degree
{
Name = "O.W.L.",
FullName = "Ordinary Wizarding Level",
CreditsRequired = 180
},
new Degree
{
Name = "N.E.W.T.",
FullName = "Nastily Exhausting Wizarding Test",
CreditsRequired = 300
},
},
Students = new Collection<Student>
{
new Student
{
FirstName = "Harry",
LastName = "Potter",
Gender = Gender.Male,
Birthdate = new DateTime(1980, 7, 31),
Address = new Address
{
AddressLine1 = "The Cupboard under the Stairs",
AddressLine2 = "4, Privet Drive",
City = "Little Whinging",
State = "Surrey",
Country = "England"
}
}
},
Professors = new Collection<Professor>
{
new Professor
{
FirstName = "Remus",
LastName = "Lupin",
Gender = Gender.Male,
Birthdate = new DateTime(1960, 3, 10),
Address = new Address
{
AddressLine1 = "The Shrieking Shack",
City = "Hogsmeade",
Country = "Scotland"
}
}
}
};
Console.ReadLine();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace Module1
{
class Program
{
/// <summary>
/// Facebook allow 71 gender options
/// </summary>
enum Gender
{
Male,
Female,
Other
}
enum SchoolStatus
{
Student,
Professor,
Other
}
enum DegreeType
{
Bachelor,
Master,
PhD,
Other
}
/// <summary>
/// AddressLine3 is required for some countries like France
/// </summary>
class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
abstract class APerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Birthdate { get; set; }
public Address Address { get; set; }
public Gender Gender { get; set; }
public abstract SchoolStatus SchoolStatus { get; }
}
class Student : APerson
{
public override SchoolStatus SchoolStatus { get { return SchoolStatus.Student; }}
}
class Professor : APerson
{
public override SchoolStatus SchoolStatus { get { return SchoolStatus.Professor; }}
}
// TODO : Idea for a degreeType notation ? I dont want to keep hungarian
interface IDegree
{
string Name { get; set; }
//string DegreeType Dt { get; set; }
}
class University
{
IEnumerable<Student> Students { get; set; }
IEnumerable<Professor> Professors { get; set; }
private IEnumerable<IDegree> Degrees { get; set; }
}
static void Main(string[] args)
{
}
}
}
| mit | C# |
dc9a53df6ffd4648425bf09cadced0a999c6dba8 | Update LinqToDBSection.cs | MaceWindu/linq2db,ronnyek/linq2db,jogibear9988/linq2db,AK107/linq2db,LinqToDB4iSeries/linq2db,enginekit/linq2db,lvaleriu/linq2db,genusP/linq2db,sdanyliv/linq2db,jogibear9988/linq2db,linq2db/linq2db,LinqToDB4iSeries/linq2db,genusP/linq2db,barsgroup/linq2db,MaceWindu/linq2db,rechkalov/linq2db,lvaleriu/linq2db,barsgroup/bars2db,AK107/linq2db,giuliohome/linq2db,sdanyliv/linq2db,inickvel/linq2db,linq2db/linq2db | Source/Configuration/LinqToDBSection.cs | Source/Configuration/LinqToDBSection.cs | using System;
using System.Configuration;
using System.Security;
namespace LinqToDB.Configuration
{
/// <summary>
/// Implementation of custom configuration section.
/// </summary>
public class LinqToDBSection : ConfigurationSection
{
static readonly ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();
static readonly ConfigurationProperty _propDataProviders = new ConfigurationProperty("dataProviders", typeof(DataProviderElementCollection), new DataProviderElementCollection(), ConfigurationPropertyOptions.None);
static readonly ConfigurationProperty _propDefaultConfiguration = new ConfigurationProperty("defaultConfiguration", typeof(string), null, ConfigurationPropertyOptions.None);
static readonly ConfigurationProperty _propDefaultDataProvider = new ConfigurationProperty("defaultDataProvider", typeof(string), null, ConfigurationPropertyOptions.None);
static LinqToDBSection()
{
_properties.Add(_propDataProviders);
_properties.Add(_propDefaultConfiguration);
_properties.Add(_propDefaultDataProvider);
}
private static LinqToDBSection _instance;
public static LinqToDBSection Instance
{
get
{
if (_instance == null)
{
try
{
_instance = (LinqToDBSection)ConfigurationManager.GetSection("linq2db");
}
catch (SecurityException)
{
return null;
}
}
return _instance;
}
}
protected override ConfigurationPropertyCollection Properties
{
get { return _properties; }
}
public DataProviderElementCollection DataProviders
{
get { return (DataProviderElementCollection) base[_propDataProviders]; }
}
public string DefaultConfiguration { get { return (string)base[_propDefaultConfiguration]; } }
public string DefaultDataProvider { get { return (string)base[_propDefaultDataProvider]; } }
}
}
| using System;
using System.Configuration;
using System.Security;
namespace LinqToDB.Configuration
{
/// <summary>
/// Implementation of custom configuration section.
/// </summary>
internal class LinqToDBSection : ConfigurationSection
{
static readonly ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();
static readonly ConfigurationProperty _propDataProviders = new ConfigurationProperty("dataProviders", typeof(DataProviderElementCollection), new DataProviderElementCollection(), ConfigurationPropertyOptions.None);
static readonly ConfigurationProperty _propDefaultConfiguration = new ConfigurationProperty("defaultConfiguration", typeof(string), null, ConfigurationPropertyOptions.None);
static readonly ConfigurationProperty _propDefaultDataProvider = new ConfigurationProperty("defaultDataProvider", typeof(string), null, ConfigurationPropertyOptions.None);
static LinqToDBSection()
{
_properties.Add(_propDataProviders);
_properties.Add(_propDefaultConfiguration);
_properties.Add(_propDefaultDataProvider);
}
private static LinqToDBSection _instance;
public static LinqToDBSection Instance
{
get
{
if (_instance == null)
{
try
{
_instance = (LinqToDBSection)ConfigurationManager.GetSection("linq2db");
}
catch (SecurityException)
{
return null;
}
}
return _instance;
}
}
protected override ConfigurationPropertyCollection Properties
{
get { return _properties; }
}
public DataProviderElementCollection DataProviders
{
get { return (DataProviderElementCollection) base[_propDataProviders]; }
}
public string DefaultConfiguration { get { return (string)base[_propDefaultConfiguration]; } }
public string DefaultDataProvider { get { return (string)base[_propDefaultDataProvider]; } }
}
}
| mit | C# |
a933b3a794e26c631f6d99dfd4f08317a3ac53bb | Add expected network | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Helpers/AddressStringParser.cs | WalletWasabi/Helpers/AddressStringParser.cs | using NBitcoin;
using NBitcoin.Payment;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace WalletWasabi.Helpers
{
public static class AddressStringParser
{
public static bool TryParseBitcoinAddress(string text, Network expectedNetwork, out BitcoinUrlBuilder url)
{
url = null;
if (text is null || expectedNetwork is null)
{
return false;
}
text = text.Trim();
if (text.Length > 100 || text.Length < 20)
{
return false;
}
try
{
var bitcoinAddress = BitcoinAddress.Create(text, expectedNetwork);
url = new BitcoinUrlBuilder($"bitcoin:{bitcoinAddress}", expectedNetwork);
return true;
}
catch (FormatException)
{
return false;
}
}
public static bool TryParseBitcoinUrl(string text, Network expectedNetwork, out BitcoinUrlBuilder url)
{
url = null;
if (text is null || expectedNetwork is null)
{
return false;
}
text = text.Trim();
if (text.Length > 1000 || text.Length < 20)
{
return false;
}
try
{
if (!text.StartsWith("bitcoin:", true, CultureInfo.InvariantCulture))
{
return false;
}
var bitcoinUrl = new BitcoinUrlBuilder(text, expectedNetwork);
if (bitcoinUrl?.Address.Network == expectedNetwork)
{
url = bitcoinUrl;
return true;
}
return false;
}
catch (FormatException)
{
return false;
}
}
public static bool TryParse(string text, Network expectedNetwork, out BitcoinUrlBuilder result)
{
result = null;
if (string.IsNullOrWhiteSpace(text) || text.Length > 1000)
{
return false;
}
if (TryParseBitcoinAddress(text, expectedNetwork, out BitcoinUrlBuilder addressResult))
{
result = addressResult;
return true;
}
else
{
if (TryParseBitcoinUrl(text, expectedNetwork, out BitcoinUrlBuilder urlResult))
{
result = urlResult;
return true;
}
}
return false;
}
}
}
| using NBitcoin;
using NBitcoin.Payment;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace WalletWasabi.Helpers
{
public static class AddressStringParser
{
public static bool TryParseBitcoinAddress(string text, Network expectedNetwork, out BitcoinUrlBuilder url)
{
url = null;
if (text is null || expectedNetwork is null)
{
return false;
}
text = text.Trim();
if (text.Length > 100 || text.Length < 20)
{
return false;
}
try
{
var bitcoinAddress = BitcoinAddress.Create(text, expectedNetwork);
url = new BitcoinUrlBuilder($"bitcoin:{bitcoinAddress}");
return true;
}
catch (FormatException)
{
return false;
}
}
public static bool TryParseBitcoinUrl(string text, Network expectedNetwork, out BitcoinUrlBuilder url)
{
url = null;
if (text is null || expectedNetwork is null)
{
return false;
}
text = text.Trim();
if (text.Length > 1000 || text.Length < 20)
{
return false;
}
try
{
if (!text.StartsWith("bitcoin:", true, CultureInfo.InvariantCulture))
{
return false;
}
var bitcoinUrl = new BitcoinUrlBuilder(text);
if (bitcoinUrl?.Address.Network == expectedNetwork)
{
url = bitcoinUrl;
return true;
}
return false;
}
catch (FormatException)
{
return false;
}
}
public static bool TryParse(string text, Network expectedNetwork, out BitcoinUrlBuilder result)
{
result = null;
if (string.IsNullOrWhiteSpace(text) || text.Length > 1000)
{
return false;
}
if (TryParseBitcoinAddress(text, expectedNetwork, out BitcoinUrlBuilder addressResult))
{
result = addressResult;
return true;
}
else
{
if (TryParseBitcoinUrl(text, expectedNetwork, out BitcoinUrlBuilder urlResult))
{
result = urlResult;
return true;
}
}
return false;
}
}
}
| mit | C# |
5c2628db64769abd78ff135bd2d9140a5beeefcb | Update Main to print the graph | ilovepi/Compiler,ilovepi/Compiler | compiler/Program/Program.cs | compiler/Program/Program.cs | using System;
using compiler.frontend;
namespace Program
{
class Program
{
//TODO: adjust main to use the parser when it is complete
static void Main(string[] args)
{
// using (Lexer l = new Lexer(@"../../testdata/big.txt"))
// {
// Token t;
// do
// {
// t = l.GetNextToken();
// Console.WriteLine(TokenHelper.PrintToken(t));
//
// } while (t != Token.EOF);
//
// // necessary when testing on windows with visual studio
// //Console.WriteLine("Press 'enter' to exit ....");
// //Console.ReadLine();
// }
using (Parser p = new Parser(@"../../testdata/test002.txt"))
{
p.Parse();
p.FlowCfg.GenerateDOTOutput();
using (System.IO.StreamWriter file = new System.IO.StreamWriter("graph.txt"))
{
file.WriteLine( p.FlowCfg.DOTOutput);
}
}
}
}
}
| using System;
using compiler.frontend;
namespace Program
{
class Program
{
//TODO: adjust main to use the parser when it is complete
static void Main(string[] args)
{
using (Lexer l = new Lexer(@"../../testdata/big.txt"))
{
Token t;
do
{
t = l.GetNextToken();
Console.WriteLine(TokenHelper.PrintToken(t));
} while (t != Token.EOF);
// necessary when testing on windows with visual studio
//Console.WriteLine("Press 'enter' to exit ....");
//Console.ReadLine();
}
}
}
}
| mit | C# |
67df14f7fc9af91118443a4a0eeeb7d7387fe4e7 | Fix initialization | lamalex/Banshee,mono-soc-2011/banshee,GNOME/banshee,GNOME/banshee,Carbenium/banshee,ixfalia/banshee,allquixotic/banshee-gst-sharp-work,stsundermann/banshee,allquixotic/banshee-gst-sharp-work,GNOME/banshee,arfbtwn/banshee,mono-soc-2011/banshee,directhex/banshee-hacks,Dynalon/banshee-osx,stsundermann/banshee,ixfalia/banshee,lamalex/Banshee,ixfalia/banshee,Dynalon/banshee-osx,allquixotic/banshee-gst-sharp-work,dufoli/banshee,arfbtwn/banshee,lamalex/Banshee,Carbenium/banshee,stsundermann/banshee,dufoli/banshee,GNOME/banshee,ixfalia/banshee,Dynalon/banshee-osx,stsundermann/banshee,arfbtwn/banshee,arfbtwn/banshee,GNOME/banshee,GNOME/banshee,dufoli/banshee,Carbenium/banshee,dufoli/banshee,lamalex/Banshee,petejohanson/banshee,mono-soc-2011/banshee,petejohanson/banshee,arfbtwn/banshee,mono-soc-2011/banshee,allquixotic/banshee-gst-sharp-work,babycaseny/banshee,stsundermann/banshee,petejohanson/banshee,lamalex/Banshee,dufoli/banshee,stsundermann/banshee,directhex/banshee-hacks,mono-soc-2011/banshee,babycaseny/banshee,petejohanson/banshee,Dynalon/banshee-osx,GNOME/banshee,babycaseny/banshee,mono-soc-2011/banshee,ixfalia/banshee,Dynalon/banshee-osx,Dynalon/banshee-osx,dufoli/banshee,arfbtwn/banshee,dufoli/banshee,ixfalia/banshee,babycaseny/banshee,petejohanson/banshee,Dynalon/banshee-osx,directhex/banshee-hacks,allquixotic/banshee-gst-sharp-work,Carbenium/banshee,GNOME/banshee,babycaseny/banshee,lamalex/Banshee,directhex/banshee-hacks,Dynalon/banshee-osx,Carbenium/banshee,Carbenium/banshee,babycaseny/banshee,stsundermann/banshee,babycaseny/banshee,mono-soc-2011/banshee,arfbtwn/banshee,directhex/banshee-hacks,babycaseny/banshee,directhex/banshee-hacks,petejohanson/banshee,ixfalia/banshee,arfbtwn/banshee,stsundermann/banshee,ixfalia/banshee,dufoli/banshee,allquixotic/banshee-gst-sharp-work | src/Core/Banshee.ThickClient/Banshee.Gui.Widgets/ConnectedVolumeButton.cs | src/Core/Banshee.ThickClient/Banshee.Gui.Widgets/ConnectedVolumeButton.cs | //
// ConnectedVolumeButton.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, 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;
using Banshee.MediaEngine;
using Banshee.ServiceStack;
namespace Banshee.Gui.Widgets
{
public class ConnectedVolumeButton : Bacon.VolumeButton
{
private bool emit_lock = false;
public ConnectedVolumeButton () : base()
{
var player = ServiceManager.PlayerEngine;
if (player.ActiveEngine != null && player.ActiveEngine.IsInitialized) {
SetVolume ();
} else {
Sensitive = false;
player.EngineAfterInitialize += (e) => {
Hyena.ThreadAssist.ProxyToMain (delegate {
SetVolume ();
Sensitive = true;
});
};
}
player.ConnectEvent (OnPlayerEvent, PlayerEvent.Volume);
}
public ConnectedVolumeButton (bool classic) : this ()
{
Classic = classic;
}
private void OnPlayerEvent (PlayerEventArgs args)
{
SetVolume ();
}
private void SetVolume ()
{
emit_lock = true;
Volume = ServiceManager.PlayerEngine.Volume;
emit_lock = false;
}
protected override void OnVolumeChanged ()
{
if (emit_lock) {
return;
}
ServiceManager.PlayerEngine.Volume = (ushort)Volume;
base.OnVolumeChanged ();
}
}
}
| //
// ConnectedVolumeButton.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007 Novell, 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;
using Banshee.MediaEngine;
using Banshee.ServiceStack;
namespace Banshee.Gui.Widgets
{
public class ConnectedVolumeButton : Bacon.VolumeButton
{
private bool emit_lock = false;
public ConnectedVolumeButton () : base()
{
emit_lock = true;
Volume = ServiceManager.PlayerEngine.Volume;
emit_lock = false;
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.Volume);
}
public ConnectedVolumeButton (bool classic) : this ()
{
Classic = classic;
}
private void OnPlayerEvent (PlayerEventArgs args)
{
emit_lock = true;
Volume = ServiceManager.PlayerEngine.Volume;
emit_lock = false;
}
protected override void OnVolumeChanged ()
{
if (emit_lock) {
return;
}
ServiceManager.PlayerEngine.Volume = (ushort)Volume;
base.OnVolumeChanged ();
}
}
}
| mit | C# |
ba23ad4883182fcb7022da739f4f15a91d113c8f | Sort the attributes before I compare them so they are not order dependant from the reflection. (Updated by TFS to TFS Connector, server: http://1x:8080/, id 6222. ) | ucdavis/CRP,ucdavis/CRP,ucdavis/CRP | CRP.Tests/Core/Helpers/AttributeAndFieldValidation.cs | CRP.Tests/Core/Helpers/AttributeAndFieldValidation.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CRP.Tests.Core.Helpers
{
public static class AttributeAndFieldValidation
{
/// <summary>
/// Validates the fields and attributes.
/// </summary>
/// <param name="expectedFields">The expected fields.</param>
/// <param name="entityType">Type of the entity.</param>
public static void ValidateFieldsAndAttributes(List<NameAndType> expectedFields, Type entityType)
{
#region Act
// get all public static properties of MyClass type
var propertyInfos = entityType.GetProperties();
// sort properties by name
Array.Sort(propertyInfos, (propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name));
#endregion Act
#region Assert
Assert.AreEqual(propertyInfos.Count(), expectedFields.Count);
for (int i = 0; i < propertyInfos.Count(); i++)
{
Assert.AreEqual(propertyInfos[i].Name, expectedFields[i].Name);
Assert.AreEqual(propertyInfos[i].PropertyType.ToString(), expectedFields[i].Property);
var foundAttributes = CustomAttributeData.GetCustomAttributes(propertyInfos[i])
.AsQueryable().OrderBy(a => a.NamedArguments.ToString()).ToList();
Assert.AreEqual(expectedFields[i].Attributes.Count, foundAttributes.Count());
if (foundAttributes.Count() > 0)
{
//Array.Sort(foundAttributes, (attribute1, attribute2)=> attribute1.NamedArguments.ToString().CompareTo(attribute2.NamedArguments.ToString()));
for (int j = 0; j < foundAttributes.Count(); j++)
{
Assert.AreEqual(expectedFields[i].Attributes[j], foundAttributes[j].ToString(), "For Field: " + propertyInfos[i].Name);
}
}
}
#endregion Assert
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CRP.Tests.Core.Helpers
{
public static class AttributeAndFieldValidation
{
/// <summary>
/// Validates the fields and attributes.
/// </summary>
/// <param name="expectedFields">The expected fields.</param>
/// <param name="entityType">Type of the entity.</param>
public static void ValidateFieldsAndAttributes(List<NameAndType> expectedFields, Type entityType)
{
#region Act
// get all public static properties of MyClass type
var propertyInfos = entityType.GetProperties();
// sort properties by name
Array.Sort(propertyInfos, (propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name));
#endregion Act
#region Assert
Assert.AreEqual(propertyInfos.Count(), expectedFields.Count);
for (int i = 0; i < propertyInfos.Count(); i++)
{
Assert.AreEqual(propertyInfos[i].Name, expectedFields[i].Name);
Assert.AreEqual(propertyInfos[i].PropertyType.ToString(), expectedFields[i].Property);
var foundAttributes = CustomAttributeData.GetCustomAttributes(propertyInfos[i]);
Assert.AreEqual(expectedFields[i].Attributes.Count, foundAttributes.Count);
if (foundAttributes.Count > 0)
{
for (int j = 0; j < foundAttributes.Count; j++)
{
Assert.AreEqual(expectedFields[i].Attributes[j], foundAttributes[j].ToString(), "For Field: " + propertyInfos[i].Name);
}
}
}
#endregion Assert
}
}
}
| mit | C# |
138e65d7a49c0d9df0c5648148bc8e490b40542f | Add missing blank line | peppy/osu,NeoAdonis/osu,NeoAdonis/osu,EVAST9919/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu,peppy/osu,johnneijzen/osu,smoogipooo/osu,peppy/osu-new,smoogipoo/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game/Utils/HumanizerUtils.cs | osu.Game/Utils/HumanizerUtils.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.Globalization;
using Humanizer;
namespace osu.Game.Utils
{
public static class HumanizerUtils
{
/// <summary>
/// Turns the current or provided date into a human readable sentence
/// </summary>
/// <param name="input">The date to be humanized</param>
/// <returns>distance of time in words</returns>
public static string Humanize(DateTimeOffset input)
{
// this works around https://github.com/xamarin/xamarin-android/issues/2012 and https://github.com/Humanizr/Humanizer/issues/690#issuecomment-368536282
try
{
return input.Humanize();
}
catch (ArgumentException)
{
return input.Humanize(culture: new CultureInfo("en-US"));
}
}
/// <summary>
/// Turns the current or provided big number into a readable string.
/// </summary>
/// <param name="input">The number to be humanized.</param>
/// <returns>Simplified number with a suffix.</returns>
public static string ToReadableString(long input)
{
const int k = 1000;
if (input < k)
return input.ToString();
int i = (int)Math.Floor(Math.Round(Math.Log(input, k)));
return $"{input / Math.Pow(k, i):F} {suffixes[i]}";
}
private static readonly string[] suffixes =
{
"",
"k",
"million",
"billion",
"trillion",
"quadrillion",
"quintillion",
};
}
}
| // 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.Globalization;
using Humanizer;
namespace osu.Game.Utils
{
public static class HumanizerUtils
{
/// <summary>
/// Turns the current or provided date into a human readable sentence
/// </summary>
/// <param name="input">The date to be humanized</param>
/// <returns>distance of time in words</returns>
public static string Humanize(DateTimeOffset input)
{
// this works around https://github.com/xamarin/xamarin-android/issues/2012 and https://github.com/Humanizr/Humanizer/issues/690#issuecomment-368536282
try
{
return input.Humanize();
}
catch (ArgumentException)
{
return input.Humanize(culture: new CultureInfo("en-US"));
}
}
/// <summary>
/// Turns the current or provided big number into a readable string.
/// </summary>
/// <param name="input">The number to be humanized.</param>
/// <returns>Simplified number with a suffix.</returns>
public static string ToReadableString(long input)
{
const int k = 1000;
if (input < k)
return input.ToString();
int i = (int)Math.Floor(Math.Round(Math.Log(input, k)));
return $"{input / Math.Pow(k, i):F} {suffixes[i]}";
}
private static readonly string[] suffixes =
{
"",
"k",
"million",
"billion",
"trillion",
"quadrillion",
"quintillion",
};
}
}
| mit | C# |
815b7a78de526af8edd188fc6f314929cf4053f3 | Update Extensions to add new AddSafe function for Dictionaries | BenVlodgi/VMFParser | VMFParser/Extensions.cs | VMFParser/Extensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace VMFParser
{
public static class Extensions
{
/// <summary>Returns a new array from given index with the specified length. </summary>
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
/// <summary> Returns first <see cref="VMFParser.VBlock"/> in list. </summary>
public static VBlock VBlock(this IEnumerable<IVNode> body)
{
return body.WhereClass<VBlock>().FirstOrDefault();
}
/// <summary> Returns first <see cref="VMFParser.VBlock"/> in list that matches the predicate. </summary>
public static VBlock VBlock(this IEnumerable<IVNode> body, Func<VBlock, bool> predicate)
{
return body.WhereClass<VBlock>().FirstOrDefault(predicate);
}
/// <summary> Returns first <see cref="VMFParser.VProperty"/> in list. </summary>
public static VProperty VProperty(this IEnumerable<IVNode> body)
{
return body.WhereClass<VProperty>().FirstOrDefault();
}
/// <summary> Returns first <see cref="VMFParser.VProperty"/> in list that matches the predicate. </summary>
public static VProperty VProperty(this IEnumerable<IVNode> body, Func<VProperty, bool> predicate)
{
return body.WhereClass<VProperty>().FirstOrDefault(predicate);
}
/// <summary> Returns given list, with values cast to given type, nulls are removed. </summary>
/// <typeparam name="AsType">Type all values will be cast to. </typeparam>
public static IEnumerable<AsType> WhereClass<AsType>(this IEnumerable<object> data) where AsType : class
{
return data.Where(d => d as AsType != null).Cast<AsType>();
}
/// <summary> Adds key value to dictionary unless already exists. </summary>
/// <param name="update">When true, value will be updated. </param>
/// <returns> True if given value was set. </returns>
public static bool AddSafe<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value, bool update = false)
{
if(dict.ContainsKey(key))
{
if (update)
{
dict[key] = value;
return true;
}
else return false;
}
else
{
dict.Add(key, value);
return true;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace VMFParser
{
public static class Extensions
{
/// <summary>Returns a new array from given index with the specified length. </summary>
public static T[] SubArray<T>(this T[] data, int index, int length)
{
T[] result = new T[length];
Array.Copy(data, index, result, 0, length);
return result;
}
/// <summary> Returns first <see cref="VMFParser.VBlock"/> in list. </summary>
public static VBlock VBlock(this IEnumerable<IVNode> body)
{
return body.WhereClass<VBlock>().FirstOrDefault();
}
/// <summary> Returns first <see cref="VMFParser.VBlock"/> in list that matches the predicate. </summary>
public static VBlock VBlock(this IEnumerable<IVNode> body, Func<VBlock,bool> predicate)
{
return body.WhereClass<VBlock>().FirstOrDefault(predicate);
}
/// <summary> Returns first <see cref="VMFParser.VProperty"/> in list. </summary>
public static VProperty VProperty(this IEnumerable<IVNode> body)
{
return body.WhereClass<VProperty>().FirstOrDefault();
}
/// <summary> Returns first <see cref="VMFParser.VProperty"/> in list that matches the predicate. </summary>
public static VProperty VProperty(this IEnumerable<IVNode> body, Func<VProperty, bool> predicate)
{
return body.WhereClass<VProperty>().FirstOrDefault(predicate);
}
/// <summary> Returns given list, with values cast to given type, nulls are removed. </summary>
/// <typeparam name="AsType">Type all values will be cast to. </typeparam>
public static IEnumerable<AsType> WhereClass<AsType>(this IEnumerable<object> data) where AsType : class
{
return data.Where(d => d as AsType != null).Cast<AsType>();
}
}
}
| mit | C# |
002e1ecf27d67024e311412bdb56f1316725739c | remove unused method | weltkante/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,gafter/roslyn,wvdd007/roslyn,KevinRansom/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,AmadeusW/roslyn,davkean/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,genlu/roslyn,dotnet/roslyn,jmarolf/roslyn,wvdd007/roslyn,jmarolf/roslyn,davkean/roslyn,weltkante/roslyn,reaction1989/roslyn,gafter/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,stephentoub/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,mavasani/roslyn,physhi/roslyn,dotnet/roslyn,aelij/roslyn,davkean/roslyn,weltkante/roslyn,aelij/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,physhi/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,AmadeusW/roslyn,mavasani/roslyn,KevinRansom/roslyn,aelij/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,diryboy/roslyn,jmarolf/roslyn,eriawan/roslyn,AmadeusW/roslyn,genlu/roslyn,tmat/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,tmat/roslyn,stephentoub/roslyn,stephentoub/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,gafter/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,physhi/roslyn,genlu/roslyn,tmat/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn | src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/ListPool.cs | src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/ListPool.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.Collections.Generic;
namespace Microsoft.CodeAnalysis.Formatting
{
internal static class ListPool<T>
{
public static List<T> Allocate()
{
return SharedPools.Default<List<T>>().AllocateAndClear();
}
public static void Free(List<T> list)
{
SharedPools.Default<List<T>>().ClearAndFree(list);
}
}
}
| // 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.Collections.Generic;
namespace Microsoft.CodeAnalysis.Formatting
{
internal static class ListPool<T>
{
public static List<T> Allocate()
{
return SharedPools.Default<List<T>>().AllocateAndClear();
}
public static void Free(List<T> list)
{
SharedPools.Default<List<T>>().ClearAndFree(list);
}
public static List<T> ReturnAndFree(List<T> list)
{
SharedPools.Default<List<T>>().ForgetTrackedObject(list);
return list;
}
}
}
| mit | C# |
ec9da167a431596e921cbe11b3eee0f155a4b854 | disable parallel tests | IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework,xyting/IdentityServer4.EntityFramework,xyting/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework | test/IdentityServer4.EntityFramework.IntegrationTests/Properties/AssemblyInfo.cs | test/IdentityServer4.EntityFramework.IntegrationTests/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IdentityServer4.EntityFramework.IntegrationTests")]
[assembly: AssemblyTrademark("")]
// 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("73cce3c6-5431-4b76-acbe-ef4ee76d6b81")]
[assembly: CollectionBehavior(DisableTestParallelization = true)] | 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("IdentityServer4.EntityFramework.IntegrationTests")]
[assembly: AssemblyTrademark("")]
// 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("73cce3c6-5431-4b76-acbe-ef4ee76d6b81")]
| apache-2.0 | C# |
7d9fa94e662b8d6c9ad09e9c9a27f025c8d4abaf | cut test user name | jarzynam/rescuer,jarzynam/continuous | src/Compatibility.Tests/Continuous.Test.WindowsService/Continuous.Test.WindowsService/Tests/ChangeAccountTests.cs | src/Compatibility.Tests/Continuous.Test.WindowsService/Continuous.Test.WindowsService/Tests/ChangeAccountTests.cs | using System;
using Continuous.Management;
using Continuous.Test.WindowsService.Logic;
using Continuous.Test.WindowsService.Logic.Installer;
using Continuous.Test.WindowsService.TestHelpers;
using Continuous.WindowsService;
using Continuous.WindowsService.Shell;
using FluentAssertions;
using NUnit.Framework;
namespace Continuous.Test.WindowsService.Tests
{
[TestFixture]
public class ChangeAccountTests
{
[SetUp]
public void SetUp()
{
_shell = (new ContinuousManagementFactory()).WindowsServiceShell();
_serviceInstaller = new ServiceInstaller();
_userInstaller = new UserInstaller();
_nameGenerator = new NameGenerator();
}
[TearDown]
public void TearDown()
{
_serviceInstaller.Dispose();
_userInstaller.Dispose();
}
private ServiceInstaller _serviceInstaller;
private NameGenerator _nameGenerator;
private UserInstaller _userInstaller;
private IWindowsServiceShell _shell;
private const string Prefix = "caTest";
[Test]
public void ChangeAccount_Should_ChangeAccount()
{
// arrange
var serviceName = _nameGenerator.GetRandomName(Prefix);
var userName = serviceName;
var userPassword = "test";
_serviceInstaller.InstallService(serviceName);
_userInstaller.Install(userName, userPassword);
// act
_shell.ChangeAccount(serviceName, userName, userPassword);
// assert
var account = ServiceHelper.GetAccount(serviceName);
account.Should().Be(".\\" + userName);
}
[Test]
public void ChangeAccount_Should_Throw_When_User_IsInvalid()
{
// arrange
var serviceName = _nameGenerator.GetRandomName(Prefix);
_serviceInstaller.InstallService(serviceName);
// act
Action act = () => _shell.ChangeAccount(serviceName, "fakeUser", "falePassword");
// assert
act.ShouldThrow<InvalidOperationException>();
}
}
} | using System;
using Continuous.Management;
using Continuous.Test.WindowsService.Logic;
using Continuous.Test.WindowsService.Logic.Installer;
using Continuous.Test.WindowsService.TestHelpers;
using Continuous.WindowsService;
using Continuous.WindowsService.Shell;
using FluentAssertions;
using NUnit.Framework;
namespace Continuous.Test.WindowsService.Tests
{
[TestFixture]
public class ChangeAccountTests
{
[SetUp]
public void SetUp()
{
_shell = (new ContinuousManagementFactory()).WindowsServiceShell();
_serviceInstaller = new ServiceInstaller();
_userInstaller = new UserInstaller();
_nameGenerator = new NameGenerator();
}
[TearDown]
public void TearDown()
{
_serviceInstaller.Dispose();
_userInstaller.Dispose();
}
private ServiceInstaller _serviceInstaller;
private NameGenerator _nameGenerator;
private UserInstaller _userInstaller;
private IWindowsServiceShell _shell;
private const string Prefix = "caTestService";
[Test]
public void ChangeAccount_Should_ChangeAccount()
{
// arrange
var serviceName = _nameGenerator.GetRandomName(Prefix);
var userName = serviceName + "User";
var userPassword = "test";
_serviceInstaller.InstallService(serviceName);
_userInstaller.Install(userName, userPassword);
// act
_shell.ChangeAccount(serviceName, userName, userPassword);
// assert
var account = ServiceHelper.GetAccount(serviceName);
account.Should().Be(".\\" + userName);
}
[Test]
public void ChangeAccount_Should_Throw_When_User_IsInvalid()
{
// arrange
var serviceName = _nameGenerator.GetRandomName(Prefix);
_serviceInstaller.InstallService(serviceName);
// act
Action act = () => _shell.ChangeAccount(serviceName, "fakeUser", "falePassword");
// assert
act.ShouldThrow<InvalidOperationException>();
}
}
} | mit | C# |
20fe0e9153e6a38a6cd8d7af8a45dfe9813c71c9 | Update DupItem.cs | unruledboy/SharpDups | Model/DupItem.cs | Model/DupItem.cs | using System.Collections.Generic;
namespace Xnlab.SharpDups.Model
{
public class DupItem : FileItem
{
public byte[] Tags { get; set; }
public string QuickHash { get; set; }
public string FullHash { get; set; }
public List<string> HashSections { get; set; }
public bool IsDifferent { get; set; }
}
}
| using System.Collections.Generic;
namespace Xnlab.SharpDups.Model
{
public class DupItem : FileItem
{
public byte[] Tags { get; set; }
public string QuickHash { get; set; }
public string FullHash { get; set; }
public List<string> HashSections { get; set; }
}
}
| apache-2.0 | C# |
a1ff4d32c20eb75a1f94548f40e210c55238b788 | Add HttpResponseMessage.EnsureSuccess that include response content in the exception. | yufeih/Common | src/HttpHelper.cs | src/HttpHelper.cs | namespace System.Net.Http
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
static class HttpHelper
{
public static string ValidatePath(string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (path == "" || path == "/") return "";
if (path[0] != '/' || path[path.Length - 1] == '/') throw new ArgumentException(nameof(path));
return path;
}
public static DelegatingHandler Combine(this IEnumerable<DelegatingHandler> handlers)
{
var result = handlers.FirstOrDefault();
var last = result;
foreach (var handler in handlers.Skip(1))
{
last.InnerHandler = handler;
last = handler;
}
return result;
}
[Conditional("DEBUG")]
public static void DumpErrors(HttpResponseMessage message)
{
if (!message.IsSuccessStatusCode && message.StatusCode != HttpStatusCode.Unauthorized)
{
var dump = (Action)(async () =>
{
var error = await message.Content.ReadAsStringAsync();
Debug.WriteLine(error);
});
dump();
}
}
public static HttpResponseMessage EnsureSuccess(this HttpResponseMessage message)
{
if (message.IsSuccessStatusCode) return message;
throw new HttpRequestException($"Http {message.StatusCode}: {message.Content.ReadAsStringAsync().Result}");
}
public static int TryGetContentLength(HttpResponseMessage response)
{
int result;
IEnumerable<string> value;
if (response.Headers.TryGetValues("Content-Length", out value) &&
value.Any() && int.TryParse(value.First(), out result))
{
return result;
}
return 0;
}
}
}
| namespace System.Net.Http
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
static class HttpHelper
{
public static string ValidatePath(string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
if (path == "" || path == "/") return "";
if (path[0] != '/' || path[path.Length - 1] == '/') throw new ArgumentException(nameof(path));
return path;
}
public static DelegatingHandler Combine(this IEnumerable<DelegatingHandler> handlers)
{
var result = handlers.FirstOrDefault();
var last = result;
foreach (var handler in handlers.Skip(1))
{
last.InnerHandler = handler;
last = handler;
}
return result;
}
[Conditional("DEBUG")]
public static void DumpErrors(HttpResponseMessage message)
{
if (!message.IsSuccessStatusCode && message.StatusCode != HttpStatusCode.Unauthorized)
{
var dump = (Action)(async () =>
{
var error = await message.Content.ReadAsStringAsync();
Debug.WriteLine(error);
});
dump();
}
}
public static int TryGetContentLength(HttpResponseMessage response)
{
int result;
IEnumerable<string> value;
if (response.Headers.TryGetValues("Content-Length", out value) &&
value.Any() && int.TryParse(value.First(), out result))
{
return result;
}
return 0;
}
}
}
| mit | C# |
528db7facd8cea49bf4f0bdcdb7487ad0686100d | Increase battery drain rate | sposterkil/eecs290fps,sposterkil/eecs290fps | Assets/PlayerAssets/PlayerManager.cs | Assets/PlayerAssets/PlayerManager.cs | using UnityEngine;
using System.Collections;
public class PlayerManager : MonoBehaviour {
public enum Weapons {Pistol, Submachine, Sword};
public static Weapons wep;
public int current;
public int health;
public float battery;
public static int ammo;
public Transform pistol;
public Transform submachine;
public Transform sword;
public Transform Flashlight;
public static bool enabled;
// Use this for initialization
public void Start () {
wep = Weapons.Pistol;
Flashlight.active = true;
pistol.active = true;
submachine.active = false;
sword.active = false;
current = 0;
health = 100;
battery = 100;
ammo = 60;
HUDManager.SetBattery ((int)battery);
HUDManager.SetHealth (health);
HUDManager.SetAmmo (ammo);
disable();
}
public void enable() {
enabled = true;
CharacterMotor.Enable();
}
public void disable() {
enabled = false;
CharacterMotor.Disable();
}
public void SetWeapon(Weapons w){
if (enabled) {
switch (w) {
case Weapons.Pistol:
pistol.active = true;
break;
case Weapons.Submachine:
submachine.active = true;
break;
case Weapons.Sword:
sword.active = true;
break;
default:
Debug.Log("Got bad weapon type: " + w);
break;
}
wep = w;
}
}
// Update is called once per frame
void Update () {
if (enabled) {
HUDManager.SetBattery ((int)battery);
HUDManager.SetHealth (health);
HUDManager.SetAmmo (ammo);
if (Input.GetAxis("Scroll") != 0) {
transform.GetChild(1).animation.Stop();
pistol.active = false;
submachine.active = false;
sword.active = false;
if (Input.GetAxis("Scroll") < -.01)
current += 2;
else if (Input.GetAxis("Scroll") > .01)
current += 1;
}
current %= 3;
switch (current) {
case 0:
wep = Weapons.Pistol;
pistol.active = true;
break;
case 1:
wep = Weapons.Submachine;
submachine.active = true;
break;
case 2:
wep = Weapons.Sword;
sword.active = true;
break;
}
if (Input.GetKeyDown ("f2")) {// kill player when f2 is pressed
this.health = 0;
}
if (this.health <= 0) { // player is dead
GameEventManager.TriggerGameOver ();
Application.LoadLevel (0);
}
if (battery > 0) {
battery -= .01f;
}
else{
Flashlight.active = false;
}
}
else {
transform.GetChild(1).animation.Stop();
disable();
}
}
}
| using UnityEngine;
using System.Collections;
public class PlayerManager : MonoBehaviour {
public enum Weapons {Pistol, Submachine, Sword};
public static Weapons wep;
public int current;
public int health;
public float battery;
public static int ammo;
public Transform pistol;
public Transform submachine;
public Transform sword;
public Transform Flashlight;
public static bool enabled;
// Use this for initialization
public void Start () {
wep = Weapons.Pistol;
Flashlight.active = true;
pistol.active = true;
submachine.active = false;
sword.active = false;
current = 0;
health = 100;
battery = 100;
ammo = 60;
HUDManager.SetBattery ((int)battery);
HUDManager.SetHealth (health);
HUDManager.SetAmmo (ammo);
disable();
}
public void enable() {
enabled = true;
CharacterMotor.Enable();
}
public void disable() {
enabled = false;
CharacterMotor.Disable();
}
public void SetWeapon(Weapons w){
if (enabled) {
switch (w) {
case Weapons.Pistol:
pistol.active = true;
break;
case Weapons.Submachine:
submachine.active = true;
break;
case Weapons.Sword:
sword.active = true;
break;
default:
Debug.Log("Got bad weapon type: " + w);
break;
}
wep = w;
}
}
// Update is called once per frame
void Update () {
if (enabled) {
HUDManager.SetBattery ((int)battery);
HUDManager.SetHealth (health);
HUDManager.SetAmmo (ammo);
if (Input.GetAxis("Scroll") != 0) {
transform.GetChild(1).animation.Stop();
pistol.active = false;
submachine.active = false;
sword.active = false;
if (Input.GetAxis("Scroll") < -.01)
current += 2;
else if (Input.GetAxis("Scroll") > .01)
current += 1;
}
current %= 3;
switch (current) {
case 0:
wep = Weapons.Pistol;
pistol.active = true;
break;
case 1:
wep = Weapons.Submachine;
submachine.active = true;
break;
case 2:
wep = Weapons.Sword;
sword.active = true;
break;
}
if (Input.GetKeyDown ("f2")) {// kill player when f2 is pressed
this.health = 0;
}
if (this.health <= 0) { // player is dead
GameEventManager.TriggerGameOver ();
Application.LoadLevel (0);
}
if (battery > 0) {
battery -= .001f;
}
else{
Flashlight.active = false;
}
}
else {
transform.GetChild(1).animation.Stop();
disable();
}
}
}
| mit | C# |
8b457315bf4ab36b18f7282c2609735a213e1760 | Add a footer navigation widget. | bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes,bigfont/orchard-cms-modules-and-themes | Orchard.Source.1.8.1/src/Orchard.Web/Modules/LccNetwork/Migrations/NavigationMigrations.cs | Orchard.Source.1.8.1/src/Orchard.Web/Modules/LccNetwork/Migrations/NavigationMigrations.cs | using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using Orchard.Environment.Extensions;
namespace LccNetwork.Migrations
{
[OrchardFeature("SectionNavigation")]
public class NavigationMigrations : DataMigrationImpl
{
public int Create()
{
return 1;
}
public int UpdateFrom1()
{
return 2;
}
public int UpdateFrom2()
{
ContentDefinitionManager.AlterTypeDefinition("SectionMenu",
cfg => cfg
.WithPart("CommonPart")
.WithPart("IdentityPart")
.WithPart("WidgetPart")
.WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI?
.WithSetting("Stereotype", "Widget")
);
return 4;
}
public int UpdateFrom4()
{
ContentDefinitionManager.AlterTypeDefinition("FooterMenu",
cfg => cfg
.WithPart("CommonPart")
.WithPart("IdentityPart")
.WithPart("WidgetPart")
.WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI?
.WithSetting("Stereotype", "Widget")
);
return 5;
}
}
} | using System;
using System.Collections.Generic;
using System.Data;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.Core.Contents.Extensions;
using Orchard.Data.Migration;
using Orchard.Environment.Extensions;
namespace LccNetwork.Migrations
{
[OrchardFeature("fea")]
public class NavigationMigrations : DataMigrationImpl
{
public int Create()
{
return 1;
}
public int UpdateFrom1()
{
return 2;
}
public int UpdateFrom2()
{
ContentDefinitionManager.AlterTypeDefinition("SectionMenu",
cfg => cfg
.WithPart("CommonPart")
.WithPart("IdentityPart")
.WithPart("WidgetPart")
.WithPart("MenuWidgetPart") // why cannot we add MenuWidgetPart through the UI?
.WithSetting("Stereotype", "Widget")
);
return 3;
}
}
} | bsd-3-clause | C# |
5c18bab11ec2600feb7cf83c913fc31e84168a9e | Update version number | eWAYPayment/eway-rapid-net | eWAY.Rapid.Tests/Properties/AssemblyInfo.cs | eWAY.Rapid.Tests/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("eWAY.Rapid.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("eWAY")]
[assembly: AssemblyProduct("eWAY.Rapid.Tests")]
[assembly: AssemblyCopyright("Copyright © Web Active 2015-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("209bf8fd-d4eb-4a01-a542-068886e7c749")]
// 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.6.3.0")]
[assembly: AssemblyFileVersion("1.6.3.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("eWAY.Rapid.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("eWAY")]
[assembly: AssemblyProduct("eWAY.Rapid.Tests")]
[assembly: AssemblyCopyright("Copyright © Web Active 2015-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("209bf8fd-d4eb-4a01-a542-068886e7c749")]
// 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.6.2.0")]
[assembly: AssemblyFileVersion("1.6.2.0")]
| mit | C# |
190819cd73f902355facb0a8b869bcb20fd67000 | Update IQueryRepository.cs | tiksn/TIKSN-Framework | TIKSN.Core/Data/IQueryRepository.cs | TIKSN.Core/Data/IQueryRepository.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data
{
public interface IQueryRepository<TEntity, TIdentity>
where TEntity : IEntity<TIdentity>
where TIdentity : IEquatable<TIdentity>
{
Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken);
Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken);
Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken);
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Data
{
public interface IQueryRepository<TEntity, TIdentity>
where TEntity : IEntity<TIdentity>
where TIdentity : IEquatable<TIdentity>
{
Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken);
Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken);
}
} | mit | C# |
423a2b24a41c6ce83b1fe26f73f0dd951a4a5a45 | hide login/password command line params | yar229/WebDavMailRuCloud | WDMRC.Console/CommandLineOptions.cs | WDMRC.Console/CommandLineOptions.cs | using System;
using CommandLine;
namespace YaR.WebDavMailRu
{
class CommandLineOptions
{
[Option('p', "port", Required = true, HelpText = "WebDAV server port")]
public int Port { get; set; }
[Obsolete]
[Option('l', "login", Required = false, HelpText = "Login to Mail.ru Cloud", Hidden = true)]
public string Login { get; set; }
[Obsolete]
[Option('s', "password", Required = false, HelpText = "Password to Mail.ru Cloud", Hidden = true)]
public string Password { get; set; }
[Option("maxthreads", Default = 5, HelpText = "Maximum concurrent connections to cloud.mail.ru")]
public int MaxThreadCount { get; set; }
[Option("user-agent", HelpText = "\"browser\" user-agent")]
public string UserAgent { get; set; }
}
}
| using CommandLine;
namespace YaR.WebDavMailRu
{
class CommandLineOptions
{
[Option('p', "port", Required = true, HelpText = "WebDAV server port")]
public int Port { get; set; }
//[Option('l', "login", Required = true, HelpText = "Login to Mail.ru Cloud")]
//public string Login { get; set; }
//[Option('s', "password", Required = true, HelpText = "Password to Mail.ru Cloud")]
//public string Password { get; set; }
[Option("maxthreads", Default = 5, HelpText = "Maximum concurrent connections to cloud.mail.ru")]
public int MaxThreadCount { get; set; }
[Option("user-agent", HelpText = "\"browser\" user-agent")]
public string UserAgent { get; set; }
}
}
| mit | C# |
94798d39b2ca07a3b7dcbd1cca1bc9c25dad4431 | Add comments to EmailDto. | harrison314/MapperPerformace | MapperPerformace/Testing/EmailDto.cs | MapperPerformace/Testing/EmailDto.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapperPerformace.Testing
{
/// <summary>
/// Dto class represents <see cref="MapperPerformace.Ef.EmailAddress"/>.
/// </summary>
public class EmailDto
{
public int EmailAddressID
{
get;
set;
}
public string EmailAddress
{
get;
set;
}
public DateTime ModifiedDate
{
get;
set;
}
/// <summary>
/// Initializes a new instance of the <see cref="EmailDto"/> class.
/// </summary>
public EmailDto()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapperPerformace.Testing
{
public class EmailDto
{
public int EmailAddressID
{
get;
set;
}
public string EmailAddress
{
get;
set;
}
public DateTime ModifiedDate
{
get;
set;
}
public EmailDto()
{
}
}
}
| mit | C# |
2d906ddcc325da720b14ea5aa52b08451253a3dd | Simplify path-format conversions. | tintoy/msbuild-project-tools-vscode,tintoy/msbuild-project-tools-vscode | src/LanguageServer.Engine/Utilities/UriExtensions.cs | src/LanguageServer.Engine/Utilities/UriExtensions.cs | using System;
using System.IO;
namespace MSBuildProjectTools.LanguageServer.Utilities
{
/// <summary>
/// Helper methods for <see cref="Uri"/>s.
/// </summary>
static class UriHelper
{
/// <summary>
/// Get the local file-system path for the specified URI.
/// </summary>
/// <param name="uri">
/// The URI.
/// </param>
/// <returns>
/// The file-system path, or <c>null</c> if the URI does not represent a file-system path.
/// </returns>
public static string GetFileSystemPath(this Uri uri)
{
if (uri == null)
throw new ArgumentNullException(nameof(uri));
if (uri.Scheme != Uri.UriSchemeFile)
return null;
// The language server protocol represents "C:\Foo\Bar" as "file:///c:/foo/bar".
string path = uri.LocalPath;
if (path.StartsWith("\\"))
path = path.Substring(1);
path = path.Replace('\\', '/');
return path;
}
/// <summary>
/// Convert a file-system path to a VSCode document URI.
/// </summary>
/// <param name="fileSystemPath">
/// The file-system path.
/// </param>
/// <returns>
/// The VSCode document URI.
/// </returns>
public static Uri CreateDocumentUri(string fileSystemPath)
{
if (String.IsNullOrWhiteSpace(fileSystemPath))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'fileSystemPath'.", nameof(fileSystemPath));
if (!Path.IsPathRooted(fileSystemPath))
throw new ArgumentException($"Path '{fileSystemPath}' is not an absolute path.", nameof(fileSystemPath));
if (Path.DirectorySeparatorChar == '\\')
fileSystemPath = fileSystemPath.Replace('\\', '/');
return new Uri("file:///" + fileSystemPath);
}
}
}
| using System;
using System.IO;
namespace MSBuildProjectTools.LanguageServer.Utilities
{
/// <summary>
/// Helper methods for <see cref="Uri"/>s.
/// </summary>
static class UriHelper
{
/// <summary>
/// Get the local file-system path for the specified URI.
/// </summary>
/// <param name="uri">
/// The URI.
/// </param>
/// <returns>
/// The file-system path, or <c>null</c> if the URI does not represent a file-system path.
/// </returns>
public static string GetFileSystemPath(this Uri uri)
{
if (uri == null)
throw new ArgumentNullException(nameof(uri));
if (uri.Scheme != Uri.UriSchemeFile)
return null;
// The language server protocol represents "C:\Foo\Bar" as "file:///c:/foo/bar".
string path = uri.LocalPath;
if (Path.DirectorySeparatorChar == '\\')
{
if (path.StartsWith("/"))
path = path.Substring(1);
path = path.Replace('\\', '/');
}
return path;
}
/// <summary>
/// Convert a file-system path to a VSCode document URI.
/// </summary>
/// <param name="fileSystemPath">
/// The file-system path.
/// </param>
/// <returns>
/// The VSCode document URI.
/// </returns>
public static Uri CreateDocumentUri(string fileSystemPath)
{
if (String.IsNullOrWhiteSpace(fileSystemPath))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'fileSystemPath'.", nameof(fileSystemPath));
if (!Path.IsPathRooted(fileSystemPath))
throw new ArgumentException($"Path '{fileSystemPath}' is not an absolute path.", nameof(fileSystemPath));
if (Path.DirectorySeparatorChar == '\\')
fileSystemPath = fileSystemPath.Replace('\\', '/');
return new Uri("file:///" + fileSystemPath);
}
}
}
| mit | C# |
9f63c163c50e3dd321984f95887cb8725ef3d6c5 | Fix bug in ValueSlotDependencyFinder | terrajobst/nquery-vnext | src/NQuery/Optimization/ValueSlotDependencyFinder.cs | src/NQuery/Optimization/ValueSlotDependencyFinder.cs | using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal sealed class ValueSlotDependencyFinder : BoundTreeWalker
{
public ValueSlotDependencyFinder()
{
ValueSlots = new HashSet<ValueSlot>();
}
public ValueSlotDependencyFinder(HashSet<ValueSlot> valueSlots)
{
ValueSlots = valueSlots;
}
public HashSet<ValueSlot> ValueSlots { get; }
protected override void VisitValueSlotExpression(BoundValueSlotExpression node)
{
ValueSlots.Add(node.ValueSlot);
base.VisitValueSlotExpression(node);
}
protected override void VisitSingleRowSubselect(BoundSingleRowSubselect node)
{
var output = node.Relation.GetOutputValues().Single();
ValueSlots.Add(output);
base.VisitSingleRowSubselect(node);
}
}
} | using System;
using System.Collections.Generic;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal sealed class ValueSlotDependencyFinder : BoundTreeWalker
{
public ValueSlotDependencyFinder()
{
ValueSlots = new HashSet<ValueSlot>();
}
public ValueSlotDependencyFinder(HashSet<ValueSlot> valueSlots)
{
ValueSlots = valueSlots;
}
public HashSet<ValueSlot> ValueSlots { get; }
protected override void VisitValueSlotExpression(BoundValueSlotExpression node)
{
ValueSlots.Add(node.ValueSlot);
base.VisitValueSlotExpression(node);
}
}
} | mit | C# |
ff0e82368ca3598416a126fc502d4d3a366edd1f | Change assembly copyright attribute | UsageStats/UsageStats,objorke/UsageStats | Source/AssemblyInfo.cs | Source/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyProduct("UsageStats")]
[assembly: AssemblyCompany("UsageStats")]
[assembly: AssemblyCopyright("© UsageStats contributors. All rights reserved.")]
[assembly: AssemblyTrademark("")]
// [assembly: CLSCompliant(true)]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version numbers will be updated by the build script
[assembly: AssemblyVersion("2.0.0")]
[assembly: AssemblyFileVersion("2.0.0")] | using System.Reflection;
using System.Runtime.InteropServices;
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyProduct("UsageStats")]
[assembly: AssemblyCompany("objo.net")]
[assembly: AssemblyCopyright("© Oystein Bjorke. All rights reserved.")]
[assembly: AssemblyTrademark("")]
// [assembly: CLSCompliant(true)]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version numbers will be updated by the build script
[assembly: AssemblyVersion("2.0.0")]
[assembly: AssemblyFileVersion("2.0.0")] | mit | C# |
05393041b3e4f29c21aaacc8edbca104f4e6c80a | Set current directory when running as a service. | VoiDeD/steam-irc-bot | SteamIrcBot/Program.cs | SteamIrcBot/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Reflection;
using System.IO;
namespace SteamIrcBot
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main( string[] args )
{
string path = Assembly.GetExecutingAssembly().Location;
path = Path.GetDirectoryName( path );
Directory.SetCurrentDirectory( path );
AppDomain.CurrentDomain.UnhandledException += ( sender, e ) =>
{
Log.WriteError( "Program", "Unhandled exception (IsTerm: {0}): {1}", e.IsTerminating, e.ExceptionObject );
};
var service = new BotService();
#if SERVICE_BUILD
ServiceBase.Run( service );
#else
service.Start( args );
#endif
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace SteamIrcBot
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main( string[] args )
{
AppDomain.CurrentDomain.UnhandledException += ( sender, e ) =>
{
Log.WriteError( "Program", "Unhandled exception (IsTerm: {0}): {1}", e.IsTerminating, e.ExceptionObject );
};
var service = new BotService();
#if SERVICE_BUILD
ServiceBase.Run( service );
#else
service.Start( args );
#endif
}
}
}
| mit | C# |
abd64947311910fe46732138dd96f2048896534d | Fix all style cop issues | Lunch-box/SimpleOrderRouting | CSharp/SimpleOrderRouting.Journey1/InstructionExecutionContext.cs | CSharp/SimpleOrderRouting.Journey1/InstructionExecutionContext.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="InstructionExecutionContext.cs" company="LunchBox corp">
// Copyright 2014 The Lunch-Box mob:
// Ozgur DEVELIOGLU (@Zgurrr)
// Cyrille DUPUYDAUBY (@Cyrdup)
// Tomasz JASKULA (@tjaskula)
// Mendel MONTEIRO-BECKERMAN (@MendelMonteiro)
// Thomas PIERRAIN (@tpierrain)
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SimpleOrderRouting.Journey1
{
using System;
/// <summary>
/// 1 to 1 relationship with an <see cref="InvestorInstruction"/>. Keeps the current state of the instruction execution.
/// </summary>
public class InstructionExecutionContext
{
private readonly InvestorInstruction investorInstruction;
private readonly int initialQuantity;
public InstructionExecutionContext(InvestorInstruction investorInstruction)
{
this.investorInstruction = investorInstruction;
this.initialQuantity = investorInstruction.Quantity;
this.Quantity = investorInstruction.Quantity;
this.Price = investorInstruction.Price;
this.Way = investorInstruction.Way;
this.AllowPartialExecution = investorInstruction.AllowPartialExecution;
}
public int Quantity { get; private set; }
public decimal Price { get; private set; }
public Way Way { get; private set; }
public bool AllowPartialExecution { get; private set; }
/// <summary>
/// Called when an order has been executed - called by the order basket.
/// </summary>
/// <param name="quantity">The executed quantity.</param>
public void Executed(int quantity)
{
this.Quantity -= quantity;
if (this.Quantity == 0)
{
this.investorInstruction.NotifyOrderExecution(this.initialQuantity, this.Price);
}
else if (this.Quantity < 0)
{
throw new ApplicationException("Executed more than specified in the investor instruction.");
}
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="InstructionExecutionContext.cs" company="LunchBox corp">
// Copyright 2014 The Lunch-Box mob:
// Ozgur DEVELIOGLU (@Zgurrr)
// Cyrille DUPUYDAUBY (@Cyrdup)
// Tomasz JASKULA (@tjaskula)
// Mendel MONTEIRO-BECKERMAN (@MendelMonteiro)
// Thomas PIERRAIN (@tpierrain)
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace SimpleOrderRouting.Journey1
{
using System;
/// <summary>
/// 1 to 1 relationship with an <see cref="InvestorInstruction"/>. Keeps the current state of the instruction execution.
/// </summary>
public class InstructionExecutionContext
{
private readonly InvestorInstruction investorInstruction;
private readonly int initialQuantity;
public InstructionExecutionContext(InvestorInstruction investorInstruction)
{
this.investorInstruction = investorInstruction;
this.initialQuantity = investorInstruction.Quantity;
this.Quantity = investorInstruction.Quantity;
this.Price = investorInstruction.Price;
this.Way = investorInstruction.Way;
this.AllowPartialExecution = investorInstruction.AllowPartialExecution;
}
public int Quantity { get; private set; }
public decimal Price { get; private set; }
public Way Way { get; private set; }
public bool AllowPartialExecution { get; private set; }
/// <summary>
/// Called when an order has been executed - called by the order basket
/// </summary>
/// <param name="quantity"></param>
public void Executed(int quantity)
{
this.Quantity -= quantity;
if (Quantity == 0)
{
investorInstruction.NotifyOrderExecution(this.initialQuantity, Price);
}
else if (Quantity < 0)
{
throw new ApplicationException("Executed more than specified in the investor instruction.");
}
}
}
} | apache-2.0 | C# |
62784221106be3c126e7bbb77f5a794cf0e7aeb7 | Fix default batch posting limit and body size | datalust/clef-tool | src/Datalust.ClefTool/Cli/Features/SeqOutputFeature.cs | src/Datalust.ClefTool/Cli/Features/SeqOutputFeature.cs | // Copyright 2016-2017 Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Datalust.ClefTool.Cli.Features
{
class SeqOutputFeature : CommandFeature
{
public string SeqUrl { get; private set; }
public string SeqApiKey { get; private set; }
public int BatchPostingLimit { get; private set; } = 100;
public long? EventBodyLimitBytes { get; private set; } = 256 * 1000;
public override void Enable(OptionSet options)
{
options.Add("out-seq=",
"Send output to Seq at the specified URL",
v => SeqUrl = string.IsNullOrWhiteSpace(v) ? null : v.Trim());
options.Add("out-seq-apikey=",
"Specify the API key to use when writing to Seq, if required",
v => SeqApiKey = string.IsNullOrWhiteSpace(v) ? null : v.Trim());
options.Add("out-seq-batchpostinglimit=",
"The maximum number of events to post in a single batch",
v => BatchPostingLimit = int.Parse((v ?? "").Trim()));
options.Add("out-seq-eventbodylimitbytes=",
"The maximum size, in bytes, that the JSON representation of an event may take before it is dropped rather than being sent to the Seq server",
v => EventBodyLimitBytes = string.IsNullOrWhiteSpace(v) ? (long?)null : long.Parse(v.Trim()));
}
}
}
| // Copyright 2016-2017 Datalust Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Datalust.ClefTool.Cli.Features
{
class SeqOutputFeature : CommandFeature
{
public const int DefaultBatchPostingLimit = 100;
public const long DefaultEventBodyLimitBytes = 256 * 1000;
public string SeqUrl { get; private set; }
public string SeqApiKey { get; private set; }
public int BatchPostingLimit { get; private set; }
public long? EventBodyLimitBytes { get; private set; }
public override void Enable(OptionSet options)
{
options.Add("out-seq=",
"Send output to Seq at the specified URL",
v => SeqUrl = string.IsNullOrWhiteSpace(v) ? null : v.Trim());
options.Add("out-seq-apikey=",
"Specify the API key to use when writing to Seq, if required",
v => SeqApiKey = string.IsNullOrWhiteSpace(v) ? null : v.Trim());
options.Add("out-seq-batchpostinglimit=",
"The maximum number of events to post in a single batch",
v => BatchPostingLimit = string.IsNullOrWhiteSpace(v) ? DefaultBatchPostingLimit : (int.TryParse(v.Trim(), out var postingLimit) ? postingLimit : DefaultBatchPostingLimit));
options.Add("out-seq-eventbodylimitbytes=",
"The maximum size, in bytes, that the JSON representation of an event may take before it is dropped rather than being sent to the Seq server",
v => EventBodyLimitBytes = string.IsNullOrWhiteSpace(v) ? DefaultEventBodyLimitBytes : (long.TryParse(v.Trim(), out var bodyLimit) ? bodyLimit : DefaultEventBodyLimitBytes));
}
}
}
| apache-2.0 | C# |
b4b9191b969fda596115b1c1d981b22de4f1ade9 | Revert "Test commit" | kpnlora/LoRaClient | src/Kpn.LoRa.Api.Stub/src/Kpn.LoRa.Api.Stub/Startup.cs | src/Kpn.LoRa.Api.Stub/src/Kpn.LoRa.Api.Stub/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.Application;
namespace Kpn.LoRa.Api.Stub
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build().ReloadOnChanged("appsettings.json");
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
services.AddSwaggerGen();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseMvc();
app.UseSwaggerGen();
app.UseSwaggerUi();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Kpn.LoRa.Api.Stub
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build().ReloadOnChanged("appsettings.json");
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
services.AddSwaggerGen();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseMvc();
app.UseSwaggerGen();
app.UseSwaggerUi();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| mit | C# |
f080b773b5cec1d90c8f36d91981d548dc0dbb0f | Call Start() only for stream providers that implement IStreamProviderImpl | zhangf911/orleans,hoopsomuah/orleans,dariobottazzi/orleans,modulexcite/orleans,Liversage/orleans,cbredlow/orleans,centur/orleans,zhangf911/orleans,skalpin/orleans,LoveElectronics/orleans,dVakulen/orleans,NaseUkolyCZ/orleans,yevhen/orleans,kucheruk/orleans,ashkan-saeedi-mazdeh/orleans,MikeHardman/orleans,garbervetsky/orleans,dotnet/orleans,TedDBarr/orleans,gigya/orleans,dVakulen/orleans,galvesribeiro/orleans,amccool/orleans,sergeybykov/orleans,kylemc/orleans,shlomiw/orleans,xclayl/orleans,veikkoeeva/orleans,benjaminpetit/orleans,waynemunro/orleans,jokin/orleans,dVakulen/orleans,NaseUkolyCZ/orleans,brhinescot/orleans,ibondy/orleans,pherbel/orleans,jokin/orleans,ticup/orleans,centur/orleans,amccool/orleans,rrector/orleans,yevhen/orleans,garbervetsky/orleans,jthelin/orleans,SoftWar1923/orleans,SoftWar1923/orleans,shayhatsor/orleans,ashkan-saeedi-mazdeh/orleans,ticup/orleans,kylemc/orleans,Liversage/orleans,galvesribeiro/orleans,shlomiw/orleans,jokin/orleans,kangkot/orleans,jason-bragg/orleans,carlos-sarmiento/orleans,kucheruk/orleans,Carlm-MS/orleans,bstauff/orleans,pherbel/orleans,cato541265/orleans,bstauff/orleans,dotnet/orleans,hoopsomuah/orleans,amccool/orleans,sebastianburckhardt/orleans,gabikliot/orleans,MikeHardman/orleans,ibondy/orleans,jdom/orleans,rore/orleans,ElanHasson/orleans,sergeybykov/orleans,Carlm-MS/orleans,carlos-sarmiento/orleans,sebastianburckhardt/orleans,TedDBarr/orleans,jkonecki/orleans,Joshua-Ferguson/orleans,brhinescot/orleans,kangkot/orleans,tsibelman/orleans,brhinescot/orleans,ElanHasson/orleans,skalpin/orleans,Joshua-Ferguson/orleans,rore/orleans,cato541265/orleans,rrector/orleans,gabikliot/orleans,modulexcite/orleans,ReubenBond/orleans,kowalot/orleans,gigya/orleans,kowalot/orleans,tsibelman/orleans,jkonecki/orleans,yaronthurm/orleans,ashkan-saeedi-mazdeh/orleans,cbredlow/orleans,jdom/orleans,Liversage/orleans,shayhatsor/orleans,xclayl/orleans,waynemunro/orleans,dariobottazzi/orleans,LoveElectronics/orleans | src/Orleans/Streams/Providers/StreamProviderManager.cs | src/Orleans/Streams/Providers/StreamProviderManager.cs | /*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
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 Orleans.Providers;
using Orleans.Runtime.Configuration;
using System.Threading.Tasks;
namespace Orleans.Streams
{
internal class StreamProviderManager : IStreamProviderManager
{
private ProviderLoader<IStreamProvider> appStreamProviders;
internal async Task LoadStreamProviders(
IDictionary<string, ProviderCategoryConfiguration> configs,
IStreamProviderRuntime providerRuntime)
{
appStreamProviders = new ProviderLoader<IStreamProvider>();
if (!configs.ContainsKey("Stream")) return;
appStreamProviders.LoadProviders(configs["Stream"].Providers, this);
await appStreamProviders.InitProviders(providerRuntime);
}
internal async Task StartStreamProviders()
{
var providers = appStreamProviders.GetProviders();
foreach (IStreamProvider streamProvider in providers)
{
var provider = streamProvider as IStreamProviderImpl;
if (provider != null)
{
await provider.Start();
}
}
}
public IEnumerable<IStreamProvider> GetStreamProviders()
{
return appStreamProviders.GetProviders();
}
public IProvider GetProvider(string name)
{
return appStreamProviders.GetProvider(name);
}
}
} | /*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
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 Orleans.Providers;
using Orleans.Runtime.Configuration;
using System.Threading.Tasks;
namespace Orleans.Streams
{
internal class StreamProviderManager : IStreamProviderManager
{
private ProviderLoader<IStreamProvider> appStreamProviders;
internal async Task LoadStreamProviders(
IDictionary<string, ProviderCategoryConfiguration> configs,
IStreamProviderRuntime providerRuntime)
{
appStreamProviders = new ProviderLoader<IStreamProvider>();
if (!configs.ContainsKey("Stream")) return;
appStreamProviders.LoadProviders(configs["Stream"].Providers, this);
await appStreamProviders.InitProviders(providerRuntime);
}
internal async Task StartStreamProviders()
{
var providers = appStreamProviders.GetProviders();
foreach (IStreamProvider streamProvider in providers)
{
var provider = (IStreamProviderImpl) streamProvider;
await provider.Start();
}
}
public IEnumerable<IStreamProvider> GetStreamProviders()
{
return appStreamProviders.GetProviders();
}
public IProvider GetProvider(string name)
{
return appStreamProviders.GetProvider(name);
}
}
} | mit | C# |
1ebda5fe9360eb29a143ca13b3526570382049b7 | add some basic methods to the manager. | VolatileMindsLLC/openvas-sharp | OpenVASManager.cs | OpenVASManager.cs | using System;
using System.Xml;
using System.Xml.Linq;
namespace openvassharp
{
public class OpenVASManager : IDisposable
{
private OpenVASSession _session;
public OpenVASManager(OpenVASSession session)
{
if (session != null)
_session = session;
}
public XDocument GetVersion() {
return _session.ExecuteCommand (XDocument.Parse ("<get_version />"));
}
public XDocument GetScanConfigurations() {
return _session.ExecuteCommand (XDocument.Parse ("<get_configs />"), true);
}
public XDocument CreateSimpleTarget(string cidrRange, string targetName) {
XDocument createTargetXML = new XDocument (
new XElement ("create_target",
new XElement ("name", targetName),
new XElement ("hosts", cidrRange)));
return _session.ExecuteCommand(createTargetXML, true);
}
public XDocument CreateSimpleTask(string name, string comment, Guid configID, Guid targetID) {
XDocument createTaskXML = new XDocument(
new XElement("create_task",
new XElement("name", name),
new XElement("comment", comment),
new XElement("config",
new XAttribute("id", configID.ToString())),
new XElement("target",
new XAttribute("id", targetID.ToString()))));
return _session.ExecuteCommand(createTaskXML, true);
}
public XDocument StartTask(Guid taskID) {
XDocument startTaskXML = new XDocument (
new XElement ("start_task",
new XAttribute ("task_id", taskID.ToString ())));
return _session.ExecuteCommand(startTaskXML, true);
}
public XDocument GetTasks() {
return _session.ExecuteCommand (XDocument.Parse ("<get_tasks />"), true);
}
public XDocument GetTaskResults(Guid taskID) {
XDocument getTaskResultsXML = new XDocument (
new XElement ("get_results",
new XAttribute ("task_id", taskID.ToString ())));
return _session.ExecuteCommand(getTaskResultsXML, true);
}
public void Dispose()
{
_session.Dispose ();
}
}
}
| using System;
using System.Xml;
using System.Xml.Linq;
namespace openvassharp
{
public class OpenVASManager : IDisposable
{
private OpenVASSession _session;
public OpenVASManager(OpenVASSession session)
{
if (session != null)
_session = session;
}
public XDocument GetVersion() {
return _session.ExecuteCommand (XDocument.Parse ("<get_version />"));
}
public XDocument GetScanConfigurations() {
return _session.ExecuteCommand (XDocument.Parse ("<get_configs />"), true);
}
public XDocument CreateSimpleTarget(string cidrRange, string targetName) {
return null;
}
public XDocument CreateSimpleTask(string name, string comment, Guid configID, Guid targetID) {
return null;
}
public XDocument StartTask(Guid taskID) {
return null;
}
public XDocument GetTasks() {
return null;
}
public XDocument GetTaskResults(Guid taskID) {
return null;
}
public void Dispose()
{
_session = null;
}
}
}
| bsd-3-clause | C# |
df8675fb4ebf656925c0b3c922702b878f4d3eed | Add AssemblyFlags.None enum value | yck1509/dnlib,modulexcite/dnlib,ZixiangBoy/dnlib,Arthur2e5/dnlib,jorik041/dnlib,0xd4d/dnlib,ilkerhalil/dnlib,kiootic/dnlib,picrap/dnlib | dot10/dotNET/Types/AssemblyFlags.cs | dot10/dotNET/Types/AssemblyFlags.cs | using System;
namespace dot10.dotNET.Types {
/// <summary>
/// Assembly flags from Assembly.Flags column.
/// </summary>
/// <remarks>See CorHdr.h/CorAssemblyFlags</remarks>
[Flags]
public enum AssemblyFlags : uint {
/// <summary>
/// No flags set
/// </summary>
None = 0,
/// <summary>
/// The assembly ref holds the full (unhashed) public key.
/// </summary>
PublicKey = 1,
/// <summary>Processor Architecture unspecified</summary>
PA_None = 0x0000,
/// <summary>Processor Architecture: neutral (PE32)</summary>
PA_MSIL = 0x0010,
/// <summary>Processor Architecture: x86 (PE32)</summary>
PA_x86 = 0x0020,
/// <summary>Processor Architecture: Itanium (PE32+)</summary>
PA_IA64 = 0x0030,
/// <summary>Processor Architecture: AMD X64 (PE32+)</summary>
PA_AMD64 = 0x0040,
/// <summary>Processor Architecture: ARM (PE32)</summary>
PA_ARM = 0x0050,
/// <summary>applies to any platform but cannot run on any (e.g. reference assembly), should not have "specified" set</summary>
PA_NoPlatform = 0x0070,
/// <summary>Propagate PA flags to AssemblyRef record</summary>
PA_Specified = 0x0080,
/// <summary>Bits describing the processor architecture</summary>
PA_Mask = 0x0070,
/// <summary>Bits describing the PA incl. Specified</summary>
PA_FullMask = 0x00F0,
/// <summary>NOT A FLAG, shift count in PA flags <--> index conversion</summary>
PA_Shift = 0x0004,
/// <summary>From "DebuggableAttribute".</summary>
EnableJITcompileTracking = 0x8000,
/// <summary>From "DebuggableAttribute".</summary>
DisableJITcompileOptimizer = 0x4000,
/// <summary>The assembly can be retargeted (at runtime) to an assembly from a different publisher.</summary>
Retargetable = 0x0100,
/// <summary></summary>
ContentType_Default = 0x0000,
/// <summary></summary>
ContentType_WindowsRuntime = 0x0200,
/// <summary>Bits describing ContentType</summary>
ContentType_Mask = 0x0E00,
}
}
| using System;
namespace dot10.dotNET.Types {
/// <summary>
/// Assembly flags from Assembly.Flags column.
/// </summary>
/// <remarks>See CorHdr.h/CorAssemblyFlags</remarks>
[Flags]
public enum AssemblyFlags : uint {
/// <summary>
/// The assembly ref holds the full (unhashed) public key.
/// </summary>
PublicKey = 1,
/// <summary>Processor Architecture unspecified</summary>
PA_None = 0x0000,
/// <summary>Processor Architecture: neutral (PE32)</summary>
PA_MSIL = 0x0010,
/// <summary>Processor Architecture: x86 (PE32)</summary>
PA_x86 = 0x0020,
/// <summary>Processor Architecture: Itanium (PE32+)</summary>
PA_IA64 = 0x0030,
/// <summary>Processor Architecture: AMD X64 (PE32+)</summary>
PA_AMD64 = 0x0040,
/// <summary>Processor Architecture: ARM (PE32)</summary>
PA_ARM = 0x0050,
/// <summary>applies to any platform but cannot run on any (e.g. reference assembly), should not have "specified" set</summary>
PA_NoPlatform = 0x0070,
/// <summary>Propagate PA flags to AssemblyRef record</summary>
PA_Specified = 0x0080,
/// <summary>Bits describing the processor architecture</summary>
PA_Mask = 0x0070,
/// <summary>Bits describing the PA incl. Specified</summary>
PA_FullMask = 0x00F0,
/// <summary>NOT A FLAG, shift count in PA flags <--> index conversion</summary>
PA_Shift = 0x0004,
/// <summary>From "DebuggableAttribute".</summary>
EnableJITcompileTracking = 0x8000,
/// <summary>From "DebuggableAttribute".</summary>
DisableJITcompileOptimizer = 0x4000,
/// <summary>The assembly can be retargeted (at runtime) to an assembly from a different publisher.</summary>
Retargetable = 0x0100,
/// <summary></summary>
ContentType_Default = 0x0000,
/// <summary></summary>
ContentType_WindowsRuntime = 0x0200,
/// <summary>Bits describing ContentType</summary>
ContentType_Mask = 0x0E00,
}
}
| mit | C# |
4f35765bd233763afca72f8487fb02c1adb8fbec | Remove unused namespace. | mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy | examples/HelloWorld/HelloWorld.cs | examples/HelloWorld/HelloWorld.cs | //
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using Manos;
using System;
using System.IO;
namespace HelloWorld {
public class HelloWorld : ManosApp {
public HelloWorld ()
{
Route ("/", ctx => ctx.Response.End ("Hello, World"));
Route ("/shutdown", ctx => System.Environment.Exit (0));
Route ("/transactions", ctx => {
ctx.Response.Write ("Number of transactions: '{0}'", ctx.Server.Transactions.Count);
foreach (var t in ctx.Server.Transactions) {
ctx.Response.WriteLine ("{0}", t.Request.LocalPath);
}
ctx.Response.End ();
});
Route ("/timeout", ctx => {
ctx.Response.WriteLine ("Hello");
AddTimeout (TimeSpan.FromSeconds (2), (app, data) => {
Console.WriteLine ("writing world.");
ctx.Response.WriteLine ("World");
ctx.Response.End ();
});
});
Route ("/encoding", ctx => {
ctx.Response.ContentEncoding = System.Text.Encoding.UTF8;
ctx.Response.SetHeader ("Content-Type","text/html; charset=UTF-8");
ctx.Response.Write ("À");
Console.WriteLine ("Writing: '{0}'", "À");
ctx.Response.End ();
});
Get ("/upload", ctx => {
ctx.Response.Write ("<html><head></head><body>");
ctx.Response.Write ("<form method=\"POST\" enctype=\"multipart/form-data\">");
ctx.Response.Write ("<input type=\"text\" name=\"some_name\"><br>");
ctx.Response.Write ("<input type=\"file\" name=\"the_file\" >");
ctx.Response.Write ("<input type=\"submit\">");
ctx.Response.Write ("</form>");
ctx.Response.Write ("</body></html>");
ctx.Response.End ();
});
Post ("/upload", ctx => {
ctx.Response.End ("handled upload!");
});
}
}
}
| //
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using Manos;
using Manos.Utilities;
using System;
using System.IO;
namespace HelloWorld {
public class HelloWorld : ManosApp {
public HelloWorld ()
{
Route ("/", ctx => ctx.Response.End ("Hello, World"));
Route ("/shutdown", ctx => System.Environment.Exit (0));
Route ("/transactions", ctx => {
ctx.Response.Write ("Number of transactions: '{0}'", ctx.Server.Transactions.Count);
foreach (var t in ctx.Server.Transactions) {
ctx.Response.WriteLine ("{0}", t.Request.LocalPath);
}
ctx.Response.End ();
});
Route ("/timeout", ctx => {
ctx.Response.WriteLine ("Hello");
AddTimeout (TimeSpan.FromSeconds (2), (app, data) => {
Console.WriteLine ("writing world.");
ctx.Response.WriteLine ("World");
ctx.Response.End ();
});
});
Route ("/encoding", ctx => {
ctx.Response.ContentEncoding = System.Text.Encoding.UTF8;
ctx.Response.SetHeader ("Content-Type","text/html; charset=UTF-8");
ctx.Response.Write ("À");
Console.WriteLine ("Writing: '{0}'", "À");
ctx.Response.End ();
});
Get ("/upload", ctx => {
ctx.Response.Write ("<html><head></head><body>");
ctx.Response.Write ("<form method=\"POST\" enctype=\"multipart/form-data\">");
ctx.Response.Write ("<input type=\"text\" name=\"some_name\"><br>");
ctx.Response.Write ("<input type=\"file\" name=\"the_file\" >");
ctx.Response.Write ("<input type=\"submit\">");
ctx.Response.Write ("</form>");
ctx.Response.Write ("</body></html>");
ctx.Response.End ();
});
Post ("/upload", ctx => {
ctx.Response.End ("handled upload!");
});
}
}
}
| mit | C# |
d6e6b43c527d84c76dbd5ddef5a4e8d7d8fad73b | Change name of ParserTest#IsFinished | lury-lang/lury-parser,lury-lang/lury-parser | UnitTest/ParserTest.cs | UnitTest/ParserTest.cs | using System;
using Lury.Compiling.Lexer;
using Lury.Compiling.Parser;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTest
{
[TestClass]
public class ParserTest
{
[TestMethod]
public void IsFinishedTest()
{
var lexer = new Lexer("", @"");
lexer.Tokenize();
var parser = new Parser(lexer.TokenOutput);
Assert.IsFalse(parser.IsFinished);
parser.Parse();
Assert.IsTrue(parser.IsFinished);
}
[TestMethod]
public void ParseTest1()
{
var lexer = new Lexer("", @"");
lexer.Tokenize();
var parser = new Parser(lexer.TokenOutput);
parser.Parse();
Assert.IsNotNull(parser.TreeOutput);
Assert.AreEqual(0, parser.TreeOutput.Count);
}
[TestMethod]
public void ParseTest2()
{
var lexer = new Lexer("", @"0");
lexer.Tokenize();
var parser = new Parser(lexer.TokenOutput);
parser.Parse();
Assert.IsNotNull(parser.TreeOutput);
Assert.AreEqual(1, parser.TreeOutput.Count);
}
}
}
| using System;
using Lury.Compiling.Lexer;
using Lury.Compiling.Parser;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTest
{
[TestClass]
public class ParserTest
{
[TestMethod]
public void IsFinished()
{
var lexer = new Lexer("", @"");
lexer.Tokenize();
var parser = new Parser(lexer.TokenOutput);
Assert.IsFalse(parser.IsFinished);
parser.Parse();
Assert.IsTrue(parser.IsFinished);
}
[TestMethod]
public void ParseTest1()
{
var lexer = new Lexer("", @"");
lexer.Tokenize();
var parser = new Parser(lexer.TokenOutput);
parser.Parse();
Assert.IsNotNull(parser.TreeOutput);
Assert.AreEqual(0, parser.TreeOutput.Count);
}
[TestMethod]
public void ParseTest2()
{
var lexer = new Lexer("", @"0");
lexer.Tokenize();
var parser = new Parser(lexer.TokenOutput);
parser.Parse();
Assert.IsNotNull(parser.TreeOutput);
Assert.AreEqual(1, parser.TreeOutput.Count);
}
}
}
| mit | C# |
c8ea9a55c4378029c1f5e1433a2a9bc1b29ba911 | increment version | YatoDev/DirectXOverlay | source/Properties/AssemblyInfo.cs | source/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("GameOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GameOverlay")]
[assembly: AssemblyCopyright("Copyright © 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("38128f56-038d-4826-a554-530f1a0fc13e")]
// 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("4.0.4.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("GameOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GameOverlay")]
[assembly: AssemblyCopyright("Copyright © 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("38128f56-038d-4826-a554-530f1a0fc13e")]
// 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("4.0.3.0")]
| mit | C# |
56177407f0a2ddfe7e2677290c79f38e194accde | update ProgressBar | jpbruyere/Crow,jpbruyere/Crow | src/GraphicObjects/ProgressBar.cs | src/GraphicObjects/ProgressBar.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cairo;
using System.Diagnostics;
using System.Xml.Serialization;
using System.ComponentModel;
namespace Crow
{
[Serializable]
public class ProgressBar : NumericControl
{
#region CTOR
public ProgressBar() : base(){}
#endregion
protected override void loadTemplate (GraphicObject template)
{
}
#region GraphicObject overrides
[XmlAttributeAttribute()][DefaultValue("vgradient|0:BlueCrayola|0,5:SkyBlue|1:BlueCrayola")]
public override Fill Foreground {
get { return base.Foreground; }
set { base.Foreground = value; }
}
protected override void onDraw (Context gr)
{
base.onDraw (gr);
Rectangle rBack = ClientRectangle;
rBack.Width = (int)((double)rBack.Width / Maximum * Value);
Foreground.SetAsSource (gr, rBack);
CairoHelpers.CairoRectangle(gr,rBack,CornerRadius);
gr.Fill();
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cairo;
using System.Diagnostics;
using System.Xml.Serialization;
using System.ComponentModel;
namespace Crow
{
[Serializable]
public class ProgressBar : Border
{
#region CTOR
public ProgressBar() : base(){}
public ProgressBar(int _max) : base()
{
Maximum = _max;
}
#endregion
#region private fields
int _currentValue = 0;
int _minimum = 0;
int _maximum = 100;
#endregion
#region public properties
[XmlAttributeAttribute()][DefaultValue(0)]
public int Value
{
get { return _currentValue; }
set
{
if (_currentValue == value)
return;
_currentValue = value;
if (_currentValue > Maximum)
_currentValue = Maximum;
registerForGraphicUpdate();
}
}
[XmlAttributeAttribute()][DefaultValue(0)]
public int Minimum {
get {return _minimum;}
set {
if (_minimum == value || _minimum >= Maximum)
return;
_minimum = value;
registerForGraphicUpdate ();
}
}
[XmlAttributeAttribute()][DefaultValue(100)]
public int Maximum {
get {return _maximum;}
set {
if (_maximum == value || _maximum <= _minimum)
return;
_maximum = value;
registerForGraphicUpdate();
}
}
#endregion
#region GraphicObject overrides
[XmlAttributeAttribute()][DefaultValue("Gray")]
public override Fill Background {
get { return base.Background; }
set { base.Background = value; }
}
[XmlAttributeAttribute()][DefaultValue(0)]
public override int BorderWidth {
get { return base.BorderWidth; }
set { base.BorderWidth = value; }
}
[XmlAttributeAttribute()][DefaultValue("BlueCrayola")]
public override Fill Foreground {
get { return base.Foreground; }
set { base.Foreground = value; }
}
protected override void onDraw (Context gr)
{
base.onDraw (gr);
Rectangle rBack = Slot.Size;
if (BorderWidth > 0)
rBack.Inflate(-BorderWidth, -BorderWidth);
rBack.Width = (int)((double)rBack.Width / Maximum * Value);
Foreground.SetAsSource (gr, rBack);
CairoHelpers.CairoRectangle(gr,rBack,CornerRadius);
gr.Fill();
}
#endregion
}
}
| mit | C# |
c5bc63f9e2a23ee504645cc133ba58130e956bd5 | Fix datetime json ext - lost one millisecond | maxkoryukov/MK.Lib,maxkoryukov/MK.WebLib | src/MK.Lib/Ext/DateTimeJsonExt.cs | src/MK.Lib/Ext/DateTimeJsonExt.cs | using System;
namespace MK.Ext
{
/// <summary>
/// DateTime Json Extensions
/// </summary>
public static class DateTimeJsonExt
{
private static readonly DateTime D1970_01_01 = new DateTime(1970, 1, 1);
public static string JsonValue(this DateTime d)
{
return "( new Date(" + ((d.Ticks - D1970_01_01.Ticks) / 10000) + "))";
}
}
} | using System;
namespace MK.Ext
{
/// <summary>
/// DateTime Json Extensions
/// </summary>
public static class DateTimeJsonExt
{
private static readonly DateTime D1970_01_01 = new DateTime(1970, 1, 1);
public static string JsonValue(this DateTime d)
{
return "( new Date(" + System.Convert.ToInt64((d - D1970_01_01).TotalMilliseconds) + "))";
}
}
} | mit | C# |
dbef30f3c469423194fc90adfb2a97eb206f271f | Bump version to 0.14.0 | quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot | CactbotOverlay/Properties/AssemblyInfo.cs | CactbotOverlay/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.14.0.0")]
[assembly: AssemblyFileVersion("0.14.0.0")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.13.5.0")]
[assembly: AssemblyFileVersion("0.13.5.0")] | apache-2.0 | C# |
62baee7d0f488ea63a8c6ce42e7f6983e4c07b3e | Change "Policy.maxRetries" default from 2 to 1. | YuvalItzchakov/aerospike-client-csharp | AerospikeClient/Policy/Policy.cs | AerospikeClient/Policy/Policy.cs | /*
* Copyright 2012-2014 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* 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.
*/
namespace Aerospike.Client
{
/// <summary>
/// Container object for transaction policy attributes used in all database
/// operation calls.
/// </summary>
public class Policy
{
/// <summary>
/// Priority of request relative to other transactions.
/// Currently, only used for scans.
/// </summary>
public Priority priority = Priority.DEFAULT;
/// <summary>
/// Transaction timeout in milliseconds.
/// This timeout is used to set the socket timeout and is also sent to the
/// server along with the transaction in the wire protocol.
/// Default to no timeout (0).
/// </summary>
public int timeout;
/// <summary>
/// Maximum number of retries before aborting the current transaction.
/// A retry is attempted when there is a network error other than timeout.
/// If maxRetries is exceeded, the abort will occur even if the timeout
/// has not yet been exceeded. The default number of retries is 1.
/// </summary>
public int maxRetries = 1;
/// <summary>
/// Milliseconds to sleep between retries if a transaction fails and the
/// timeout was not exceeded. The default sleep between retries is 500 ms.
/// </summary>
public int sleepBetweenRetries = 500;
/// <summary>
/// Allow read operations to use replicated data partitions instead of master
/// partition. By default, both read and write operations are directed to the
/// master partition.
/// <para>
/// This variable is currently only used in batch read/exists operations. For
/// batch, this variable should only be set to true when the replication factor
/// is greater than or equal to the number of nodes in the cluster.
/// </para>
/// </summary>
public bool allowProleReads;
/// <summary>
/// Copy constructor.
/// </summary>
public Policy(Policy other)
{
this.priority = other.priority;
this.timeout = other.timeout;
this.maxRetries = other.maxRetries;
this.sleepBetweenRetries = other.sleepBetweenRetries;
this.allowProleReads = other.allowProleReads;
}
/// <summary>
/// Default constructor.
/// </summary>
public Policy()
{
}
}
}
| /*
* Copyright 2012-2014 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* 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.
*/
namespace Aerospike.Client
{
/// <summary>
/// Container object for transaction policy attributes used in all database
/// operation calls.
/// </summary>
public class Policy
{
/// <summary>
/// Priority of request relative to other transactions.
/// Currently, only used for scans.
/// </summary>
public Priority priority = Priority.DEFAULT;
/// <summary>
/// Transaction timeout in milliseconds.
/// This timeout is used to set the socket timeout and is also sent to the
/// server along with the transaction in the wire protocol.
/// Default to no timeout (0).
/// </summary>
public int timeout;
/// <summary>
/// Maximum number of retries before aborting the current transaction.
/// A retry is attempted when there is a network error other than timeout.
/// If maxRetries is exceeded, the abort will occur even if the timeout
/// has not yet been exceeded. The default number of retries is 2.
/// </summary>
public int maxRetries = 2;
/// <summary>
/// Milliseconds to sleep between retries if a transaction fails and the
/// timeout was not exceeded. The default sleep between retries is 500 ms.
/// </summary>
public int sleepBetweenRetries = 500;
/// <summary>
/// Allow read operations to use replicated data partitions instead of master
/// partition. By default, both read and write operations are directed to the
/// master partition.
/// <para>
/// This variable is currently only used in batch read/exists operations. For
/// batch, this variable should only be set to true when the replication factor
/// is greater than or equal to the number of nodes in the cluster.
/// </para>
/// </summary>
public bool allowProleReads;
/// <summary>
/// Copy constructor.
/// </summary>
public Policy(Policy other)
{
this.priority = other.priority;
this.timeout = other.timeout;
this.maxRetries = other.maxRetries;
this.sleepBetweenRetries = other.sleepBetweenRetries;
this.allowProleReads = other.allowProleReads;
}
/// <summary>
/// Default constructor.
/// </summary>
public Policy()
{
}
}
}
| apache-2.0 | C# |
5f6a9dfe5078ab11aef4dd367bb978bbc695df3d | Change the page title and h1. | bigfont/sweet-water-revolver | mvcWebApp/Views/Home/Index.cshtml | mvcWebApp/Views/Home/Index.cshtml | @{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sweet Water Revolver</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Sweet Water Revolver</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="assets/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
| @{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="assets/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
| mit | C# |
b321de76fb49d404aaf842e030e23f526fde45bb | Add mapping for all entities | Marusyk/SmartVillageOnline,Marusyk/SmartVillageOnline | BLL/Mapping/AutomapperProfile.cs | BLL/Mapping/AutomapperProfile.cs | using AutoMapper;
using BusinessEntities;
using BusinessEntities.Dictionaries;
using DataModel;
using DataModel.Dictionaries;
namespace BLL.Mapping
{
public class AutomapperProfile : Profile
{
public AutomapperProfile()
{
CreateMap<Animal, AnimalEntity>();
CreateMap<Council, CouncilEntity>();
CreateMap<ActivityType, ActivityTypeEntity>();
CreateMap<Address, AddressEntity>();
CreateMap<City, CityEntity>();
CreateMap<CityType, CityTypeEntity>();
CreateMap<Company, CompanyEntity>();
CreateMap<Country, CountryEntity>();
CreateMap<District, DistrictEntity>();
CreateMap<DocumentType, DocumentTypeEntity>();
CreateMap<EducationDegree, EducationDegreeEntity>();
CreateMap<FamilyRelations, FamilyRelationsEntity>();
CreateMap<FamilyStatus, FamilyStatusEntity>();
CreateMap<Institution, InstitutionEntity>();
CreateMap<Material, MaterialEntity>();
CreateMap<Nationality, NationalityEntity>();
CreateMap<PassAuthority, PassAuthorityEntity>();
CreateMap<PensionType, PensionTypeEntity>();
CreateMap<Person, PersonEntity>();
CreateMap<Position, PositionEntity>();
CreateMap<Region, RegionEntity>();
CreateMap<Speciality, SpecialityEntity>();
CreateMap<Street, StreetEntity>();
CreateMap<StreetType, StreetType>();
CreateMap<Catalog, CatalogEntity>();
CreateMap<Document, DocumentEntity>();
CreateMap<Education, EducationEntity>();
CreateMap<Employment, EmploymentEntity>();
CreateMap<House, HouseEntity>();
CreateMap<People, PeopleEntity>();
CreateMap<PersonDocument, PersonDocumentEntity>();
}
}
}
| using AutoMapper;
using BusinessEntities;
using BusinessEntities.Dictionaries;
using DataModel;
using DataModel.Dictionaries;
namespace BLL.Mapping
{
public class AutomapperProfile : Profile
{
public AutomapperProfile()
{
CreateMap<Animal, AnimalEntity>();
CreateMap<Council, CouncilEntity>();
}
}
}
| mit | C# |
60f88c3ddd6ae8df1f804b8f12b1a0b86188fbd7 | Add Message if AvgKmL is null | sanarujung/tdd-carfuel,sanarujung/tdd-carfuel,sanarujung/tdd-carfuel | CarFuel/Views/Car/Details.cshtml | CarFuel/Views/Car/Details.cshtml | @using CarFuel.Models
@model Car
<h2>@Model.Make (@Model.Model)</h2>
<div class="well well-sm">
@if (Model.AverageKmL == null)
{
<div>
Not has enough data to calculate consumption rate.
Please add more fill up.
</div>
}
Average consumption is <strong>@(Model.AverageKmL?.ToString("n2"))</strong> km/L
</div> | @using CarFuel.Models
@model Car
<h2>@Model.Make (@Model.Model)</h2>
<div class="well well-sm">
Average consumption is <strong>@(Model.AverageKmL?.ToString("n2"))</strong> km/L
</div> | mit | C# |
8b3ca3afed29ad5218ef0eddfcfd3c2ef487886e | 생성된 콘텐츠가 Pressed 일 경우 활성화/비활성화 하지 않도록 수정. | WontakKim/DynamicScroll | Assets/DynamicScroll/Scripts/UIScrollBlinker.cs | Assets/DynamicScroll/Scripts/UIScrollBlinker.cs | using UnityEngine;
using System.Collections;
public class UIScrollBlinker : MonoBehaviour
{
public UIScrollView scrollView;
private bool firstTime = true;
void Start()
{
if (scrollView == null)
scrollView = NGUITools.FindInParents<UIScrollView>(gameObject);
if (scrollView != null)
{
if (scrollView.horizontalScrollBar != null)
EventDelegate.Add(scrollView.horizontalScrollBar.onChange, Blink);
if (scrollView.verticalScrollBar != null)
EventDelegate.Add(scrollView.verticalScrollBar.onChange, Blink);
}
Blink();
firstTime = false;
}
void Update()
{
SpringPanel sp = scrollView.gameObject.GetComponent<SpringPanel>();
if ((sp != null && sp.enabled == true) || scrollView.currentMomentum.magnitude > 0f)
Blink();
}
void OnEnable()
{
if (firstTime == false)
Blink();
}
public void Blink()
{
if (scrollView.panel == null)
return;
Vector3[] corners = scrollView.panel.worldCorners;
for (int i=0; i<4; i++)
{
Vector3 v = corners[i];
v = transform.InverseTransformPoint(v);
corners[i] = v;
}
Vector3 center = Vector3.Lerp(corners[0], corners[2], 0.5f);
for (int i=0; i<transform.childCount; i++)
{
Transform t = transform.GetChild(i);
if (UICamera.IsPressed(t.gameObject) == true)
continue;
Bounds b = NGUIMath.CalculateRelativeWidgetBounds(t, true);
float minX = corners[0].x - b.extents.x;
float minY = corners[0].y - b.extents.y;
float maxX = corners[2].x + b.extents.x;
float maxY = corners[2].y + b.extents.y;
float distanceX = t.localPosition.x - center.x + scrollView.panel.clipOffset.x - transform.localPosition.x;
float distanceY = t.localPosition.y - center.y + scrollView.panel.clipOffset.y - transform.localPosition.y;
bool active = (distanceX > minX && distanceX < maxX) && (distanceY > minY && distanceY < maxY);
NGUITools.SetActive(t.gameObject, active, false);
}
}
}
| using UnityEngine;
using System.Collections;
public class UIScrollBlinker : MonoBehaviour
{
public UIScrollView scrollView;
private bool firstTime = true;
void Start()
{
if (scrollView == null)
scrollView = NGUITools.FindInParents<UIScrollView>(gameObject);
if (scrollView != null)
{
if (scrollView.horizontalScrollBar != null)
EventDelegate.Add(scrollView.horizontalScrollBar.onChange, Blink);
if (scrollView.verticalScrollBar != null)
EventDelegate.Add(scrollView.verticalScrollBar.onChange, Blink);
}
Blink();
firstTime = false;
}
void Update()
{
SpringPanel sp = scrollView.gameObject.GetComponent<SpringPanel>();
if ((sp != null && sp.enabled == true) || scrollView.currentMomentum.magnitude > 0f)
Blink();
}
void OnEnable()
{
if (firstTime == false)
Blink();
}
public void Blink()
{
if (scrollView.panel == null)
return;
Vector3[] corners = scrollView.panel.worldCorners;
for (int i=0; i<4; i++)
{
Vector3 v = corners[i];
v = transform.InverseTransformPoint(v);
corners[i] = v;
}
Vector3 center = Vector3.Lerp(corners[0], corners[2], 0.5f);
for (int i=0; i<transform.childCount; i++)
{
Transform t = transform.GetChild(i);
Bounds b = NGUIMath.CalculateRelativeWidgetBounds(t, true);
float minX = corners[0].x - b.extents.x;
float minY = corners[0].y - b.extents.y;
float maxX = corners[2].x + b.extents.x;
float maxY = corners[2].y + b.extents.y;
float distanceX = t.localPosition.x - center.x + scrollView.panel.clipOffset.x - transform.localPosition.x;
float distanceY = t.localPosition.y - center.y + scrollView.panel.clipOffset.y - transform.localPosition.y;
bool active = (distanceX > minX && distanceX < maxX) && (distanceY > minY && distanceY < maxY);
NGUITools.SetActive(t.gameObject, active, false);
}
}
}
| mit | C# |
159e645546856a7ce88bb5b92586ea53a0e9db83 | add GetApproximateMessageCount to IMessageQueue<> | halforbit/data-stores | Halforbit.DataStores/Interface/IMessageQueue.cs | Halforbit.DataStores/Interface/IMessageQueue.cs | using Halforbit.DataStores.Model;
namespace Halforbit.DataStores.Interface
{
public interface IMessageQueue<TContent>
{
Message<TContent> Get();
Message<TContent> Put(TContent content);
void Delete(Message<TContent> message);
int? GetApproximateMessageCount();
}
}
| using Halforbit.DataStores.Model;
namespace Halforbit.DataStores.Interface
{
public interface IMessageQueue<TContent>
{
Message<TContent> Get();
Message<TContent> Put(TContent content);
void Delete(Message<TContent> message);
}
}
| mit | C# |
a83af69fb1d41322b02a4c883d9ccc981c99fa81 | Add logic for creating a pantru for new users | AlinCiocan/PlanEatSave,AlinCiocan/PlanEatSave,AlinCiocan/FoodPlanApp,AlinCiocan/PlanEatSave,AlinCiocan/FoodPlanApp,AlinCiocan/FoodPlanApp | DataAccessLayer/PantryService.cs | DataAccessLayer/PantryService.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PlanEatSave.Models;
using PlanEatSave.Utils;
namespace PlanEatSave.DataAceessLayer
{
public class PantryService
{
private ApplicationDbContext _context;
private IPlanEatSaveLogger _logger;
public PantryService(ApplicationDbContext context, IPlanEatSaveLogger logger)
{
_context = context;
_logger = logger;
}
public async Task<Pantry> GetPantryByUserIdAsync(string userId)
{
var pantryFromDb = await _context.Pantries
.Where(pantry => pantry.UserId == userId)
.Include(pantry => pantry.PantryItems).FirstOrDefaultAsync();
if (pantryFromDb != null)
{
return pantryFromDb;
}
var newPantry = new Pantry
{
UserId = userId
};
_context.Pantries.Add(newPantry);
await _context.SaveChangesAsync();
return newPantry;
}
public async Task<bool> AddItem(string userId, PantryItem item)
{
var pantryDb = await _context.Pantries.Where(pantry => pantry.Id == item.PantryId).FirstOrDefaultAsync();
if (pantryDb == null || pantryDb.UserId != userId)
{
return false;
}
_context.PantryItems.Add(item);
await _context.SaveChangesAsync();
return true;
}
}
} | using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PlanEatSave.Models;
using PlanEatSave.Utils;
namespace PlanEatSave.DataAceessLayer
{
public class PantryService
{
private ApplicationDbContext _context;
private IPlanEatSaveLogger _logger;
public PantryService(ApplicationDbContext context, IPlanEatSaveLogger logger)
{
_context = context;
_logger = logger;
}
public async Task<Pantry> GetPantryByUserIdAsync(string userId)
{
return await _context.Pantries
.Where(pantry => pantry.UserId == userId)
.Include(pantry => pantry.PantryItems).FirstOrDefaultAsync();
}
public async Task<bool> AddItem(string userId, PantryItem item)
{
var pantryDb = await _context.Pantries.Where(pantry => pantry.Id == item.PantryId).FirstOrDefaultAsync();
if (pantryDb == null || pantryDb.UserId != userId)
{
return false;
}
_context.PantryItems.Add(item);
await _context.SaveChangesAsync();
return true;
}
}
} | mit | C# |
40f46443515cacb332327a7f9fc2b3eff4b32c81 | Change SpritePart to be reference type since it's too big | k-t/SharpHaven | MonoHaven.Client/Graphics/Sprites/SpritePart.cs | MonoHaven.Client/Graphics/Sprites/SpritePart.cs | using System.Drawing;
namespace MonoHaven.Graphics.Sprites
{
public class SpritePart
{
private readonly int id;
private readonly TextureSlice tex;
private readonly Point offset;
private readonly Size size;
private readonly int z;
private readonly int subz;
public SpritePart(int id, TextureSlice tex, Point offset, Size size, int z, int subz)
{
this.id = id;
this.tex = tex;
this.offset = offset;
this.size = size;
this.z = z;
this.subz = subz;
}
public int Id
{
get { return id; }
}
public TextureSlice Tex
{
get { return tex; }
}
public Point Offset
{
get { return offset; }
}
public Size Size
{
get { return size; }
}
public int Width
{
get { return size.Width; }
}
public int Height
{
get { return size.Height; }
}
public int Z
{
get { return z; }
}
public int SubZ
{
get { return subz; }
}
public void Draw(SpriteBatch batch, int x, int y)
{
Tex.Draw(batch,
x + Offset.X,
y + Offset.Y,
Width,
Height);
}
}
}
| using System.Drawing;
namespace MonoHaven.Graphics.Sprites
{
public struct SpritePart
{
private readonly int id;
private readonly TextureSlice tex;
private readonly Point offset;
private readonly Size size;
private readonly int z;
private readonly int subz;
public SpritePart(int id, TextureSlice tex, Point offset, Size size, int z, int subz)
{
this.id = id;
this.tex = tex;
this.offset = offset;
this.size = size;
this.z = z;
this.subz = subz;
}
public int Id
{
get { return id; }
}
public TextureSlice Tex
{
get { return tex; }
}
public Point Offset
{
get { return offset; }
}
public Size Size
{
get { return size; }
}
public int Width
{
get { return size.Width; }
}
public int Height
{
get { return size.Height; }
}
public int Z
{
get { return z; }
}
public int SubZ
{
get { return subz; }
}
public void Draw(SpriteBatch batch, int x, int y)
{
Tex.Draw(batch,
x + Offset.X,
y + Offset.Y,
Width,
Height);
}
}
}
| mit | C# |
88ef95809cb9d86833aacc5a2b347f390b22b323 | change node service name | GusJassal/agri-nmp,GusJassal/agri-nmp,GusJassal/agri-nmp,GusJassal/agri-nmp | PDF/src/PDF.Server/Controllers/PDFController.cs | PDF/src/PDF.Server/Controllers/PDFController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using PDF.Models;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.NodeServices;
namespace PDF.Controllers
{
public class PDFRequest
{
public string html { get; set; }
}
public class JSONResponse
{
public string type;
public byte[] data;
}
[Route("api/[controller]")]
public class PDFController : Controller
{
private readonly IConfiguration Configuration;
private readonly DbAppContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
private string userId;
private string guid;
private string directory;
protected ILogger _logger;
public PDFController(IHttpContextAccessor httpContextAccessor, IConfigurationRoot configuration, ILoggerFactory loggerFactory)
{
Configuration = configuration;
_httpContextAccessor = httpContextAccessor;
userId = getFromHeaders("SM_UNIVERSALID");
guid = getFromHeaders("SMGOV_USERGUID");
directory = getFromHeaders("SM_AUTHDIRNAME");
_logger = loggerFactory.CreateLogger(typeof(PDFController));
}
private string getFromHeaders(string key)
{
string result = null;
if (Request.Headers.ContainsKey(key))
{
result = Request.Headers[key];
}
return result;
}
[HttpPost]
[Route("GetPDF")]
public async Task<IActionResult> GetPDF([FromServices] INodeServices nodeServices, [FromBody] PDFRequest rawdata )
{
JSONResponse result = null;
var options = new { format="letter", orientation= "landscape" };
// execute the Node.js component
result = await nodeServices.InvokeAsync<JSONResponse>("./pdf.js", rawdata.html, options);
return new FileContentResult(result.data, "application/pdf");
}
protected HttpRequest Request
{
get { return _httpContextAccessor.HttpContext.Request; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using PDF.Models;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.NodeServices;
namespace PDF.Controllers
{
public class PDFRequest
{
public string html { get; set; }
}
public class JSONResponse
{
public string type;
public byte[] data;
}
[Route("api/[controller]")]
public class PDFController : Controller
{
private readonly IConfiguration Configuration;
private readonly DbAppContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
private string userId;
private string guid;
private string directory;
protected ILogger _logger;
public PDFController(IHttpContextAccessor httpContextAccessor, IConfigurationRoot configuration, ILoggerFactory loggerFactory)
{
Configuration = configuration;
_httpContextAccessor = httpContextAccessor;
userId = getFromHeaders("SM_UNIVERSALID");
guid = getFromHeaders("SMGOV_USERGUID");
directory = getFromHeaders("SM_AUTHDIRNAME");
_logger = loggerFactory.CreateLogger(typeof(PDFController));
}
private string getFromHeaders(string key)
{
string result = null;
if (Request.Headers.ContainsKey(key))
{
result = Request.Headers[key];
}
return result;
}
[HttpPost]
[Route("GetPDF")]
public async Task<IActionResult> GetPDF([FromServices] INodeServices nodeServices, [FromBody] PDFRequest rawdata )
{
JSONResponse result = null;
var options = new { format="letter", orientation= "landscape" };
// execute the Node.js component
result = await nodeServices.InvokeAsync<JSONResponse>("./pdf", rawdata.html, options);
return new FileContentResult(result.data, "application/pdf");
}
protected HttpRequest Request
{
get { return _httpContextAccessor.HttpContext.Request; }
}
}
}
| apache-2.0 | C# |
9714888c599d1e66c32472b9a960546422337098 | test assembly info extractor | lAnubisl/byalexblog,lAnubisl/byalexblog,lAnubisl/byalexblog,lAnubisl/byalexblog,lAnubisl/byalexblog,lAnubisl/byalexblog | MvcApplication/Properties/AssemblyInfo.cs | MvcApplication/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("MvcApplication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MvcApplication")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4bbaf730-938f-4431-9e07-a964c7282eb1")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.2.1.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("MvcApplication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MvcApplication")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4bbaf730-938f-4431-9e07-a964c7282eb1")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
16c061f7a7c6974573b78a0f5c6cf030e23a8845 | Tweak visual | Simie/PrecisionEngineering | Src/PrecisionEngineering/UI/MeasurementLabel.cs | Src/PrecisionEngineering/UI/MeasurementLabel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ColossalFramework.UI;
using UnityEngine;
namespace PrecisionEngineering.UI
{
class MeasurementLabel : UILabel
{
public void SetValue(string v)
{
text = string.Format("<color=#87d3ff>{0}</color>", v);
}
public void SetWorldPosition(RenderManager.CameraInfo camera, Vector3 worldPos)
{
var uiView = GetUIView();
var vector3_1 = Camera.main.WorldToScreenPoint(worldPos) / uiView.inputScale;
var vector3_3 = uiView.ScreenPointToGUI(vector3_1) - new Vector2(size.x * 0.5f, size.y * 0.5f);// + new Vector2(vector3_2.x, vector3_2.y);
relativePosition = vector3_3;
}
public override void Start()
{
base.Start();
backgroundSprite = "CursorInfoBack";
autoSize = true;
padding = new RectOffset(5, 5, 5, 5);
textScale = 0.65f;
textAlignment = UIHorizontalAlignment.Center;
verticalAlignment = UIVerticalAlignment.Middle;
zOrder = 100;
pivot = UIPivotPoint.MiddleCenter;
color = new Color32(255, 255, 255, 190);
processMarkup = true;
isInteractive = false;
//<color #87d3ff>Construction cost: 520</color>
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ColossalFramework.UI;
using UnityEngine;
namespace PrecisionEngineering.UI
{
class MeasurementLabel : UILabel
{
public void SetValue(string v)
{
text = string.Format("<color=#87d3ff>{0}</color>", v);
}
public void SetWorldPosition(RenderManager.CameraInfo camera, Vector3 worldPos)
{
var uiView = GetUIView();
var vector3_1 = Camera.main.WorldToScreenPoint(worldPos) / uiView.inputScale;
var vector3_3 = uiView.ScreenPointToGUI(vector3_1) - new Vector2(size.x * 0.5f, size.y * 0.5f);// + new Vector2(vector3_2.x, vector3_2.y);
relativePosition = vector3_3;
}
public override void Start()
{
base.Start();
backgroundSprite = "CursorInfoBack";
autoSize = true;
padding = new RectOffset(5, 5, 5, 5);
textScale = 0.6f;
textAlignment = UIHorizontalAlignment.Center;
verticalAlignment = UIVerticalAlignment.Middle;
zOrder = 100;
pivot = UIPivotPoint.MiddleCenter;
color = new Color32(255, 255, 255, 180);
processMarkup = true;
isInteractive = false;
//<color #87d3ff>Construction cost: 520</color>
}
}
}
| mit | C# |
40b33afe452db138fdfdf850441ea7c6371b870f | Update test | mispy/JSIL,FUSEEProjectTeam/JSIL,dmirmilshteyn/JSIL,TukekeSoft/JSIL,sander-git/JSIL,FUSEEProjectTeam/JSIL,dmirmilshteyn/JSIL,sq/JSIL,Trattpingvin/JSIL,dmirmilshteyn/JSIL,TukekeSoft/JSIL,acourtney2015/JSIL,antiufo/JSIL,volkd/JSIL,Trattpingvin/JSIL,hach-que/JSIL,acourtney2015/JSIL,x335/JSIL,sq/JSIL,iskiselev/JSIL,hach-que/JSIL,sander-git/JSIL,FUSEEProjectTeam/JSIL,sq/JSIL,antiufo/JSIL,sander-git/JSIL,volkd/JSIL,iskiselev/JSIL,mispy/JSIL,iskiselev/JSIL,hach-que/JSIL,sander-git/JSIL,FUSEEProjectTeam/JSIL,iskiselev/JSIL,acourtney2015/JSIL,x335/JSIL,sq/JSIL,acourtney2015/JSIL,FUSEEProjectTeam/JSIL,dmirmilshteyn/JSIL,volkd/JSIL,iskiselev/JSIL,TukekeSoft/JSIL,hach-que/JSIL,volkd/JSIL,mispy/JSIL,sander-git/JSIL,TukekeSoft/JSIL,Trattpingvin/JSIL,mispy/JSIL,sq/JSIL,hach-que/JSIL,Trattpingvin/JSIL,acourtney2015/JSIL,antiufo/JSIL,x335/JSIL,volkd/JSIL,x335/JSIL,antiufo/JSIL | Tests/EmscriptenTestCases/PinnedStringBuffer.cs | Tests/EmscriptenTestCases/PinnedStringBuffer.cs | using System;
using System.Text;
using JSIL.Runtime;
using System.Runtime.InteropServices;
public static unsafe class Program {
[DllImport("common.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int WriteStringIntoBuffer (
byte * dest, int capacity
);
public static void Main () {
using (var na = new NativePackedArray<byte>(512)) {
int numBytes;
fixed (byte* pBuffer = na.Array)
numBytes = WriteStringIntoBuffer(pBuffer, na.Length);
var s = Encoding.ASCII.GetString(na, 0, numBytes);
Console.WriteLine("'{0}'", s);
}
}
} | using System;
using System.Text;
using JSIL.Runtime;
using System.Runtime.InteropServices;
public static unsafe class Program {
[DllImport("common.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int WriteStringIntoBuffer (
byte * dest, int capacity
);
public static void Main () {
using (var na = new NativePackedArray<byte>(512)) {
int numBytes;
fixed (byte* pBuffer = na.Array)
numBytes = WriteStringIntoBuffer(pBuffer, na.Size);
var s = Encoding.ASCII.GetString(na, 0, numBytes);
Console.WriteLine("'{0}'", s);
}
}
} | mit | C# |
deeac84b40bc7e533a93ffa46eb9bad745bea21f | fix encounter rate | poke-project/Unity-poke-project | PokeProject/Assets/Scripts/GameManager.cs | PokeProject/Assets/Scripts/GameManager.cs | using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
public static GameManager instance;
[HideInInspector]
public Game game;
[HideInInspector]
public PersistentData persistentData;
[HideInInspector]
public bool inMenu;
//[HideInInspector]
public bool inBagMenu;
public bool inPartyMenu;
[SerializeField]
public bool inFight;
[SerializeField]
private GameObject UIManager;
void Awake()
{
instance = this;
persistentData = GameObject.Find("PersistentData").GetComponent<PersistentData>();
inMenu = false;
inBagMenu = false;
inPartyMenu = false;
}
// Use this for initialization
void Start ()
{
game = Game.Instance;
inBagMenu = false;
inPartyMenu = false;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.M))
{
inMenu = !inMenu;
}
}
public void checkEncounter()
{
float rand = Random.Range(0f, 100f);
if (rand <= 0.66f)
{
print("Very rare");
}
else if (rand <= 2.436f)
{
print("Rare");
}
else if (rand <= 6.036f)
{
print("Semi-rare");
}
else if (rand <= 10.57f)
{
print("Common");
}
else if (rand <= 15.9f)
{
print("Very common");
}
}
}
| using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
public static GameManager instance;
[HideInInspector]
public Game game;
[HideInInspector]
public PersistentData persistentData;
[HideInInspector]
public bool inMenu;
//[HideInInspector]
public bool inBagMenu;
public bool inPartyMenu;
[SerializeField]
public bool inFight;
[SerializeField]
private GameObject UIManager;
void Awake()
{
instance = this;
persistentData = GameObject.Find("PersistentData").GetComponent<PersistentData>();
inMenu = false;
inBagMenu = false;
inPartyMenu = false;
}
// Use this for initialization
void Start ()
{
game = Game.Instance;
inBagMenu = false;
inPartyMenu = false;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.M))
{
inMenu = !inMenu;
}
}
public void checkEncounter()
{
// Should get type of area in parameters
int rand = Random.Range(1, 1880);
if (rand <= 100)
{
print("Very common");
}
else if (rand <= 185)
{
print("Common");
}
else if (rand <= 252)
{
print("Semi-rare");
}
else if (rand <= 285)
{
print("Rare");
}
else if (rand <= 297)
{
print("Very rare");
}
}
}
| unlicense | C# |
158e890d65ac5af7c04e869e62d504c0be09e662 | Implement UserFile.HashObject (and add ValidateData) | zr40/kyru-dotnet,zr40/kyru-dotnet | Kyru/Network/Objects/UserFile.cs | Kyru/Network/Objects/UserFile.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Kyru.Utilities;
using ProtoBuf;
namespace Kyru.Network.Objects
{
[ProtoContract]
internal class UserFile
{
[ProtoMember(1)] internal byte[] Signature;
[ProtoMember(2)] internal ulong FileId;
[ProtoMember(3)] internal byte[] EncryptedKey;
[ProtoMember(4)] internal byte[] FileIV;
[ProtoMember(5)] internal byte[] NameIV;
[ProtoMember(6)] internal byte[] EncryptedFileName;
[ProtoMember(7)] internal byte[] Hash; // Hash of encrypted file contents.
[ProtoMember(8)] internal List<KademliaId> ChunkList = new List<KademliaId>();
internal byte[] HashObject()
{
var bytes = new List<byte>();
bytes.AddRange(BitConverter.GetBytes(FileId));
bytes.AddRange(EncryptedKey);
bytes.AddRange(FileIV);
bytes.AddRange(NameIV);
bytes.AddRange(BitConverter.GetBytes(EncryptedFileName.Length));
bytes.AddRange(EncryptedFileName);
bytes.AddRange(BitConverter.GetBytes(ChunkList.Count));
foreach (var chunkId in ChunkList)
{
bytes.AddRange(chunkId.Bytes);
}
return Crypto.Hash(bytes.ToArray());
}
internal bool ValidateData()
{
if (EncryptedKey.Length != 32 || FileIV.Length != 16 || NameIV.Length != 16 | Hash.Length != 20)
return false;
return true;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using ProtoBuf;
namespace Kyru.Network.Objects
{
[ProtoContract]
internal class UserFile
{
[ProtoMember(1)] internal byte[] Signature;
[ProtoMember(2)] internal ulong FileId;
[ProtoMember(3)] internal byte[] EncryptedKey;
[ProtoMember(4)] internal byte[] FileIV;
[ProtoMember(5)] internal byte[] NameIV;
[ProtoMember(6)] internal byte[] EncryptedFileName;
[ProtoMember(7)] internal byte[] Hash; // Hash of encrypted file contents.
[ProtoMember(8)] internal List<KademliaId> ChunkList = new List<KademliaId>();
internal byte[] HashObject()
{
throw new NotImplementedException();
}
}
} | bsd-3-clause | C# |
b5e2b660f775cc283f0fb167829c1edb55c1ea11 | Add Image to clipboard data | ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET | ElectronNET.API/Entities/Data.cs | ElectronNET.API/Entities/Data.cs | namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
public class Data
{
/// <summary>
/// Gets or sets the text.
/// </summary>
/// <value>
/// The text.
/// </value>
public string Text { get; set; }
/// <summary>
/// Gets or sets the HTML.
/// </summary>
/// <value>
/// The HTML.
/// </value>
public string Html { get; set; }
/// <summary>
/// Gets or sets the RTF.
/// </summary>
/// <value>
/// The RTF.
/// </value>
public string Rtf { get; set; }
/// <summary>
/// The title of the url at text.
/// </summary>
public string Bookmark { get; set; }
public NativeImage? Image { get; set; }
}
}
| namespace ElectronNET.API.Entities
{
/// <summary>
///
/// </summary>
public class Data
{
/// <summary>
/// Gets or sets the text.
/// </summary>
/// <value>
/// The text.
/// </value>
public string Text { get; set; }
/// <summary>
/// Gets or sets the HTML.
/// </summary>
/// <value>
/// The HTML.
/// </value>
public string Html { get; set; }
/// <summary>
/// Gets or sets the RTF.
/// </summary>
/// <value>
/// The RTF.
/// </value>
public string Rtf { get; set; }
/// <summary>
/// The title of the url at text.
/// </summary>
public string Bookmark { get; set; }
}
} | mit | C# |
8ba929d6e616c66ac4a15ee3a8c6e49f0facc09a | add max length restriction | CVBDL/RALibraryServer | RaLibrary/Models/Book.cs | RaLibrary/Models/Book.cs | using System.ComponentModel.DataAnnotations;
namespace RaLibrary.Models
{
public class Book
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Code { get; set; }
[Required]
[MaxLength(200)]
public string Title { get; set; }
[MaxLength(50)]
public string Borrower { get; set; }
}
}
| using System.ComponentModel.DataAnnotations;
namespace RaLibrary.Models
{
public class Book
{
public int Id { get; set; }
[Required]
public string Code { get; set; }
[Required]
public string Title { get; set; }
public string Borrower { get; set; }
}
}
| mit | C# |
67f71e4dc6788de1955cc7e99ff7434290030341 | add accept header for organization permissions | thedillonb/octokit.net,TattsGroup/octokit.net,adamralph/octokit.net,alfhenrik/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shiftkey-tester/octokit.net,rlugojr/octokit.net,devkhan/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,SmithAndr/octokit.net,khellang/octokit.net,thedillonb/octokit.net,eriawan/octokit.net,Sarmad93/octokit.net,ivandrofly/octokit.net,editor-tools/octokit.net,shana/octokit.net,octokit/octokit.net,M-Zuber/octokit.net,Sarmad93/octokit.net,shiftkey/octokit.net,gdziadkiewicz/octokit.net,editor-tools/octokit.net,eriawan/octokit.net,SmithAndr/octokit.net,shiftkey-tester/octokit.net,khellang/octokit.net,dampir/octokit.net,dampir/octokit.net,shiftkey/octokit.net,octokit/octokit.net,ivandrofly/octokit.net,alfhenrik/octokit.net,rlugojr/octokit.net,devkhan/octokit.net,M-Zuber/octokit.net,shana/octokit.net,TattsGroup/octokit.net | Octokit/Helpers/AcceptHeaders.cs | Octokit/Helpers/AcceptHeaders.cs | namespace Octokit
{
public static class AcceptHeaders
{
public const string StableVersion = "application/vnd.github.v3";
public const string StableVersionHtml = "application/vnd.github.html";
public const string RedirectsPreviewThenStableVersionJson = "application/vnd.github.quicksilver-preview+json; charset=utf-8, application/vnd.github.v3+json; charset=utf-8";
public const string LicensesApiPreview = "application/vnd.github.drax-preview+json";
public const string ProtectedBranchesApiPreview = "application/vnd.github.loki-preview+json";
public const string StarCreationTimestamps = "application/vnd.github.v3.star+json";
public const string IssueLockingUnlockingApiPreview = "application/vnd.github.the-key-preview+json";
public const string CommitReferenceSha1Preview = "application/vnd.github.chitauri-preview+sha";
public const string SquashCommitPreview = "application/vnd.github.polaris-preview+json";
public const string MigrationsApiPreview = " application/vnd.github.wyandotte-preview+json";
public const string OrganizationPermissionsPreview = "application/vnd.github.ironman-preview+json";
}
}
| namespace Octokit
{
public static class AcceptHeaders
{
public const string StableVersion = "application/vnd.github.v3";
public const string StableVersionHtml = "application/vnd.github.html";
public const string RedirectsPreviewThenStableVersionJson = "application/vnd.github.quicksilver-preview+json; charset=utf-8, application/vnd.github.v3+json; charset=utf-8";
public const string LicensesApiPreview = "application/vnd.github.drax-preview+json";
public const string ProtectedBranchesApiPreview = "application/vnd.github.loki-preview+json";
public const string StarCreationTimestamps = "application/vnd.github.v3.star+json";
public const string IssueLockingUnlockingApiPreview = "application/vnd.github.the-key-preview+json";
public const string CommitReferenceSha1Preview = "application/vnd.github.chitauri-preview+sha";
public const string SquashCommitPreview = "application/vnd.github.polaris-preview+json";
public const string MigrationsApiPreview = " application/vnd.github.wyandotte-preview+json";
}
}
| mit | C# |
1c10669b29c036abaf1c15691902cb800fb2da02 | disable web optimizations | eugenpodaru/resume,eugenpodaru/resume,eugenpodaru/resume | Resume/App_Start/BundleConfig.cs | Resume/App_Start/BundleConfig.cs | namespace Resume
{
using System.Web.Optimization;
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
// javascript bundles
bundles.Add(new ScriptBundle("~/bundles/js")
.Include("~/Content/lib/jquery/dist/jquery.js")
.Include("~/Content/lib/jquery-easing/jquery.easing.js")
.Include("~/Content/lib/bootstrap/dist/js/bootstrap.js")
.Include("~/Content/Scripts/resume.js"));
//style sheet bundles
bundles.Add(new StyleBundle("~/Content/Styles/css")
.Include("~/Content/Styles/theme.css"));
#if DEBUG
// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = false;
#else
BundleTable.EnableOptimizations = false;
#endif
}
}
} | namespace Resume
{
using System.Web.Optimization;
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
// javascript bundles
bundles.Add(new ScriptBundle("~/bundles/js")
.Include("~/Content/lib/jquery/dist/jquery.js")
.Include("~/Content/lib/jquery-easing/jquery.easing.js")
.Include("~/Content/lib/bootstrap/dist/js/bootstrap.js")
.Include("~/Content/Scripts/resume.js"));
//style sheet bundles
bundles.Add(new StyleBundle("~/Content/Styles/css")
.Include("~/Content/Styles/theme.css"));
#if DEBUG
// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = false;
#else
BundleTable.EnableOptimizations = true;
#endif
}
}
} | mit | C# |
9ba66499781ac302b8b06f0ce8463871d082a195 | Update settings model | OrenTiger/my-personal-blog,OrenTiger/my-personal-blog | MyPersonalBlog/Models/Setting.cs | MyPersonalBlog/Models/Setting.cs | using System.ComponentModel.DataAnnotations;
namespace MyPersonalBlog.Models
{
public class Settings
{
public int Id { get; set; }
[Required]
[Range(1, 10, ErrorMessage = "Укажите значение от 1 до 10")]
[Display(Name = "Количество постов на страницу")]
public int PostListPageSize { get; set; }
[Required]
[Range(1, 50, ErrorMessage = "Укажите значение от 1 до 50")]
[Display(Name = "Количество записей в таблице на страницу")]
public int PageSize { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Укажите валидный email")]
[StringLength(254, ErrorMessage = "Превышена максимальная длина (254 символа)")]
[Display(Name = "E-mail администратора")]
public string AdminEmail { get; set; }
public string VkAppId { get; set; }
public string VkAppSecret { get; set; }
public string GoogleAppId { get; set; }
public string GoogleAppSecret { get; set; }
public string OAuthRedirectUri { get; set; }
}
} | using System.ComponentModel.DataAnnotations;
namespace MyPersonalBlog.Models
{
public class Settings
{
public int Id { get; set; }
[Required]
[Range(1, 10, ErrorMessage = "Укажите значение от 1 до 10")]
[Display(Name = "Количество постов на страницу")]
public int PostListPageSize { get; set; }
[Required]
[Range(1, 50, ErrorMessage = "Укажите значение от 1 до 50")]
[Display(Name = "Количество записей в таблице на страницу")]
public int PageSize { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Укажите валидный email")]
[StringLength(254, ErrorMessage = "Превышена максимальная длина (254 символа)")]
[Display(Name = "E-mail администратора")]
public string AdminEmail { get; set; }
[Required]
public string VkAppId { get; set; }
[Required]
public string VkAppSecret { get; set; }
[Required]
public string GoogleAppId { get; set; }
[Required]
public string GoogleAppSecret { get; set; }
[Required]
public string OAuthRedirectUri { get; set; }
}
} | mit | C# |
da439e99466c8e25ca16b2d588528b05c8dc95e0 | Update welcomemessages.cs | GTANetworkDev/ExampleResources,GTANetworkDev/ExampleResources,GTANetworkDev/ExampleResources,GTANetworkDev/ExampleResources | welcomemessages/welcomemessages.cs | welcomemessages/welcomemessages.cs | using System;
using System.Collections.Generic;
using GTANetworkServer;
using GTANetworkShared;
public class WelcomeMsgs : Script
{
public WelcomeMsgs()
{
API.onPlayerConnected += onPlayerConnect;
API.onPlayerDisconnected += onPlayerDisconnect;
}
public void onPlayerConnect(Client player)
{
API.sendNotificationToAll("~b~~h~" + player.name + "~h~ ~w~joined.");
API.sendChatMessageToAll("~b~~h~" + player.name + "~h~~w~ has joined the server.");
}
public void onPlayerDisconnect(Client player, string reason)
{
API.sendNotificationToAll("~b~~h~" + player.name + "~h~ ~w~quit.");
API.sendChatMessageToAll("~b~~h~" + player.name + "~h~~w~ has quit the server. (" + reason + ")");
}
}
| using System;
using System.Collections.Generic;
using GTANetworkServer;
using GTANetworkShared;
public class WelcomeMsgs : Script
{
public WelcomeMsgs()
{
API.onPlayerConnected += onPlayerConnect;
API.onPlayerDisconnected += onPlayerDisconnect;
}
public void onPlayerConnect(Client player)
{
API.sendNotificationToAll("~b~~h~" + player.name + "~h~ ~w~joined.");
API.sendChatMessageToAll("~b~~h~" + player.name + "~h~~w~ has joined the server.");
}
public void onPlayerDisconnect(Client player, string reason)
{
API.sendNotificationToAll("~b~~h~" + player.name + "~h~ ~w~quit.");
API.sendChatMessageToAll("~b~~h~" + player.name + "~h~~w~ has quit the server. (" + reason + ")");
}
}
| mit | C# |
11102034c66b636926c8c44e41684ea1843ea1eb | add test case | dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap | test/Cap.Consistency.Test/ConsistencyMessageManagerTest.cs | test/Cap.Consistency.Test/ConsistencyMessageManagerTest.cs | using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Microsoft.Extensions.Logging;
using Moq;
using System.Threading;
namespace Cap.Consistency.Test
{
public class ConsistencyMessageManagerTest
{
[Fact]
public void EnsureDefaultServicesDefaultsWithStoreWorks() {
var services = new ServiceCollection()
.AddTransient<IConsistencyMessageStore<TestConsistencyMessage>, NoopMessageStore>();
services.AddConsistency<TestConsistencyMessage>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddLogging();
var manager = services.BuildServiceProvider()
.GetRequiredService<ConsistencyMessageManager<TestConsistencyMessage>>();
Assert.NotNull(manager);
}
[Fact]
public void AddMessageManagerWithCustomerMannagerReturnsSameInstance() {
var services = new ServiceCollection()
.AddTransient<IConsistencyMessageStore<TestConsistencyMessage>, NoopMessageStore>()
.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddLogging();
services.AddConsistency<TestConsistencyMessage>()
.AddConsistencyMessageManager<CustomMessageManager>();
var provider = services.BuildServiceProvider();
Assert.Same(provider.GetRequiredService<ConsistencyMessageManager<TestConsistencyMessage>>(),
provider.GetRequiredService<CustomMessageManager>());
}
public class CustomMessageManager : ConsistencyMessageManager<TestConsistencyMessage>
{
public CustomMessageManager()
: base(new Mock<IConsistencyMessageStore<TestConsistencyMessage>>().Object, null, null) {
}
}
[Fact]
public async Task CreateCallsStore() {
var store = new Mock<IConsistencyMessageStore<TestConsistencyMessage>>();
var message = new TestConsistencyMessage { Time = DateTime.Now };
store.Setup(x => x.CreateAsync(message, CancellationToken.None)).ReturnsAsync(OperateResult.Success).Verifiable();
var messageManager = TestConsistencyMessageManager(store.Object);
var result = await messageManager.CreateAsync(message);
Assert.True(result.Succeeded);
store.VerifyAll();
}
public ConsistencyMessageManager<TMessage> TestConsistencyMessageManager<TMessage>(IConsistencyMessageStore<TMessage> store = null)
where TMessage : class {
store = store ?? new Mock<IConsistencyMessageStore<TMessage>>().Object;
var mockLogger = new Mock<ILogger<ConsistencyMessageManager<TMessage>>>().Object;
var manager = new ConsistencyMessageManager<TMessage>(store, null, mockLogger);
return manager;
}
}
}
| using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Microsoft.Extensions.Logging;
using Moq;
namespace Cap.Consistency.Test
{
public class ConsistencyMessageManagerTest
{
[Fact]
public void EnsureDefaultServicesDefaultsWithStoreWorks() {
var services = new ServiceCollection()
.AddTransient<IConsistencyMessageStore<TestConsistencyMessage>, NoopMessageStore>();
services.AddConsistency<TestConsistencyMessage>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddLogging();
var manager = services.BuildServiceProvider()
.GetRequiredService<ConsistencyMessageManager<TestConsistencyMessage>>();
Assert.NotNull(manager);
}
[Fact]
public void AddMessageManagerWithCustomerMannagerReturnsSameInstance() {
var services = new ServiceCollection()
.AddTransient<IConsistencyMessageStore<TestConsistencyMessage>, NoopMessageStore>()
.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddLogging();
services.AddConsistency<TestConsistencyMessage>()
.AddConsistencyMessageManager<CustomMessageManager>();
var provider = services.BuildServiceProvider();
Assert.Same(provider.GetRequiredService<ConsistencyMessageManager<TestConsistencyMessage>>(),
provider.GetRequiredService<CustomMessageManager>());
}
public class CustomMessageManager : ConsistencyMessageManager<TestConsistencyMessage>
{
public CustomMessageManager()
: base(new Mock<IConsistencyMessageStore<TestConsistencyMessage>>().Object, null, null) {
}
}
}
}
| mit | C# |
86488372ff283cfec28584d533390548496ea3f1 | Move the Recenter and Monoscoping Rendering feature to the Oculus Head Controller | xfleckx/BeMoBI,xfleckx/BeMoBI | Assets/Editor/VRSubjectInspector.cs | Assets/Editor/VRSubjectInspector.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(VRSubjectController))]
public class VRSubjectInspector : Editor
{
VRSubjectController instance;
public override void OnInspectorGUI()
{
instance = target as VRSubjectController;
base.OnInspectorGUI();
GUILayout.BeginVertical();
var availableBodyController = instance.GetComponents<IBodyMovementController>();
var availableHeadController = instance.GetComponents<IHeadMovementController>();
EditorGUILayout.LabelField("Available Head Controller");
if (!availableHeadController.Any())
EditorGUILayout.HelpBox("No Head Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info);
foreach (var headController in availableHeadController)
{
if (GUILayout.Button(headController.Identifier))
{
instance.ChangeHeadController(headController);
}
}
EditorGUILayout.LabelField("Available Body Controller");
if (!availableBodyController.Any())
EditorGUILayout.HelpBox("No Body Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info);
foreach (var bodyController in availableBodyController)
{
if(GUILayout.Button(bodyController.Identifier))
instance.ChangeBodyController(bodyController);
}
EditorGUILayout.Space();
if (GUILayout.Button("Reset Controller"))
{
instance.ResetController();
}
GUILayout.EndVertical();
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(VRSubjectController))]
public class VRSubjectInspector : Editor
{
VRSubjectController instance;
public override void OnInspectorGUI()
{
instance = target as VRSubjectController;
base.OnInspectorGUI();
GUILayout.BeginVertical();
var availableBodyController = instance.GetComponents<IBodyMovementController>();
var availableHeadController = instance.GetComponents<IHeadMovementController>();
EditorGUILayout.LabelField("Available Head Controller");
if (!availableHeadController.Any())
EditorGUILayout.HelpBox("No Head Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info);
foreach (var headController in availableHeadController)
{
if (GUILayout.Button(headController.Identifier))
{
instance.ChangeHeadController(headController);
}
}
EditorGUILayout.LabelField("Available Body Controller");
if (!availableBodyController.Any())
EditorGUILayout.HelpBox("No Body Controller Implementations found! \n Attache them to this GameObject!", MessageType.Info);
foreach (var bodyController in availableBodyController)
{
if(GUILayout.Button(bodyController.Identifier))
instance.ChangeBodyController(bodyController);
}
EditorGUILayout.Space();
if (GUILayout.Button("Reset Controller"))
{
instance.ResetController();
}
GUILayout.EndVertical();
instance.UseMonoscopigRendering = EditorGUILayout.Toggle("Monoscopic Rendering", instance.UseMonoscopigRendering);
if (instance.UseMonoscopigRendering)
instance.SetMonoscopic(instance.UseMonoscopigRendering);
}
} | mit | C# |
85d5160782acd1ff6683b744c4b96f0ef7f50598 | Add plugin identifier to the object itself | chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck | Plugins/PluginScriptGenerator.cs | Plugins/PluginScriptGenerator.cs | using System.Text;
namespace TweetDck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
StringBuilder build = new StringBuilder(2*pluginIdentifier.Length+pluginContents.Length+165);
build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");
build.Append("let tmp={");
build.Append("id:\"").Append(pluginIdentifier).Append("\",");
build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
build.Append("};");
build.Append("tmp.obj.$id=\"").Append(pluginIdentifier).Append("\";");
build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
build.Append("window.TD_PLUGINS.install(tmp);");
build.Append("})(").Append(environment.GetScriptVariables()).Append(");");
return build.ToString();
}
}
}
| using System.Text;
namespace TweetDck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"", config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150);
build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");
build.Append("let tmp={");
build.Append("id:\"").Append(pluginIdentifier).Append("\",");
build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
build.Append("};");
build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
build.Append("window.TD_PLUGINS.install(tmp);");
build.Append("})(").Append(environment.GetScriptVariables()).Append(");");
return build.ToString();
}
}
}
| mit | C# |
08a10b6231218870754f3e9c7b77fe246c004ce1 | Remove explicit private set from BulletTexture (#5) | ForNeVeR/TankDriver | TankDriver.App/TextureStorage.cs | TankDriver.App/TextureStorage.cs | using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace TankDriver
{
/// <summary>
/// Class for storeing loaded textures.
/// </summary>
internal class TextureStorage
{
/// <summary>
/// Tank body texture.
/// </summary>
public Texture2D TankBodyTexture { get; private set; }
/// <summary>
/// Tank turret texture.
/// </summary>
public Texture2D TankTurretTexture { get; private set; }
/// <summary>
/// Bullet texture
/// </summary>
/// <value>The bullet texture.</value>
public Texture2D BulletTexture { get; }
/// <summary>
/// Texture storage constructor. Loads textures from <see cref="contentManager"/>.
/// </summary>
/// <param name="contentManager">Object from which textures will be loaded.</param>
public TextureStorage(ContentManager contentManager)
{
TankBodyTexture = contentManager.Load<Texture2D>("Tank/Body");
TankTurretTexture = contentManager.Load<Texture2D>("Tank/Turret");
BulletTexture = contentManager.Load<Texture2D> ("Bullet/Bullet");
}
}
}
| using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace TankDriver
{
/// <summary>
/// Class for storeing loaded textures.
/// </summary>
internal class TextureStorage
{
/// <summary>
/// Tank body texture.
/// </summary>
public Texture2D TankBodyTexture { get; private set; }
/// <summary>
/// Tank turret texture.
/// </summary>
public Texture2D TankTurretTexture { get; private set; }
/// <summary>
/// Bullet texture
/// </summary>
/// <value>The bullet texture.</value>
public Texture2D BulletTexture { get; private set; }
/// <summary>
/// Texture storage constructor. Loads textures from <see cref="contentManager"/>.
/// </summary>
/// <param name="contentManager">Object from which textures will be loaded.</param>
public TextureStorage(ContentManager contentManager)
{
TankBodyTexture = contentManager.Load<Texture2D>("Tank/Body");
TankTurretTexture = contentManager.Load<Texture2D>("Tank/Turret");
BulletTexture = contentManager.Load<Texture2D> ("Bullet/Bullet");
}
}
}
| mit | C# |
824a4c7a98289aedd3474893ab17d0566988229d | Remove signupbox id from register bx since then it can be hidden by the zk.showLoginBox function | erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner | Zk/Views/Account/Register.cshtml | Zk/Views/Account/Register.cshtml | @{
ViewBag.Title = "Registreer je vandaag bij de Oogstplanner";
}
<div class="flowtype-area">
<!-- START RESPONSIVE RECTANGLE LAYOUT -->
<!-- Top bar -->
<div id="top">
</div>
<!-- Fixed main screen -->
<div id="login" class="bg imglogin">
<div class="row">
<div class="mainbox col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Registreer je vandaag bij de Oogstplanner</div>
<div class="panel-side-link">
<a id="signin-link" href="#">Inloggen</a>
</div>
</div>
<div class="panel-body">
@{ Html.RenderPartial("_RegisterForm"); }
</div><!-- End panel body -->
</div><!-- End panel -->
</div><!-- End signup box -->
</div><!-- End row -->
</div><!-- End main login div -->
<!-- END RESPONSIVE RECTANGLES LAYOUT -->
</div><!-- End flowtype-area --> | @{
ViewBag.Title = "Registreer je vandaag bij de Oogstplanner";
}
<div class="flowtype-area">
<!-- START RESPONSIVE RECTANGLE LAYOUT -->
<!-- Top bar -->
<div id="top">
<h1>Registreer je vandaag bij de Oogstplanner</h1>
</div>
<!-- Fixed main screen -->
<div id="login" class="bg imglogin">
<!-- Signup box inspired by http://bootsnipp.com/snippets/featured/login-amp-signup-forms-in-panel -->
<div id="signupbox" class="mainbox span12">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-side-link">
<a id="signin-link form-text" href="Login">Inloggen</a>
</div>
</div>
<div class="panel-body">
@{ Html.RenderPartial("_RegisterForm"); }
</div><!-- End panel body -->
</div><!-- End panel -->
</div><!-- End signup box -->
</div><!-- End main login div -->
<!-- END RESPONSIVE RECTANGLES LAYOUT -->
</div><!-- End flowtype-area --> | mit | C# |
8f8aff201fa934ec0083046267de3f623aac7886 | Change unity scene type to struct | insthync/LiteNetLibManager,insthync/LiteNetLibManager | Scripts/Utils/LiteNetLibScene.cs | Scripts/Utils/LiteNetLibScene.cs | using UnityEngine;
namespace LiteNetLibManager
{
[System.Serializable]
public struct LiteNetLibScene
{
[SerializeField]
private Object sceneAsset;
[SerializeField]
private string sceneName;
public string SceneName
{
get { return sceneName; }
set { sceneName = value; }
}
public static implicit operator string(LiteNetLibScene unityScene)
{
return unityScene.SceneName;
}
public bool IsSet()
{
return !string.IsNullOrEmpty(sceneName);
}
}
}
| using UnityEngine;
namespace LiteNetLibManager
{
[System.Serializable]
public class LiteNetLibScene
{
[SerializeField]
private Object sceneAsset;
[SerializeField]
private string sceneName = string.Empty;
public string SceneName
{
get { return sceneName; }
set { sceneName = value; }
}
public static implicit operator string(LiteNetLibScene unityScene)
{
return unityScene.SceneName;
}
public bool IsSet()
{
return !string.IsNullOrEmpty(sceneName);
}
}
}
| mit | C# |
fa3d5c57a76aa1c01100686bffc7c7fcf1baf460 | Move WinApi call into NativeMethods | CindyB/sloth | Sloth/Sloth/Core/WinUtilities.cs | Sloth/Sloth/Core/WinUtilities.cs | using Sloth.Interfaces.Core;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace Sloth.Core
{
public class WinUtilities : IWinUtilities
{
private List<IntPtr> m_ChildHandles;
public IntPtr FindControlHandle(IntPtr windowsHandle, string controlName)
{
m_ChildHandles = new List<IntPtr>();
NativeMethods.EnumChildWindows(windowsHandle, EnumChildProc, 0);
foreach (IntPtr childHandle in m_ChildHandles) if (Control.FromHandle(childHandle)?.Name == controlName) return childHandle;
return IntPtr.Zero;
}
public IntPtr FindWindowsHandle(string className,string windowsName)
{
return NativeMethods.FindWindow(className, windowsName);
}
public string GetWindowText(IntPtr windowsHandle)
{
StringBuilder builder = new StringBuilder(256);
NativeMethods.GetWindowText(windowsHandle, builder, builder.Capacity);
return builder.ToString();
}
public void SendMessage(IntPtr windowsHandle, IntPtr controlHandle, ISlothEvent slothEvent)
{
NativeMethods.SendMessage(controlHandle, slothEvent.Message,IntPtr.Zero,IntPtr.Zero);
}
public delegate bool EnumChildCallback(IntPtr hwnd, ref IntPtr lParam);
public bool EnumChildProc(IntPtr hwndChild, ref IntPtr lParam)
{
m_ChildHandles.Add(hwndChild);
return true;
}
internal static class NativeMethods
{
[DllImport("user32.dll")]
internal static extern int EnumChildWindows(IntPtr hwnd, EnumChildCallback Proc, int lParam);
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
internal static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);
}
}
}
| using Sloth.Interfaces.Core;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace Sloth.Core
{
public class WinUtilities : IWinUtilities
{
private List<IntPtr> m_ChildHandles;
public IntPtr FindControlHandle(IntPtr windowsHandle, string controlName)
{
m_ChildHandles = new List<IntPtr>();
EnumChildWindows(windowsHandle, EnumChildProc, 0);
foreach (IntPtr childHandle in m_ChildHandles) if (Control.FromHandle(childHandle)?.Name == controlName) return childHandle;
return IntPtr.Zero;
}
public IntPtr FindWindowsHandle(string className,string windowsName)
{
return FindWindow(className, windowsName);
}
public string GetWindowText(IntPtr windowsHandle)
{
StringBuilder builder = new StringBuilder(256);
GetWindowText(windowsHandle, builder, builder.Capacity);
return builder.ToString();
}
public void SendMessage(IntPtr windowsHandle, IntPtr controlHandle, ISlothEvent slothEvent)
{
SendMessage(controlHandle, slothEvent.Message,IntPtr.Zero,IntPtr.Zero);
}
public delegate bool EnumChildCallback(IntPtr hwnd, ref IntPtr lParam);
public bool EnumChildProc(IntPtr hwndChild, ref IntPtr lParam)
{
m_ChildHandles.Add(hwndChild);
return true;
}
[DllImport("user32.dll")]
public static extern int EnumChildWindows(IntPtr hwnd, EnumChildCallback Proc, int lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);
}
}
| mit | C# |
0ebfa35381aca838fac68c7666b8e84c5784560e | increase threads count | LykkeCity/bitcoinservice,LykkeCity/bitcoinservice | src/ApiRunner/Program.cs | src/ApiRunner/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AzureRepositories;
using BitcoinApi;
using Core.Settings;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace ApiRunner
{
public class Program
{
public static void Main(string[] args)
{
var arguments = args.Select(t => t.Split('=')).ToDictionary(spl => spl[0].Trim('-'), spl => spl[1]);
Console.Clear();
Console.Title = "Bitcoin self-hosted API - Ver. " + Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion;
var builder = new WebHostBuilder()
.UseKestrel(o => o.ThreadCount = 4)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
if (arguments.ContainsKey("port"))
builder.UseUrls($"http://*:{arguments["port"]}");
Console.WriteLine($"Web Server is running");
Console.WriteLine("Utc time: " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
var host = builder.Build();
host.Run();
}
static void Exit()
{
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static BaseSettings GetSettings()
{
var settingsData = ReadSettingsFile();
if (string.IsNullOrWhiteSpace(settingsData))
{
Console.WriteLine("Please, provide generalsettings.json file");
return null;
}
var settings = JsonConvert.DeserializeObject<BaseSettings>(settingsData);
return settings;
}
static string ReadSettingsFile()
{
#if DEBUG
return File.ReadAllText(@"..\..\settings\settings.json");
#else
return File.ReadAllText("settings.json");
#endif
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AzureRepositories;
using BitcoinApi;
using Core.Settings;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace ApiRunner
{
public class Program
{
public static void Main(string[] args)
{
var arguments = args.Select(t => t.Split('=')).ToDictionary(spl => spl[0].Trim('-'), spl => spl[1]);
Console.Clear();
Console.Title = "Bitcoin self-hosted API - Ver. " + Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationVersion;
var builder = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
if (arguments.ContainsKey("port"))
builder.UseUrls($"http://*:{arguments["port"]}");
Console.WriteLine($"Web Server is running");
Console.WriteLine("Utc time: " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"));
var host = builder.Build();
host.Run();
}
static void Exit()
{
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static BaseSettings GetSettings()
{
var settingsData = ReadSettingsFile();
if (string.IsNullOrWhiteSpace(settingsData))
{
Console.WriteLine("Please, provide generalsettings.json file");
return null;
}
var settings = JsonConvert.DeserializeObject<BaseSettings>(settingsData);
return settings;
}
static string ReadSettingsFile()
{
#if DEBUG
return File.ReadAllText(@"..\..\settings\settings.json");
#else
return File.ReadAllText("settings.json");
#endif
}
}
}
| mit | C# |
37d159c8c3755902453c1c4a124a60609dbad892 | Make Names a IReadOnlyList<string> | jcmoyer/Yeena | Yeena/PathOfExile/PoEItemList.cs | Yeena/PathOfExile/PoEItemList.cs | // Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
/// <summary>
/// An item list is a list of items with a name that classifies their type,
/// i.e. Claw has Nailed Fist, Sharktooth Claw, etc...
/// </summary>
[JsonObject]
class PoEItemList : IReadOnlyList<string> {
[JsonProperty("name")]
private readonly string _name;
[JsonProperty("items")]
private readonly List<string> _names;
[JsonConstructor]
private PoEItemList() {
}
public PoEItemList(string name, IEnumerable<string> itemNames) {
_name = name;
_names = new List<string>(itemNames);
}
public IReadOnlyList<string> Names {
get { return _names; }
}
public IEnumerator<string> GetEnumerator() {
return Names.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public int Count {
get { return Names.Count; }
}
public string this[int index] {
get { return Names[index]; }
}
public override string ToString() {
return _name;
}
}
}
| // Copyright 2013 J.C. Moyer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
/// <summary>
/// An item list is a list of items with a name that classifies their type,
/// i.e. Claw has Nailed Fist, Sharktooth Claw, etc...
/// </summary>
[JsonObject]
class PoEItemList : IReadOnlyList<string> {
[JsonProperty("name")]
private readonly string _name;
[JsonProperty("items")]
private readonly List<string> _names;
[JsonConstructor]
private PoEItemList() {
}
public PoEItemList(string name, IEnumerable<string> itemNames) {
_name = name;
_names = new List<string>(itemNames);
}
public IReadOnlyCollection<string> Names {
get { return _names; }
}
public IEnumerator<string> GetEnumerator() {
return _names.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public int Count {
get { return _names.Count; }
}
public string this[int index] {
get { return _names[index]; }
}
public override string ToString() {
return _name;
}
}
}
| apache-2.0 | C# |
61a53a8ecc556f366f611e5cb46fb8bac5a98e17 | Use IReadOnlyList instead of IReadOnlyCollection for stash tab items | jcmoyer/Yeena | Yeena/PathOfExile/PoEStashTab.cs | Yeena/PathOfExile/PoEStashTab.cs | // Copyright 2013 J.C. Moyer
//
// 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.
#pragma warning disable 649
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
[JsonObject]
class PoEStashTab : IEnumerable<PoEItem> {
[JsonProperty("numTabs")] private readonly int _numTabs = 0;
[JsonProperty("items")] private readonly List<PoEItem> _items = new List<PoEItem>();
[JsonProperty("tabs")] private readonly List<PoEStashTabInfo> _tabInfo = new List<PoEStashTabInfo>();
[JsonProperty("error")] private readonly PoEStashRequestError _error;
private PoEStashTabInfo _assocInfo;
public int TabCount {
get { return _numTabs; }
}
public IReadOnlyList<PoEItem> Items {
get { return _items; }
}
public PoEStashTabInfo TabInfo {
get { return _assocInfo; }
}
public PoEStashRequestError Error {
get { return _error; }
}
public IEnumerator<PoEItem> GetEnumerator() {
return _items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context) {
// Something went wrong. The caller can handle this.
if (Error != null) return;
_assocInfo = _tabInfo[(int)context.Context];
}
}
}
| // Copyright 2013 J.C. Moyer
//
// 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.
#pragma warning disable 649
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Yeena.PathOfExile {
[JsonObject]
class PoEStashTab : IEnumerable<PoEItem> {
[JsonProperty("numTabs")] private readonly int _numTabs = 0;
[JsonProperty("items")] private readonly List<PoEItem> _items = new List<PoEItem>();
[JsonProperty("tabs")] private readonly List<PoEStashTabInfo> _tabInfo = new List<PoEStashTabInfo>();
[JsonProperty("error")] private readonly PoEStashRequestError _error;
private PoEStashTabInfo _assocInfo;
public int TabCount {
get { return _numTabs; }
}
public IReadOnlyCollection<PoEItem> Items {
get { return _items; }
}
public PoEStashTabInfo TabInfo {
get { return _assocInfo; }
}
public PoEStashRequestError Error {
get { return _error; }
}
public IEnumerator<PoEItem> GetEnumerator() {
return _items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context) {
// Something went wrong. The caller can handle this.
if (Error != null) return;
_assocInfo = _tabInfo[(int)context.Context];
}
}
}
| apache-2.0 | C# |
c67fc8cea0116015e9780a635712d59c319fa1fe | Add WriteLog method. | eternnoir/NLogging | src/NLogging/Logger.cs | src/NLogging/Logger.cs | namespace NLogging
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Logger : ILogger
{
private string loggerName;
private LogLevel logLevel;
private List<IHandler> handlerList;
public string Name
{
get
{
return this.loggerName;
}
}
/// <summary>
/// Log level property
/// </summary>
public LogLevel Level
{
get
{
return this.logLevel;
}
set
{
this.logLevel = value;
}
}
public Logger(string loggerName)
{
this.init(loggerName, LogLevel.NOTSET);
}
public Logger(string loggerName, LogLevel logLevel)
{
this.init(loggerName, logLevel);
}
private void init(string loggerName, LogLevel logLevel)
{
this.loggerName = loggerName;
this.logLevel = logLevel;
this.handlerList = new List<IHandler>();
}
public void AddHandler(IHandler handler)
{
if (handler != null)
{
this.handlerList.Add(handler);
}
}
public void WriteLog(LogLevel level, string message)
{
if (message == null)
{
//TODO change exception
throw new Exception("Message can not be null");
}
StackTrace stack = new System.Diagnostics.StackTrace(true);
string functionName = stack.GetFrame(1).GetMethod().Name;
Record record = new Record(this.loggerName, level, stack, message, functionName);
foreach (var handler in handlerList)
{
handler.push(record);
}
}
}
}
| namespace NLogging
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Logger : ILogger
{
private string loggerName;
private LogLevel logLevel;
private List<IHandler> handlerList;
public string Name
{
get
{
return this.loggerName;
}
}
/// <summary>
/// Log level property
/// </summary>
public LogLevel Level
{
get
{
return this.logLevel;
}
set
{
this.logLevel = value;
}
}
public Logger(string loggerName)
{
this.init(loggerName, LogLevel.NOTSET);
}
public Logger(string loggerName, LogLevel logLevel)
{
this.init(loggerName, logLevel);
}
private void init(string loggerName, LogLevel logLevel)
{
this.loggerName = loggerName;
this.logLevel = logLevel;
this.handlerList = new List<IHandler>();
}
public void AddHandler(IHandler handler)
{
if (handler != null)
{
this.handlerList.Add(handler);
}
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.