Datasets:
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
Error code: JobManagerExceededMaximumDurationError
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
code_text
string | repo_name
string | file_path
string | language
string | license
string | size
int32 |
---|---|---|---|---|---|
using System;
using System.Text;
namespace FileHelpers.Dynamic
{
/// <summary>
/// Helper classes for strings
/// </summary>
internal static class StringHelper
{
/// <summary>
/// replace the one string with another, and keep doing it
/// </summary>
/// <param name="original">Original string</param>
/// <param name="oldValue">Value to replace</param>
/// <param name="newValue">value to replace with</param>
/// <returns>String with all multiple occurrences replaced</returns>
private static string ReplaceRecursive(string original, string oldValue, string newValue)
{
const int maxTries = 1000;
string ante, res;
res = original.Replace(oldValue, newValue);
var i = 0;
do
{
i++;
ante = res;
res = ante.Replace(oldValue, newValue);
} while (ante != res ||
i > maxTries);
return res;
}
/// <summary>
/// convert a string into a valid identifier
/// </summary>
/// <param name="original">Original string</param>
/// <returns>valid identifier Original_string</returns>
internal static string ToValidIdentifier(string original)
{
if (original.Length == 0)
return string.Empty;
var res = new StringBuilder(original.Length + 1);
if (!char.IsLetter(original[0]) &&
original[0] != '_')
res.Append('_');
for (int i = 0; i < original.Length; i++)
{
char c = original[i];
if (char.IsLetterOrDigit(c) ||
c == '_')
res.Append(c);
else
res.Append('_');
}
var identifier = ReplaceRecursive(res.ToString(), "__", "_").Trim('_');
if (identifier.Length == 0)
return "_";
else if (char.IsDigit(identifier[0]))
identifier = "_" + identifier;
return identifier;
}
}
} | MarcosMeli/FileHelpers | FileHelpers/Dynamic/StringHelper.cs | C# | mit | 2,199 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ChallengeAccepted.Data.Contracts;
using ChallengeAccepted.Models;
namespace ChallengeAccepted.Api.Controllers
{
// [Authorize]
public class BaseController : ApiController
{
protected IChallengeAcceptedData data;
private User currentUser;
public BaseController(IChallengeAcceptedData data)
{
this.data = data;
//this.CurrentUser = this.data.Users.All().FirstOrDefault(u => u.UserName == this.User.Identity.Name);
}
protected User CurrentUser
{
get
{
if (this.currentUser == null)
{
this.currentUser = this.data.Users
.All()
.FirstOrDefault(x => x.UserName == this.User.Identity.Name);
}
return this.currentUser;
}
}
}
}
| NativeScriptHybrids/ChallengeAccepted | ChallengeAccepted.Service/ChallengeAccepted.Api/Controllers/BaseController.cs | C# | mit | 1,034 |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
namespace RedBadger.Xpf.Data
{
internal enum BindingResolutionMode
{
Immediate,
Deferred
}
}
| redbadger/XPF | XPF/RedBadger.Xpf/Data/BindingResolutionMode.cs | C# | mit | 1,329 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JsonHelper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JsonHelper")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("dc25dd33-dd16-4993-bf9f-45a1b685824f")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| fsjohnhuang/Kit.Net | BaseLibrary/JsonHelper/Properties/AssemblyInfo.cs | C# | mit | 1,304 |
using System;
using DotJEM.Json.Validation.Context;
using DotJEM.Json.Validation.Descriptive;
using DotJEM.Json.Validation.Results;
using Newtonsoft.Json.Linq;
namespace DotJEM.Json.Validation.Constraints
{
public sealed class NotJsonConstraint : JsonConstraint
{
public JsonConstraint Constraint { get; }
public NotJsonConstraint(JsonConstraint constraint)
{
Constraint = constraint;
}
public override JsonConstraint Optimize()
{
NotJsonConstraint not = Constraint as NotJsonConstraint;
return not != null ? not.Constraint : base.Optimize();
}
public override Result DoMatch(JToken token, IJsonValidationContext context)
=> !Constraint.DoMatch(token, context);
public override bool Matches(JToken token, IJsonValidationContext context)
=> !Constraint.Matches(token, context);
public override string ToString()
{
return $"not {Constraint}";
}
}
} | dotJEM/json-validation | DotJEM.Json.Validation/Constraints/NotJsonConstraint.cs | C# | mit | 1,034 |
// --------------------------------------------------------------------
// © Copyright 2013 Hewlett-Packard Development Company, L.P.
//--------------------------------------------------------------------
using HP.LR.Vugen.Common;
using HP.LR.VuGen.ServiceCore;
using HP.LR.VuGen.ServiceCore.Data.ProjectSystem;
using HP.LR.VuGen.ServiceCore.Interfaces;
using HP.Utt.ProjectSystem;
using HP.Utt.UttCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TransactionWriterAddin
{
public class AutostartCommand : UttBaseCommand
{
public override void Run()
{
VuGenServiceManager.RunWhenInitialized(InnerRun);
}
private void InnerRun()
{
IVuGenProjectService projectService = VuGenServiceManager.GetService<IVuGenProjectService>();
projectService.ScriptSaved += projectService_ScriptSaved;
projectService.ScriptSavedAs += projectService_ScriptSavedAs;
if (projectService is UttProjectService)
(projectService as UttProjectService).ScriptExported+=AutostartCommand_ScriptExported;
}
void projectService_ScriptSavedAs(object sender, SaveAsEventArgs e)
{
AddTransactionNames(e.Script as IVuGenScript);
}
void AutostartCommand_ScriptExported(object sender, ExportEventArgs e)
{
AddTransactionNames(e.Script as IVuGenScript,Path.Combine(e.PersistenceToken.LocalPath,e.PersistenceToken.LoadData));
}
void projectService_ScriptSaved(object sender, HP.Utt.ProjectSystem.SaveEventArgs e)
{
AddTransactionNames(e.Script as IVuGenScript);
}
private static void AddTransactionNames(IVuGenScript script, string usrFileName=null)
{
try
{
if (script == null) return;
List<IExtraFileScriptItem> extraFiles = script.GetExtraFiles();
IExtraFileScriptItem dynamicTransacrions = null;
foreach (IExtraFileScriptItem extraFile in extraFiles)
{
if (extraFile.FileName == "dynamic_transactions.txt") //This is not configurable. This is the file name!
{
dynamicTransacrions = extraFile;
break;
}
}
if (dynamicTransacrions == null) return;
string fileContent = File.ReadAllText(dynamicTransacrions.FullFileName);
string[] transactionNames = fileContent.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
IScriptDataObject scriptData = script.GenerateDataObject() as IScriptDataObject;
if (scriptData == null) return;
List<String> transactionsList = scriptData.SpecialSteps.Transactions;
transactionsList.AddRange(transactionNames);
IniUsrFile usr;
if (usrFileName != null)
{
usr = new IniUsrFile(usrFileName);
}
else
{
usr = new IniUsrFile(script.FileName);
}
usr.WriteTransactions(transactionsList);
usr.Save();
}
catch
{
//Don't want to have adverse influence on the regular usage of VuGen. If this fails it does so silently.
}
}
}
}
| HPSoftware/VuGenPowerPack | Experimental/TransactionWriterAddin/AutostartCommand.cs | C# | mit | 3,176 |
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using WebProject.Models;
namespace WebProject
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
}
| saifcoding/angular-apartments-project | WebProject_Server/WebProject/App_Start/IdentityConfig.cs | C# | mit | 1,784 |
// UrlRewriter - A .NET URL Rewriter module
// Version 2.0
//
// Copyright 2011 Intelligencia
// Copyright 2011 Seth Yates
//
using System;
namespace Intelligencia.UrlRewriter.Actions
{
/// <summary>
/// Action that sets properties in the context.
/// </summary>
public class SetPropertyAction : IRewriteAction
{
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="name">The name of the variable.</param>
/// <param name="value">The name of the value.</param>
public SetPropertyAction(string name, string value)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
_name = name;
_value = value;
}
/// <summary>
/// The name of the variable.
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// The value of the variable.
/// </summary>
public string Value
{
get { return _value; }
}
/// <summary>
/// Executes the action.
/// </summary>
/// <param name="context">The rewrite context.</param>
public RewriteProcessing Execute(IRewriteContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
context.Properties.Set(Name, context.Expand(Value));
return RewriteProcessing.ContinueProcessing;
}
private string _name;
private string _value;
}
}
| sethyates/urlrewriter | src/Actions/SetPropertyAction.cs | C# | mit | 1,857 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Linq;
namespace HTLib2
{
public static partial class LinAlg
{
static bool Eye_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr Eye(int size, double diagval=1)
{
if(Eye_SelfTest)
{
Eye_SelfTest = false;
MatrixByArr tT0 = new double[3, 3] { { 2, 0, 0 }, { 0, 2, 0 }, { 0, 0, 2 }, };
MatrixByArr tT1 = Eye(3, 2);
HDebug.AssertTolerance(double.Epsilon, tT0 - tT1);
}
MatrixByArr mat = new MatrixByArr(size,size);
for(int i=0; i<size; i++)
mat[i, i] = diagval;
return mat;
}
static bool Tr_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix Tr(this Matrix M)
{
if(Tr_SelfTest)
{
Tr_SelfTest = false;
Matrix tM0 = new double[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
Matrix tT0 = new double[3, 2] { { 1, 4 }, { 2, 5 }, { 3, 6 } };
Matrix tT1 = Tr(tM0);
HDebug.AssertToleranceMatrix(double.Epsilon, tT0 - tT1);
}
Matrix tr = Matrix.Zeros(M.RowSize, M.ColSize);
for(int c=0; c<tr.ColSize; c++)
for(int r=0; r<tr.RowSize; r++)
tr[c, r] = M[r, c];
return tr;
}
static bool Diagd_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr Diag(this Vector d)
{
if(Diagd_SelfTest)
{
Diagd_SelfTest = false;
MatrixByArr tD1 = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector td1 = new double[3] { 1, 2, 3 };
MatrixByArr tD = Diag(td1);
HDebug.AssertTolerance(double.Epsilon, tD - tD1);
}
int size = d.Size;
MatrixByArr D = new MatrixByArr(size, size);
for(int i=0; i < size; i++)
D[i, i] = d[i];
return D;
}
static bool DiagD_SelfTest = HDebug.IsDebuggerAttached;
public static Vector Diag(this Matrix D)
{
if(DiagD_SelfTest)
{
DiagD_SelfTest = false;
MatrixByArr tD1 = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector td1 = new double[3] { 1, 2, 3 };
Vector td = Diag(tD1);
HDebug.AssertTolerance(double.Epsilon, td - td1);
}
HDebug.Assert(D.ColSize == D.RowSize);
int size = D.ColSize;
Vector d = new double[size];
for(int i=0; i<size; i++)
d[i] = D[i,i];
return d;
}
static bool DV_SelfTest1 = HDebug.IsDebuggerAttached;
public static Vector DV(Matrix D, Vector V, bool assertDiag = true)
{
if(DV_SelfTest1)
{
DV_SelfTest1 = false;
MatrixByArr tD = new double[3, 3] { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
Vector tV = new double[3] { 1, 2, 3 };
Vector tDV = new double[3] { 1, 4, 9 };
// [1 0 0] [1] [1]
// [0 2 0] * [2] = [4]
// [0 0 3] [3] [9]
HDebug.AssertTolerance(double.Epsilon, DV(tD, tV) - tDV);
}
// D is the diagonal matrix
HDebug.Assert(D.ColSize == D.RowSize);
if(assertDiag) // check diagonal matrix
HDebug.AssertToleranceMatrix(double.Epsilon, D - Diag(Diag(D)));
HDebug.Assert(D.ColSize == V.Size);
Vector diagD = Diag(D);
Vector diagDV = DV(diagD, V);
return diagDV;
}
static bool DV_SelfTest2 = HDebug.IsDebuggerAttached;
public static Vector DV(Vector D, Vector V, bool assertDiag = true)
{
if(DV_SelfTest2)
{
DV_SelfTest2 = false;
Vector tD = new double[3] { 1, 2, 3 };
Vector tV = new double[3] { 1, 2, 3 };
Vector tDV = new double[3] { 1, 4, 9 };
// [1 0 0] [1] [1]
// [0 2 0] * [2] = [4]
// [0 0 3] [3] [9]
HDebug.AssertTolerance(double.Epsilon, DV(tD, tV) - tDV);
}
// D is the diagonal matrix
HDebug.Assert(D.Size == V.Size);
int size = V.Size;
Vector dv = new double[size];
for(int i=0; i < size; i++)
dv[i] = D[i] * V[i];
return dv;
}
static bool MD_SelfTest = HDebug.IsDebuggerAttached;
public static MatrixByArr MD(MatrixByArr M, Vector D)
{ // M * Diag(D)
if(MD_SelfTest)
{
MD_SelfTest = false;
MatrixByArr tM = new double[3, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 } };
Vector tD = new double[3] { 1, 2, 3 };
MatrixByArr tMD0 = new double[3, 3] { { 1, 4, 9 }
, { 4, 10, 18 }
, { 7, 16, 27 } };
MatrixByArr tMD1 = MD(tM, tD);
MatrixByArr dtMD = tMD0 - tMD1;
double maxAbsDtMD = dtMD.ToArray().HAbs().HMax();
Debug.Assert(maxAbsDtMD == 0);
}
HDebug.Assert(M.RowSize == D.Size);
MatrixByArr lMD = new double[M.ColSize, M.RowSize];
for(int c=0; c<lMD.ColSize; c++)
for(int r=0; r<lMD.RowSize; r++)
lMD[c, r] = M[c, r] * D[r];
return lMD;
}
static bool MV_SelfTest = HDebug.IsDebuggerAttached;
static bool MV_SelfTest_lmat_rvec = HDebug.IsDebuggerAttached;
public static Vector MV<MATRIX>(MATRIX lmat, Vector rvec, string options="")
where MATRIX : IMatrix<double>
{
Vector result = new Vector(lmat.ColSize);
MV(lmat, rvec, result, options);
if(MV_SelfTest_lmat_rvec)
{
MV_SelfTest_lmat_rvec = false;
HDebug.Assert(lmat.RowSize == rvec.Size);
Vector lresult = new Vector(lmat.ColSize);
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
lresult[c] += lmat[c, r] * rvec[r];
HDebug.AssertTolerance(double.Epsilon, lresult-result);
}
return result;
}
public static void MV<MATRIX>(MATRIX lmat, Vector rvec, Vector result, string options="")
where MATRIX : IMatrix<double>
{
if(MV_SelfTest)
{
MV_SelfTest = false;
MatrixByArr tM = new double[4, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 }
, { 10, 11, 12 } };
Vector tV = new double[3] { 1, 2, 3 };
Vector tMV0 = new double[4] { 14, 32, 50, 68 };
Vector tMV1 = MV(tM, tV);
double err = (tMV0 - tMV1).ToArray().HAbs().Max();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.RowSize == rvec.Size);
HDebug.Assert(lmat.ColSize == result.Size);
if(options.Split(';').Contains("parallel") == false)
{
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
result[c] += lmat[c, r] * rvec[r];
}
else
{
System.Threading.Tasks.Parallel.For(0, lmat.ColSize, delegate(int c)
{
for(int r=0; r<lmat.RowSize; r++)
result[c] += lmat[c, r] * rvec[r];
});
}
}
//static bool MtM_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix MtM(Matrix lmat, Matrix rmat)
{
bool MtM_SelfTest = false;//HDebug.IsDebuggerAttached;
if(MtM_SelfTest)
{
MtM_SelfTest = false;
/// >> A=[ 1,5 ; 2,6 ; 3,7 ; 4,8 ];
/// >> B=[ 1,2,3 ; 3,4,5 ; 5,6,7 ; 7,8,9 ];
/// >> A'*B
/// ans =
/// 50 60 70
/// 114 140 166
Matrix _A = new double[4, 2] {{ 1,5 },{ 2,6 },{ 3,7 },{ 4,8 }};
Matrix _B = new double[4, 3] {{ 1,2,3 },{ 3,4,5 },{ 5,6,7 },{ 7,8,9 }};
Matrix _AtB = MtM(_A, _B);
Matrix _AtB_sol = new double[2,3]
{ { 50, 60, 70 }
, { 114, 140, 166 } };
double err = (_AtB - _AtB_sol).HAbsMax();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.ColSize == rmat.ColSize);
int size1 = lmat.RowSize;
int size2 = rmat.ColSize;
int size3 = rmat.RowSize;
Matrix result = Matrix.Zeros(size1, size3);
for(int c=0; c<size1; c++)
for(int r=0; r<size3; r++)
{
double sum = 0;
for(int i=0; i<size2; i++)
// tr(lmat[c,i]) * rmat[i,r] => lmat[i,c] * rmat[i,r]
sum += lmat[i,c] * rmat[i,r];
result[c, r] = sum;
}
return result;
}
//static bool MMt_SelfTest = HDebug.IsDebuggerAttached;
public static Matrix MMt(Matrix lmat, Matrix rmat)
{
bool MMt_SelfTest = false;//HDebug.IsDebuggerAttached;
if(MMt_SelfTest)
{
MMt_SelfTest = false;
/// >> A=[ 1,2,3,4 ; 5,6,7,8 ];
/// >> B=[ 1,3,5,7 ; 2,4,6,8 ; 3,5,7,9 ];
/// >> A*B'
/// ans =
/// 50 60 70
/// 114 140 166
Matrix _A = new double[2, 4]
{ { 1, 2, 3, 4 }
, { 5, 6, 7, 8 } };
Matrix _B = new double[3, 4]
{ { 1, 3, 5, 7 }
, { 2, 4, 6, 8 }
, { 3, 5, 7, 9 } };
Matrix _AtB = MMt(_A, _B);
Matrix _AtB_sol = new double[2,3]
{ { 50, 60, 70 }
, { 114, 140, 166 } };
double err = (_AtB - _AtB_sol).HAbsMax();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.RowSize == rmat.RowSize);
int size1 = lmat.ColSize;
int size2 = lmat.RowSize;
int size3 = rmat.ColSize;
Matrix result = Matrix.Zeros(size1, size3);
for(int c=0; c<size1; c++)
for(int r=0; r<size3; r++)
{
double sum = 0;
for(int i=0; i<size2; i++)
// lmat[c,i] * tr(rmat[i,r]) => lmat[c,i] * rmat[r,i]
sum += lmat[c,i] * rmat[r,i];
result[c, r] = sum;
}
return result;
}
static bool MtV_SelfTest = HDebug.IsDebuggerAttached;
public static Vector MtV(Matrix lmat, Vector rvec)
{
if(MtV_SelfTest)
{
MtV_SelfTest = false;
/// >> A = [ 1,2,3 ; 4,5,6 ; 7,8,9 ; 10,11,12 ];
/// >> B = [ 1; 2; 3; 4 ];
/// >> A'*B
/// ans =
/// 70
/// 80
/// 90
MatrixByArr tM = new double[4, 3] { { 1, 2, 3 }
, { 4, 5, 6 }
, { 7, 8, 9 }
, { 10, 11, 12 } };
Vector tV = new double[4] { 1, 2, 3, 4 };
Vector tMtV0 = new double[3] { 70, 80, 90 };
Vector tMtV1 = MtV(tM, tV);
double err = (tMtV0 - tMtV1).ToArray().HAbs().Max();
HDebug.Assert(err == 0);
}
HDebug.Assert(lmat.ColSize == rvec.Size);
Vector result = new Vector(lmat.RowSize);
for(int c=0; c<lmat.ColSize; c++)
for(int r=0; r<lmat.RowSize; r++)
result[r] += lmat[c, r] * rvec[c];
return result;
}
public static bool V1tD2V3_SelfTest = HDebug.IsDebuggerAttached;
public static double V1tD2V3(Vector V1, Matrix D2, Vector V3, bool assertDiag=true)
{
if(V1tD2V3_SelfTest)
{
V1tD2V3_SelfTest = false;
Vector tV1 = new double[3] { 1, 2, 3 };
MatrixByArr tD2 = new double[3, 3] { { 2, 0, 0 }, { 0, 3, 0 }, { 0, 0, 4 } };
Vector tV3 = new double[3] { 3, 4, 5 };
// [2 ] [3] [ 6]
// [1 2 3] * [ 3 ] * [4] = [1 2 3] * [12] = 6+24+60 = 90
// [ 4] [5] [20]
double tV1tD2V3 = 90;
HDebug.AssertTolerance(double.Epsilon, tV1tD2V3 - V1tD2V3(tV1, tD2, tV3));
}
if(assertDiag) // check diagonal matrix
HDebug.AssertToleranceMatrix(double.Epsilon, D2 - Diag(Diag(D2)));
HDebug.Assert(V1.Size == D2.ColSize);
HDebug.Assert(D2.RowSize == V3.Size );
Vector lD2V3 = DV(D2, V3, assertDiag);
double lV1tD2V3 = VtV(V1, lD2V3);
return lV1tD2V3;
}
public static MatrixByArr VVt(Vector lvec, Vector rvec)
{
MatrixByArr outmat = new MatrixByArr(lvec.Size, rvec.Size);
VVt(lvec, rvec, outmat);
return outmat;
}
public static void VVt(Vector lvec, Vector rvec, MatrixByArr outmat)
{
HDebug.Exception(outmat.ColSize == lvec.Size);
HDebug.Exception(outmat.RowSize == rvec.Size);
//MatrixByArr mat = new MatrixByArr(lvec.Size, rvec.Size);
for(int c = 0; c < lvec.Size; c++)
for(int r = 0; r < rvec.Size; r++)
outmat[c, r] = lvec[c] * rvec[r];
}
public static void VVt_AddTo(Vector lvec, Vector rvec, MatrixByArr mat)
{
HDebug.Exception(mat.ColSize == lvec.Size);
HDebug.Exception(mat.RowSize == rvec.Size);
for(int c = 0; c < lvec.Size; c++)
for(int r = 0; r < rvec.Size; r++)
mat[c, r] += lvec[c] * rvec[r];
}
public static void sVVt_AddTo(double scale, Vector lvec, Vector rvec, MatrixByArr mat)
{
HDebug.Exception(mat.ColSize == lvec.Size);
HDebug.Exception(mat.RowSize == rvec.Size);
for(int c = 0; c < lvec.Size; c++)
for(int r = 0; r < rvec.Size; r++)
mat[c, r] += lvec[c] * rvec[r] * scale;
}
public static bool DMD_selftest = HDebug.IsDebuggerAttached;
public static MATRIX DMD<MATRIX>(Vector diagmat1, MATRIX mat,Vector diagmat2, Func<int,int,MATRIX> Zeros)
where MATRIX : IMatrix<double>
{
if(DMD_selftest)
#region selftest
{
HDebug.ToDo("check");
DMD_selftest = false;
Vector td1 = new double[] { 1, 2, 3 };
Vector td2 = new double[] { 4, 5, 6 };
Matrix tm = new double[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Matrix dmd0 = LinAlg.Diag(td1) * tm * LinAlg.Diag(td2);
Matrix dmd1 = LinAlg.DMD(td1, tm, td2, Matrix.Zeros);
double err = (dmd0 - dmd1).HAbsMax();
HDebug.Assert(err == 0);
}
#endregion
MATRIX DMD = Zeros(mat.ColSize, mat.RowSize);
for(int c=0; c<mat.ColSize; c++)
for(int r=0; r<mat.RowSize; r++)
{
double v0 = mat[c, r];
double v1 = diagmat1[c] * v0 * diagmat2[r];
if(v0 == v1) continue;
DMD[c, r] = v1;
}
return DMD;
}
//public static bool VtMV_selftest = HDebug.IsDebuggerAttached;
public static double VtMV(Vector lvec, IMatrix<double> mat, Vector rvec) //, string options="")
{
if(HDebug.Selftest())
{
Vector _lvec = new double[3] { 1, 2, 3 };
Matrix _mat = new double[3,4] { { 4, 5, 6, 7 }
, { 8, 9, 10, 11 }
, { 12, 13, 14, 15 }
};
Vector _rvec = new double[4] { 16, 17, 18, 19 };
double _v0 = VtMV(_lvec,_mat,_rvec);
double _v1 = 4580;
HDebug.Assert(_v0 == _v1);
}
HDebug.Assert(lvec.Size == mat.ColSize);
HDebug.Assert(mat.RowSize == rvec.Size);
double ret = 0;
for(int c=0; c<lvec.Size; c++)
for(int r=0; r<rvec.Size; r++)
ret += lvec[c] * mat[c,r] * rvec[r];
return ret;
// Vector MV = LinAlg.MV(mat, rvec, options);
// double VMV = LinAlg.VtV(lvec, MV);
// //Debug.AssertToleranceIf(lvec.Size<100, 0.00000001, Vector.VtV(lvec, Vector.MV(mat, rvec)) - VMV);
// return VMV;
}
public static MatrixByArr M_Mt(MatrixByArr lmat, MatrixByArr rmat)
{
// M + Mt
HDebug.Assert(lmat.ColSize == rmat.RowSize);
HDebug.Assert(lmat.RowSize == rmat.ColSize);
MatrixByArr MMt = lmat.CloneT();
for(int c = 0; c < MMt.ColSize; c++)
for(int r = 0; r < MMt.RowSize; r++)
MMt[c, r] += rmat[r, c];
return MMt;
}
public static double VtV(Vector l, Vector r)
{
HDebug.Assert(l.Size == r.Size);
int size = l.Size;
double result = 0;
for(int i=0; i < size; i++)
result += l[i] * r[i];
return result;
}
public static double[] ListVtV(Vector l, IList<Vector> rs)
{
double[] listvtv = new double[rs.Count];
for(int i=0; i<rs.Count; i++)
listvtv[i] = VtV(l, rs[i]);
return listvtv;
}
public static double VtV(Vector l, Vector r, IList<int> idxsele)
{
HDebug.Assert(l.Size == r.Size);
Vector ls = l.ToArray().HSelectByIndex(idxsele);
Vector rs = r.ToArray().HSelectByIndex(idxsele);
return VtV(ls, rs);
}
public static Vector VtMM(Vector v1, Matrix m2, Matrix m3)
{
Vector v12 = VtM(v1, m2);
return VtM(v12, m3);
}
public static class AddToM
{
public static void VVt(Matrix M, Vector V)
{
HDebug.Assert(M.ColSize == V.Size);
HDebug.Assert(M.RowSize == V.Size);
int size = V.Size;
for(int c=0; c<size; c++)
for(int r=0; r<size; r++)
M[c, r] += V[c] * V[r];
}
}
public static Vector VtM<MATRIX>(Vector lvec, MATRIX rmat)
where MATRIX : IMatrix<double>
{
HDebug.Assert(lvec.Size == rmat.ColSize);
Vector result = new Vector(rmat.RowSize);
for(int c=0; c<rmat.ColSize; c++)
for(int r=0; r<rmat.RowSize; r++)
result[r] += lvec[c] * rmat[c, r];
return result;
}
}
}
| htna/HCsbLib | HCsbLib/HCsbLib/HTLib2/HMath.Numerics.LinAlg/LinAlg/LinAlg.Matrix.cs | C# | mit | 20,887 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
//[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", Watch = true)]
// 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("Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("560958c4-0e26-41ab-ba0d-6b36e97013e2")]
// 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")]
| sfederella/simurails-project | Desarrollo/Tests/Properties/AssemblyInfo.cs | C# | mit | 1,474 |
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("Practice Integer Numbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Practice Integer Numbers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1f0e5981-373b-4979-a1db-6755bea3ce96")]
// 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")]
| VelizarMitrev/Programmming_Fundamentals | Data types and variables/Practice Integer Numbers/Properties/AssemblyInfo.cs | C# | mit | 1,424 |
using System.Web;
using System.Web.Optimization;
namespace CattoEmptyWebApplication
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| ccatto/VisualStudio2015WebMVCEmptyTemplate | CattoEmptyWebApplication/CattoEmptyWebApplication/App_Start/BundleConfig.cs | C# | mit | 1,255 |
using System.Collections;
using System.Collections.Generic;
using Lockstep.Data;
using UnityEngine;
namespace Lockstep
{
public static class InputCodeManager
{
private static Dictionary<string,InputDataItem> InputDataMap = new Dictionary<string, InputDataItem>();
private static BiDictionary<string,ushort> InputMap = new BiDictionary<string, ushort>();
private static bool Setted {get; set;}
public static void Setup () {
IInputDataProvider provider;
if (LSDatabaseManager.TryGetDatabase<IInputDataProvider> (out provider)) {
InputDataItem[] inputData = provider.InputData;
for (int i = inputData.Length - 1; i >= 0; i--) {
InputDataItem item = inputData[i];
ushort id = (ushort)(i + 1);
string code = inputData[i].Name;
InputMap.Add(code,id);
InputDataMap.Add (code,item);
}
Setted = true;
}
}
public static InputDataItem GetInputData (string code) {
InputDataItem item;
if (InputDataMap.TryGetValue(code, out item)) {
return item;
}
else {
Debug.Log ("No InputData of " + code + " found. Ignoring.");
}
return null;
}
public static ushort GetCodeID (string code) {
if (!Setted)
throw NotSetupException;
if (string.IsNullOrEmpty(code))
return 0;
try {
return InputMap[code];
}
catch {
throw new System.Exception(string.Format("Code '{0}' does not exist in the current database", code));
}
}
public static string GetIDCode (ushort id) {
if (!Setted)
throw NotSetupException;
if (id == 0)
return "";
return InputMap.GetReversed(id);
}
static System.Exception NotSetupException {
get {
return new System.Exception("InputCodeManager has not yet been setup.");
}
}
}
} | erebuswolf/LockstepFramework | Core/Game/Managers/Input/InputCodeManager.cs | C# | mit | 2,251 |
using System;
class SortingArray
{
//Sorting an array means to arrange its elements in
//increasing order. Write a program to sort an array.
//Use the "selection sort" algorithm: Find the smallest
//element, move it at the first position, find the smallest
//from the rest, move it at the second position, etc.
static void Main()
{
//variables
int[] array = new int[10];
Random rand = new Random();
int max;
//expressions
//fill the array with random values
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(9);
}
//sort the array from smallest to biggest
//I variant
for (int i = array.Length - 1; i > 0; i--)
{
max = i;
for (int m = i - 1; m >= 0; m--)
{
if (array[m] > array[max])
{
max = m;
}
}
//swap current element with smallest element
if (i != max)
{
array[i] = array[i] ^ array[max];
array[max] = array[max] ^ array[i];
array[i] = array[i] ^ array[max];
}
}
//II variant
//Array.Sort(array);
#region print result
//print array
Console.Write("{");
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i] + " ");
if (i != array.Length - 1)
{
Console.Write(',');
}
}
Console.WriteLine("}");
#endregion
}
}
| niki-funky/Telerik_Academy | Programming/02.Csharp/02. Arrays/07.SortingArray/07.SortingArray .cs | C# | mit | 1,655 |
namespace Knoledge_Monitor
{
partial class FormNodes
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.textBoxVersion = new System.Windows.Forms.TextBox();
this.textBoxHeight = new System.Windows.Forms.TextBox();
this.textBoxPerf = new System.Windows.Forms.TextBox();
this.textBoxLatency = new System.Windows.Forms.TextBox();
this.textBoxAt = new System.Windows.Forms.TextBox();
this.textBoxSeen = new System.Windows.Forms.TextBox();
this.buttonClose = new System.Windows.Forms.Button();
this.listView = new System.Windows.Forms.ListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(403, 15);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(67, 20);
this.label1.TabIndex = 1;
this.label1.Text = "Version:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(403, 49);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(99, 20);
this.label2.TabIndex = 2;
this.label2.Text = "Start Height:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(403, 81);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(104, 20);
this.label3.TabIndex = 3;
this.label3.Text = "Performance:";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(403, 113);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(104, 20);
this.label4.TabIndex = 4;
this.label4.Text = "Latency (ms):";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(403, 145);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(109, 20);
this.label5.TabIndex = 5;
this.label5.Text = "Connected at:";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(403, 177);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(83, 20);
this.label6.TabIndex = 6;
this.label6.Text = "Last seen:";
//
// textBoxVersion
//
this.textBoxVersion.Location = new System.Drawing.Point(528, 12);
this.textBoxVersion.Name = "textBoxVersion";
this.textBoxVersion.ReadOnly = true;
this.textBoxVersion.Size = new System.Drawing.Size(387, 26);
this.textBoxVersion.TabIndex = 7;
//
// textBoxHeight
//
this.textBoxHeight.Location = new System.Drawing.Point(528, 46);
this.textBoxHeight.Name = "textBoxHeight";
this.textBoxHeight.ReadOnly = true;
this.textBoxHeight.Size = new System.Drawing.Size(387, 26);
this.textBoxHeight.TabIndex = 8;
//
// textBoxPerf
//
this.textBoxPerf.Location = new System.Drawing.Point(528, 78);
this.textBoxPerf.Name = "textBoxPerf";
this.textBoxPerf.ReadOnly = true;
this.textBoxPerf.Size = new System.Drawing.Size(387, 26);
this.textBoxPerf.TabIndex = 9;
//
// textBoxLatency
//
this.textBoxLatency.Location = new System.Drawing.Point(528, 110);
this.textBoxLatency.Name = "textBoxLatency";
this.textBoxLatency.ReadOnly = true;
this.textBoxLatency.Size = new System.Drawing.Size(387, 26);
this.textBoxLatency.TabIndex = 10;
//
// textBoxAt
//
this.textBoxAt.Location = new System.Drawing.Point(528, 142);
this.textBoxAt.Name = "textBoxAt";
this.textBoxAt.ReadOnly = true;
this.textBoxAt.Size = new System.Drawing.Size(387, 26);
this.textBoxAt.TabIndex = 11;
//
// textBoxSeen
//
this.textBoxSeen.Location = new System.Drawing.Point(528, 174);
this.textBoxSeen.Name = "textBoxSeen";
this.textBoxSeen.ReadOnly = true;
this.textBoxSeen.Size = new System.Drawing.Size(387, 26);
this.textBoxSeen.TabIndex = 12;
//
// buttonClose
//
this.buttonClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonClose.Location = new System.Drawing.Point(840, 384);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(75, 34);
this.buttonClose.TabIndex = 13;
this.buttonClose.Text = "Close";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
//
// listView
//
this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1});
this.listView.FullRowSelect = true;
this.listView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.listView.HideSelection = false;
this.listView.Location = new System.Drawing.Point(12, 15);
this.listView.Name = "listView";
this.listView.Size = new System.Drawing.Size(365, 403);
this.listView.TabIndex = 14;
this.listView.UseCompatibleStateImageBehavior = false;
this.listView.View = System.Windows.Forms.View.Details;
this.listView.SelectedIndexChanged += new System.EventHandler(this.listView_SelectedIndexChanged);
//
// columnHeader1
//
this.columnHeader1.Text = "Address";
this.columnHeader1.Width = 300;
//
// FormNodes
//
this.AcceptButton = this.buttonClose;
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.buttonClose;
this.ClientSize = new System.Drawing.Size(947, 430);
this.Controls.Add(this.listView);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.textBoxSeen);
this.Controls.Add(this.textBoxAt);
this.Controls.Add(this.textBoxLatency);
this.Controls.Add(this.textBoxPerf);
this.Controls.Add(this.textBoxHeight);
this.Controls.Add(this.textBoxVersion);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FormNodes";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Connected Nodes";
this.Load += new System.EventHandler(this.FormNodes_Load);
this.Shown += new System.EventHandler(this.FormNodes_Shown);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox textBoxVersion;
private System.Windows.Forms.TextBox textBoxHeight;
private System.Windows.Forms.TextBox textBoxPerf;
private System.Windows.Forms.TextBox textBoxLatency;
private System.Windows.Forms.TextBox textBoxAt;
private System.Windows.Forms.TextBox textBoxSeen;
private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.ListView listView;
private System.Windows.Forms.ColumnHeader columnHeader1;
}
} | petebryant/knoledge-monitor | Knoledge-Monitor/FormNodes.Designer.cs | C# | mit | 10,270 |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Globalization;
using System.IO;
namespace uWebshop.Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a raw JSON string.
/// </summary>
public class JRaw : JValue
{
/// <summary>
/// Initializes a new instance of the <see cref="JRaw"/> class from another <see cref="JRaw"/> object.
/// </summary>
/// <param name="other">A <see cref="JRaw"/> object to copy from.</param>
public JRaw(JRaw other) : base(other)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JRaw"/> class.
/// </summary>
/// <param name="rawJson">The raw json.</param>
public JRaw(object rawJson) : base(rawJson, JTokenType.Raw)
{
}
/// <summary>
/// Creates an instance of <see cref="JRaw"/> with the content of the reader's current token.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>An instance of <see cref="JRaw"/> with the content of the reader's current token.</returns>
public static JRaw Create(JsonReader reader)
{
using (var sw = new StringWriter(CultureInfo.InvariantCulture))
using (var jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteToken(reader);
return new JRaw(sw.ToString());
}
}
internal override JToken CloneToken()
{
return new JRaw(this);
}
}
} | uWebshop/uWebshop-Releases | Core/uWebshop.Domain/NewtonsoftJsonNet/Linq/JRaw.cs | C# | mit | 2,442 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Track.Auth.Web.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_UserId",
table: "AspNetUserRoles",
column: "UserId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| iqduke/Track | src/Track.Auth.Web/Data/Migrations/00000000000000_CreateIdentitySchema.cs | C# | mit | 9,250 |
using SpectrumFish;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Num = System.Int32;
namespace SpectrumFish.Tests
{
[TestFixture]
class Z80Tests
{
[Test]
public void GivenZ80WithChanges_WhenReset_ThenRegistersAndStuffMatchNewZ80()
{
// arrange
var mockMem = new Mock<IMemory>();
var mockPorts = new Mock<IPorts>();
var testZ80 = new Z80(mockMem.Object, mockPorts.Object);
testZ80.a = testZ80.f = testZ80.b = testZ80.c = testZ80.d = testZ80.e = testZ80.h = testZ80.l = 1;
testZ80.a_ = testZ80.f_ = testZ80.b_ = testZ80.c_ = testZ80.d_ = testZ80.e_ = testZ80.h_ = testZ80.l_ = 1;
testZ80.ixh = testZ80.ixl = testZ80.iyh = testZ80.iyl = 1;
testZ80.i = 1;
testZ80.r = 1;
testZ80.r7 = 1;
testZ80.sp = testZ80.pc = 1;
testZ80.iff1 = testZ80.iff2 = testZ80.im = 1;
testZ80.halted = true;
//// act
testZ80.reset();
// assert
var expected = new Z80(mockMem.Object, mockPorts.Object);
//Assert. (new Z80(mockMem.Object, mockPorts.Object), testZ80);
Assert.AreEqual(expected, testZ80);
}
[Test]
public void GivenNewZ80_WhenInterrupt_ThenWriteByteIsntCalled()
{
// arrange
var mockMem = new Mock<IMemory>();
var writebyteIsCalled = false;
mockMem.Setup(mem => mem.WriteByte(It.IsAny<Num>(), It.IsAny<Num>())).Callback(() => writebyteIsCalled = true);
var mockPorts = new Mock<IPorts>();
var expected = new Z80(mockMem.Object, mockPorts.Object);
var testZ80 = new Z80(mockMem.Object, mockPorts.Object);
// act
testZ80.interrupt();
// assert
Assert.AreEqual(expected, testZ80);
Assert.IsFalse(writebyteIsCalled);
}
[Test]
public void GivenZ80WithIff1_WhenInterrupt_ThenStackPointCalled()
{
// arrange
var mockMem = new Mock<IMemory>();
var writebyteIsCalled = false;
mockMem.Setup(mem => mem.WriteByte(65534, 0)).Callback(() => writebyteIsCalled = true);
var mockPorts = new Mock<IPorts>();
var testZ80 = new Z80(mockMem.Object, mockPorts.Object);
// act
testZ80.iff1 = 1;
testZ80.halted = false;
testZ80.im = 0;
testZ80.interrupt();
// assert
var expected = new Z80(mockMem.Object, mockPorts.Object) { r = 1, sp = 65534, pc = 56, tstates = 12 };
Assert.AreEqual(expected, testZ80);
Assert.IsTrue(writebyteIsCalled);
}
[Test]
public void GivenZ80IsHalted_WhenInterrupt_ThenStuffhappens()
{
// arrange
Z80 expected = null;
var mockMem = new Mock<IMemory>();
var writebyteIsCalled = false;
mockMem.Setup(mem => mem.WriteByte(It.IsAny<Num>(), It.IsAny<Num>())).Callback(() => writebyteIsCalled = true);
var mockPorts = new Mock<IPorts>();
var testZ80 = new Z80(mockMem.Object, mockPorts.Object);
// act
testZ80.iff1 = 0;
testZ80.halted = false;
testZ80.im = 0;
testZ80.interrupt();
// assert
expected = new Z80(mockMem.Object, mockPorts.Object) { r = 0, sp = 0, pc = 0 };
Assert.AreEqual(expected, testZ80);
Assert.False(writebyteIsCalled);
//-----------------------------------------------------
// arrange
writebyteIsCalled = false;
mockMem.Setup(mem => mem.WriteByte(65534, 0)).Callback(() => writebyteIsCalled = true);
// act
testZ80.iff1 = 1;
testZ80.halted = false;
testZ80.im = 0;
testZ80.interrupt();
// assert
expected = new Z80(mockMem.Object, mockPorts.Object) { r = 1, sp = 65534, pc = 56, tstates = 12 };
Assert.AreEqual(expected, testZ80);
Assert.IsTrue(writebyteIsCalled);
//-----------------------------------------------------
// arrange
writebyteIsCalled = false;
mockMem.Setup(mem => mem.WriteByte(65532, 57)).Callback(() => writebyteIsCalled = true);
// act
testZ80.iff1 = 1;
testZ80.halted = true;
testZ80.im = 0;
testZ80.interrupt();
// assert
expected = new Z80(mockMem.Object, mockPorts.Object) { r = 2, sp = 65532, pc = 56, tstates = 24 };
Assert.AreEqual(expected, testZ80);
Assert.IsTrue(writebyteIsCalled);
//-----------------------------------------------------
// arrange
writebyteIsCalled = false;
mockMem.Setup(mem => mem.WriteByte(65530, 57)).Callback(() => writebyteIsCalled = true);
//Act
testZ80.iff1 = 1;
testZ80.halted = true;
testZ80.im = 1;
testZ80.interrupt();
// assert
expected = new Z80(mockMem.Object, mockPorts.Object) { r = 3, sp = 65530, pc = 56, im = 1, tstates = 37 };
Assert.AreEqual(expected, testZ80);
Assert.IsTrue(writebyteIsCalled);
//-----------------------------------------------------
// arrange
writebyteIsCalled = false;
mockMem.Setup(mem => mem.WriteByte(65528, 57)).Callback(() => writebyteIsCalled = true);
//Act
testZ80.iff1 = 1;
testZ80.halted = true;
testZ80.im = 2;
testZ80.interrupt();
// assert
expected = new Z80(mockMem.Object, mockPorts.Object) { r = 4, sp = 65528, im = 2, tstates = 56 };
Assert.AreEqual(expected, testZ80);
Assert.IsTrue(writebyteIsCalled);
}
[Test]
public void GivenZ80_WhenNMI_ThenSomethingHappens()
{
// arrange
var mockMem = new Mock<IMemory>();
var writebyteIsCalled = false;
mockMem.Setup(mem => mem.WriteByte(65534, 0)).Callback(() => writebyteIsCalled = true);
var mockPorts = new Mock<IPorts>();
var testZ80 = new Z80(mockMem.Object, mockPorts.Object);
// act
testZ80.iff1 = 1;
testZ80.halted = false;
testZ80.im = 0;
testZ80.interrupt();
// assert
var expected = new Z80(mockMem.Object, mockPorts.Object) { r=1, sp = 65534, pc=56, tstates = 12 };
Assert.AreEqual(expected, testZ80);
Assert.IsTrue(writebyteIsCalled);
}
}
}
| FinnAngelo/Tomfoolery | ZX/ZxMe/FAfx.SpectrumFish.Tests/Z80Tests.cs | C# | mit | 7,053 |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Rhapsody.Utilities;
namespace Rhapsody.Core.AlbumInfoProviders
{
internal class FileNameAlbumInfoProvider : IAlbumInfoProvider
{
public string Name
{
get
{
return "File and Folder Name";
}
}
public Image Icon
{
get
{
return null;
}
}
public AlbumInfo GetAlbumInfo(Album album, Session session, Context context)
{
var albumInfo = new AlbumInfo();
var directoryName = album.SourceDirectory.Parent.Name + @"\" + album.SourceDirectory.Name;
var formats = new[]
{
new Regex(@"^.*\\(?<artist>.*)-(?<album>.*)-.*-(?<year>\d{4})$"),
new Regex(@"^.*\\(?<artist>.*)-( )*(?<album>.*)( )*\(?(?<year>\d{4})\)?$"),
new Regex(@"^.*\\(?<artist>.*)-( )*(?<year>\d{4})( )*-(?<album>.*)$"),
new Regex(@"^(?<artist>.*)\\(?<year>\d{4}) - (?<album>.*)$"),
new Regex(@"^(?<artist>.*)\\(?<album>.*)$")
};
foreach (var format in formats)
{
var match = format.Match(directoryName);
if (match.Success)
{
albumInfo.ArtistName = StringHelper.Normalize(match.Groups["artist"].Value);
albumInfo.Name = StringHelper.Normalize(match.Groups["album"].Value);
albumInfo.ReleaseYear = StringHelper.Trim(match.Groups["year"].Value);
break;
}
}
foreach (var disc in album.Discs)
{
albumInfo.DiscNames[disc] = null;
var discTrackNames = new Dictionary<Track, string>();
foreach (var track in disc.Tracks)
discTrackNames[track] = Path.GetFileNameWithoutExtension(track.SourceFile.Name).Replace("_", " ");
TrimLeft(discTrackNames);
TrimRight(discTrackNames);
foreach (var pair in new Dictionary<Track, string>(albumInfo.TrackNames))
discTrackNames[pair.Key] = StringHelper.MakeProperCase(StringHelper.Trim(pair.Value));
foreach (var pair in discTrackNames)
albumInfo.TrackNames[pair.Key] = pair.Value;
}
var imageFiles = album.SourceDirectory.EnumerateFilesEx(@"\.jpg|\.png|\.gif").ToArray();
var coverImageFile = SelectCoverImage(imageFiles, albumInfo);
if (coverImageFile != null)
albumInfo.Cover = Picture.Load(coverImageFile.FullName);
return albumInfo;
}
private static FileInfo SelectCoverImage(IEnumerable<FileInfo> imageFiles, AlbumInfo albumInfo)
{
var cachedImageFiles = imageFiles.Cache();
var patterns = new List<Regex>();
patterns.Add(new Regex(@"cover", RegexOptions.IgnoreCase));
patterns.Add(new Regex(@"front", RegexOptions.IgnoreCase));
if (albumInfo.Name != null)
patterns.Add(new Regex(Regex.Escape(albumInfo.Name), RegexOptions.IgnoreCase));
foreach (var pattern in patterns)
foreach (var imageFile in cachedImageFiles)
if (pattern.IsMatch(imageFile.Name))
return imageFile;
return null;
}
private static void TrimLeft(Dictionary<Track, string> trackNames)
{
if (trackNames.Count < 2)
return;
while (true)
{
if (trackNames.Values.Any(trackName => trackName.Length == 0))
return;
var areAllFirstCharsEqual = trackNames.Values.AllEqual(trackName => trackName.First());
var areAllFirstCharsDigit = trackNames.Values.All(trackName => char.IsDigit(trackName.First()));
if (!areAllFirstCharsEqual && !areAllFirstCharsDigit)
break;
foreach (var pair in new Dictionary<Track, string>(trackNames))
trackNames[pair.Key] = pair.Value.Remove(0, 1);
}
}
private static void TrimRight(Dictionary<Track, string> trackNames)
{
if (trackNames.Count < 2)
return;
while (true)
{
if (trackNames.Values.Any(trackName => trackName.Length == 0))
return;
var areAllLastCharsEqual = trackNames.Values.AllEqual(trackName => trackName.Last());
if (!areAllLastCharsEqual)
break;
var lastChar = trackNames.First().Value.Last();
if (lastChar == ')')
break;
foreach (var pair in new Dictionary<Track, string>(trackNames))
trackNames[pair.Key] = pair.Value.Remove(pair.Value.Length - 1, 1);
}
}
}
}
| soheilpro/Rhapsody | Sources/Rhapsody/Core/AlbumInfoProviders/FileNameAlbumInfoProvider.cs | C# | mit | 5,336 |
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("06. FindAndSumIntegers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06. FindAndSumIntegers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3eea31e4-f665-49cb-9f61-310a705453fc")]
// 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")]
| krasiymihajlov/Soft-Uni-practices | C# Advanced/08. LinQ/LINQ - Lab/06. FindAndSumIntegers/Properties/AssemblyInfo.cs | C# | mit | 1,415 |
using NUnit.Framework;
using CurrencyCloud.Entity;
using CurrencyCloud.Tests.Mock.Data;
using CurrencyCloud.Entity.Pagination;
using CurrencyCloud.Tests.Mock.Http;
using CurrencyCloud.Environment;
using System.Threading.Tasks;
namespace CurrencyCloud.Tests
{
[TestFixture]
class VirtualAccountsTest
{
Client client = new Client();
Player player = new Player("/../../Mock/Http/Recordings/VirtualAccounts.json");
[OneTimeSetUpAttribute]
public void SetUp()
{
player.Start(ApiServer.Mock.Url);
player.Play("SetUp");
var credentials = Authentication.Credentials;
client.InitializeAsync(Authentication.ApiServer, credentials.LoginId, credentials.ApiKey).Wait();
}
[OneTimeTearDownAttribute]
public void TearDown()
{
player.Play("TearDown");
client.CloseAsync().Wait();
player.Close();
}
/// <summary>
/// Successfully finds VANS.
/// </summary>
[Test]
public async Task Find()
{
player.Play("Find");
var van = VirtualAccounts.Van1;
PaginatedVirtualAccounts found = await client.FindVirtualAccountsAsync();
Assert.AreEqual(van.Id, found.VirtualAccounts[0].Id);
Assert.AreEqual(van.VirtualAccountNumber, found.VirtualAccounts[0].VirtualAccountNumber);
Assert.AreEqual(van.AccountId, found.VirtualAccounts[0].AccountId);
Assert.AreEqual(van.AccountHolderName, found.VirtualAccounts[0].AccountHolderName);
Assert.AreEqual(van.BankInstitutionName, found.VirtualAccounts[0].BankInstitutionName);
Assert.AreEqual(van.BankInstitutionAddress, found.VirtualAccounts[0].BankInstitutionAddress);
Assert.AreEqual(van.BankInstitutionCountry, found.VirtualAccounts[0].BankInstitutionCountry);
Assert.AreEqual(van.RoutingCode, found.VirtualAccounts[0].RoutingCode);
}
}
} | CurrencyCloud/currencycloud-net | Source/CurrencyCloud.Tests/VirtualAccountsTest.cs | C# | mit | 2,033 |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using SocialToolBox.Core.Database.Index;
namespace SocialToolBox.Core.Tests.Database.Index
{
[TestFixture]
public class index_key_comparer
{
[IndexKey]
public class KeyMock
{
[IndexField(1)]
public int Integer;
[IndexField(0)]
public int? NullInteger { get; set; }
[IndexField(2)]
public string String;
[IndexField(3, IsCaseSensitive = false)]
public string StringCaseInsensitive;
[IndexField(4)]
public bool Boolean;
[IndexField(4)]
public bool? NullBoolean;
[IndexField(5)]
public DateTime Time;
[IndexField(6)]
public DateTime? NullTime { get; set; }
public int NotCompared;
}
private IComparer<KeyMock> _comparer;
[SetUp]
public void SetUp()
{
_comparer = new IndexKeyComparer<KeyMock>();
}
[Test]
public void equal()
{
Assert.AreEqual(0, _comparer.Compare(new KeyMock(), new KeyMock()));
}
[Test]
public void equal_with_not_compared()
{
Assert.AreEqual(0, _comparer.Compare(new KeyMock{NotCompared = 1}, new KeyMock()));
}
[Test]
public void int_inequality()
{
Assert.Less(0, _comparer.Compare(new KeyMock{Integer=3}, new KeyMock()));
}
[Test]
public void is_symmetrical()
{
Assert.Greater(0, _comparer.Compare(new KeyMock(), new KeyMock { Integer = 3 }));
}
[Test]
public void null_int_inequality()
{
Assert.Less(0, _comparer.Compare(new KeyMock {NullInteger=3}, new KeyMock()));
}
[Test]
public void string_inequality()
{
Assert.Less(0, _comparer.Compare(new KeyMock {String="A"}, new KeyMock()));
}
[Test]
public void string_ci_inequality()
{
Assert.Less(0, _comparer.Compare(new KeyMock {StringCaseInsensitive="A"}, new KeyMock()));
}
[Test]
public void string_ci_equality()
{
Assert.AreEqual(0, _comparer.Compare(new KeyMock { StringCaseInsensitive="i"}, new KeyMock{StringCaseInsensitive="I"}));
}
[Test]
public void bool_inequality()
{
Assert.Less(0, _comparer.Compare(new KeyMock {Boolean = true}, new KeyMock()));
}
[Test]
public void null_bool_inequality()
{
Assert.Less(0, _comparer.Compare(new KeyMock {NullBoolean = false}, new KeyMock()));
}
[Test]
public void datetime_inequality()
{
Assert.Less(0, _comparer.Compare(new KeyMock {Time=DateTime.Parse("2012/05/21")}, new KeyMock()));
}
[Test]
public void null_datetime_inequality()
{
Assert.Less(0, _comparer.Compare(new KeyMock {NullTime=DateTime.Parse("2012/05/21")}, new KeyMock()));
}
[Test]
public void respect_order()
{
Assert.Less(0, _comparer.Compare(
// Field order = 0 is greater
new KeyMock{NullInteger = 1},
// Field order = 1 is greater
new KeyMock{Integer = 1}
));
}
[Test]
public void same_order_respect_declaration()
{
Assert.Less(0, _comparer.Compare(
new KeyMock { Boolean = true },
new KeyMock { NullBoolean = true }
));
}
}
}
| VictorNicollet/SocialToolBox | SocialToolBox.Core.Tests/Database/Index/index_key_comparer.cs | C# | mit | 3,776 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra;
namespace SamSeifert.ComputerVision
{
public static partial class SingleImage
{
/// <summary>
/// Specials Errors: Couldn't Initialize different clusters!
/// </summary>
/// <param name="inpt"></param>
/// <param name="K"></param>
/// <param name="outp"></param>
/// <returns></returns>
public static ToolboxReturn KMeans(
Sect inpt,
ref Sect outp,
int K,
int max_iterations = 100
)
{
if (inpt == null)
{
outp = null;
return ToolboxReturn.NullInput;
}
else
{
MatchOutputToInput(inpt, ref outp);
var sz = outp.getPrefferedSize();
int w = sz.Width;
int h = sz.Height;
var in_sects = new List<Sect>();
var out_sects = new List<Sect>();
if (inpt._Type == SectType.Holder)
{
var sh = inpt as SectHolder;
foreach (var inp in sh.Sects.Values)
{
in_sects.Add(inp);
out_sects.Add((outp as SectHolder).getSect(inp._Type));
}
}
else
{
in_sects.Add(inpt);
out_sects.Add(outp);
}
int pixels = w * h;
var pixels_vectors = new Vector<float>[pixels];
var pixels_cluster = new int[pixels];
for (int p = 0; p < pixels; p++)
pixels_vectors[p] = Vector<float>.Build.Dense(in_sects.Count);
for (int s = 0; s < in_sects.Count; s++)
{
var sect = in_sects[s];
int p = 0;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
pixels_vectors[p++][s] = sect[y, x];
}
var new_cluster_centers = new Vector<float>[K];
var new_cluster_counts = new int[K];
var cluster_centers = new Vector<float>[K];
// Initialize Clusters
{
// Try to initialize K clusters! (give us 10 tries)
bool found = false;
Random r = new Random(Environment.TickCount);
for (int tries = 0; (tries < 10) && (!found); tries++)
{
found = true;
for (int k = 0; (k < K) && found; k++)
{
cluster_centers[k] = pixels_vectors[r.Next(pixels)];
for (int checker = 0; (checker < k) && found; checker++)
if (cluster_centers[k].Equals(cluster_centers[checker]))
found = false;
}
}
if (!found) return ToolboxReturn.SpecialError;
}
// Run K Means. Max 100 iterations
for (int iterations = 0; iterations < max_iterations; iterations++)
{
// Assign clusters
for (int k = 0; k < K; k++)
{
new_cluster_centers[k] = Vector<float>.Build.Dense(in_sects.Count, 0);
new_cluster_counts[k] = 0;
}
bool no_changes = true;
for (int p = 0; p < pixels; p++)
{
double best_dist = double.MaxValue;
int best_cluster = 0;
for (int k = 0; k < K; k++)
{
double dist = (pixels_vectors[p] - cluster_centers[k]).L2Norm();
if (dist < best_dist)
{
best_dist = dist;
best_cluster = k;
}
}
new_cluster_centers[best_cluster] += pixels_vectors[p];
new_cluster_counts[best_cluster]++;
if (pixels_cluster[p] != best_cluster)
{
no_changes = false;
pixels_cluster[p] = best_cluster;
}
}
if ((no_changes) && (iterations != 0)) // We're done here!
break;
for (int k = 0; k < K; k++)
{
if (new_cluster_counts[k] == 0) return ToolboxReturn.SpecialError; // Nothing in cluster!
cluster_centers[k] = new_cluster_centers[k] / new_cluster_counts[k];
}
if (no_changes) // We're done here!
break;
}
for (int s = 0; s < out_sects.Count; s++)
{
int p = 0;
var sect = out_sects[s];
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
sect[y, x] = cluster_centers[pixels_cluster[p++]][s];
}
return ToolboxReturn.Good;
}
}
}
}
| SnowmanTackler/SamSeifert.Utilities | SamSeifert.ComputerVision/SingleImage/KMeans.cs | C# | mit | 5,752 |
using Hangfire;
using Hangfire.Mongo;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Bson.Serialization.Options;
using MongoDB.Bson.Serialization.Serializers;
using MongoDB.Driver;
using SIL.XForge.WebApi.Server.Models;
using SIL.XForge.WebApi.Server.Models.Lexicon;
using SIL.XForge.WebApi.Server.Models.Translate;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SIL.XForge.WebApi.Server.DataAccess
{
public static class DataAccessExtensions
{
public static IRepository<T> Create<T>(this IProjectRepositoryFactory<T> factory, Project project)
where T : IEntity
{
return factory.Create(project.ProjectCode);
}
public static Task<T> UpdateAsync<T>(this IRepository<T> repo, T entity,
Func<UpdateDefinitionBuilder<T>, UpdateDefinition<T>> update, bool upsert = false) where T : IEntity
{
return repo.UpdateAsync(e => e.Id == entity.Id, update, upsert);
}
public static async Task<bool> DeleteAsync<T>(this IRepository<T> repo, T entity) where T : IEntity
{
return await repo.DeleteAsync(e => e.Id == entity.Id) != null;
}
public static IServiceCollection AddMongoDataAccess(this IServiceCollection services,
IConfiguration configuration)
{
IConfigurationSection dataAccessConfig = configuration.GetSection("DataAccess");
string connectionString = dataAccessConfig.GetValue<string>("ConnectionString");
services.AddHangfire(x => x.UseMongoStorage(connectionString, "jobs"));
BsonSerializer.RegisterDiscriminatorConvention(typeof(Project),
new HierarchicalDiscriminatorConvention("appName"));
BsonSerializer.RegisterDiscriminatorConvention(typeof(LexConfig),
new HierarchicalDiscriminatorConvention("type"));
BsonSerializer.RegisterDiscriminatorConvention(typeof(LexViewFieldConfig),
new HierarchicalDiscriminatorConvention("type"));
BsonSerializer.RegisterDiscriminatorConvention(typeof(LexTask),
new HierarchicalDiscriminatorConvention("type"));
var globalPack = new ConventionPack
{
new CamelCaseElementNameConvention(),
new ObjectRefConvention()
};
ConventionRegistry.Register("Global", globalPack, t => true);
var paratextProjectPack = new ConventionPack { new NoIdMemberConvention() };
ConventionRegistry.Register("ParatextProject", paratextProjectPack, t => t == typeof(ParatextProject));
RegisterClass<EntityBase>(cm =>
{
cm.MapIdProperty(e => e.Id)
.SetIdGenerator(StringObjectIdGenerator.Instance)
.SetSerializer(new StringSerializer(BsonType.ObjectId));
});
RegisterClass<LexConfig>(cm =>
{
cm.MapMember(lc => lc.HideIfEmpty).SetSerializer(new EmptyStringBooleanSerializer());
});
RegisterClass<LexConfigFieldList>(cm => cm.SetDiscriminator(LexConfig.FieldList));
RegisterClass<LexConfigOptionList>(cm => cm.SetDiscriminator(LexConfig.OptionList));
RegisterClass<LexConfigMultiOptionList>(cm => cm.SetDiscriminator(LexConfig.MultiOptionList));
RegisterClass<LexConfigMultiText>(cm => cm.SetDiscriminator(LexConfig.MultiText));
RegisterClass<LexConfigPictures>(cm => cm.SetDiscriminator(LexConfig.Pictures));
RegisterClass<LexConfigMultiParagraph>(cm => cm.SetDiscriminator(LexConfig.MultiParagraph));
RegisterClass<LexViewFieldConfig>(cm => cm.SetDiscriminator("basic"));
RegisterClass<LexViewMultiTextFieldConfig>(cm => cm.SetDiscriminator("multitext"));
RegisterClass<LexTask>(cm => cm.SetDiscriminator(""));
RegisterClass<LexTaskDashboard>(cm => cm.SetDiscriminator(LexTask.Dashboard));
RegisterClass<LexTaskSemdom>(cm => cm.SetDiscriminator(LexTask.Semdom));
RegisterClass<LexAuthorInfo>(cm =>
{
cm.MapMember(a => a.ModifiedByUserRef)
.SetSerializer(new StringSerializer(BsonType.ObjectId));
cm.MapMember(a => a.CreatedByUserRef)
.SetSerializer(new StringSerializer(BsonType.ObjectId));
});
RegisterClass<LexSense>(cm =>
{
cm.UnmapMember(s => s.CustomFields);
cm.UnmapMember(s => s.AuthorInfo);
cm.UnmapMember(s => s.ReversalEntries);
});
services.AddSingleton<IMongoClient>(sp => new MongoClient(connectionString));
services.AddMongoRepository<SendReceiveJob>("send_receive");
services.AddMongoRepository<User>("users", cm =>
{
cm.MapMember(u => u.SiteRole).SetSerializer(
new DictionaryInterfaceImplementerSerializer<Dictionary<string, string>>(
DictionaryRepresentation.Document, new SiteDomainSerializer(), new StringSerializer()));
cm.MapMember(u => u.Projects)
.SetSerializer(new EnumerableInterfaceImplementerSerializer<List<string>, string>(
new StringSerializer(BsonType.ObjectId)));
});
services.AddMongoRepository<Project>("projects");
services.AddMongoRepository<LexProject>("projects", cm => cm.SetDiscriminator("lexicon"));
services.AddMongoRepository<TranslateProject>("projects", cm => cm.SetDiscriminator("translate"));
services.AddMongoProjectRepositoryFactory<TranslateDocumentSet>("translate");
services.AddMongoProjectRepositoryFactory<LexEntry>("lexicon", cm =>
{
cm.UnmapMember(e => e.Environments);
cm.UnmapMember(e => e.MorphologyType);
});
return services;
}
private static void AddMongoRepository<T>(this IServiceCollection services, string collectionName,
Action<BsonClassMap<T>> setup = null) where T : IEntity
{
RegisterClass<T>(setup);
services.AddSingleton<IRepository<T>>(sp =>
new MongoRepository<T>(sp.GetService<IMongoClient>().GetDatabase("scriptureforge")
.GetCollection<T>(collectionName)));
}
private static void AddMongoProjectRepositoryFactory<T>(this IServiceCollection services, string collectionName,
Action<BsonClassMap<T>> setup = null) where T : IEntity
{
RegisterClass<T>(setup);
services.AddSingleton<IProjectRepositoryFactory<T>>(sp =>
new MongoProjectRepositoryFactory<T>(sp.GetService<IMongoClient>(), collectionName));
}
private static void RegisterClass<T>(Action<BsonClassMap<T>> setup = null)
{
BsonClassMap.RegisterClassMap<T>(cm =>
{
cm.AutoMap();
setup?.Invoke(cm);
});
}
}
}
| sillsdev/web-scriptureforge | src/netcore-api/SIL.XForge.WebApi.Server/DataAccess/DataAccessExtensions.cs | C# | mit | 7,515 |
#pragma checksum "C:\Users\Shubham Singh\Documents\Visual Studio 2013\Projects\PhoneApp1\PhoneApp1\Page1.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "40F23D24908E7D0B183979BB30966C15"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Microsoft.Phone.Controls;
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace PhoneApp1 {
public partial class Page1 : Microsoft.Phone.Controls.PhoneApplicationPage {
internal System.Windows.Controls.Grid LayoutRoot;
internal Microsoft.Phone.Controls.PhoneTextBox email;
internal Microsoft.Phone.Controls.PhoneTextBox roll;
internal System.Windows.Controls.Grid ContentPanel;
internal System.Windows.Controls.Canvas graphCanvas;
internal System.Windows.Controls.Button submit;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/PhoneApp1;component/Page1.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
this.email = ((Microsoft.Phone.Controls.PhoneTextBox)(this.FindName("email")));
this.roll = ((Microsoft.Phone.Controls.PhoneTextBox)(this.FindName("roll")));
this.ContentPanel = ((System.Windows.Controls.Grid)(this.FindName("ContentPanel")));
this.graphCanvas = ((System.Windows.Controls.Canvas)(this.FindName("graphCanvas")));
this.submit = ((System.Windows.Controls.Button)(this.FindName("submit")));
}
}
}
| rohaniitr/helpEx_Windows | PhoneApp1/obj/Debug/Page1.g.i.cs | C# | mit | 2,786 |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type UserRequest.
/// </summary>
public partial class UserRequest : BaseRequest, IUserRequest
{
/// <summary>
/// Constructs a new UserRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public UserRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified User using POST.
/// </summary>
/// <param name="userToCreate">The User to create.</param>
/// <returns>The created User.</returns>
public System.Threading.Tasks.Task<User> CreateAsync(User userToCreate)
{
return this.CreateAsync(userToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified User using POST.
/// </summary>
/// <param name="userToCreate">The User to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created User.</returns>
public async System.Threading.Tasks.Task<User> CreateAsync(User userToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<User>(userToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified User.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified User.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<User>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified User.
/// </summary>
/// <returns>The User.</returns>
public System.Threading.Tasks.Task<User> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified User.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The User.</returns>
public async System.Threading.Tasks.Task<User> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<User>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified User using PATCH.
/// </summary>
/// <param name="userToUpdate">The User to update.</param>
/// <returns>The updated User.</returns>
public System.Threading.Tasks.Task<User> UpdateAsync(User userToUpdate)
{
return this.UpdateAsync(userToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified User using PATCH.
/// </summary>
/// <param name="userToUpdate">The User to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated User.</returns>
public async System.Threading.Tasks.Task<User> UpdateAsync(User userToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<User>(userToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IUserRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IUserRequest Expand(Expression<Func<User, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IUserRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IUserRequest Select(Expression<Func<User, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="userToInitialize">The <see cref="User"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(User userToInitialize)
{
if (userToInitialize != null && userToInitialize.AdditionalData != null)
{
if (userToInitialize.OwnedDevices != null && userToInitialize.OwnedDevices.CurrentPage != null)
{
userToInitialize.OwnedDevices.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.OwnedDevices.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.RegisteredDevices != null && userToInitialize.RegisteredDevices.CurrentPage != null)
{
userToInitialize.RegisteredDevices.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.RegisteredDevices.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.DirectReports != null && userToInitialize.DirectReports.CurrentPage != null)
{
userToInitialize.DirectReports.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.DirectReports.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.MemberOf != null && userToInitialize.MemberOf.CurrentPage != null)
{
userToInitialize.MemberOf.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.MemberOf.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.CreatedObjects != null && userToInitialize.CreatedObjects.CurrentPage != null)
{
userToInitialize.CreatedObjects.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.CreatedObjects.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.OwnedObjects != null && userToInitialize.OwnedObjects.CurrentPage != null)
{
userToInitialize.OwnedObjects.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.OwnedObjects.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.Messages != null && userToInitialize.Messages.CurrentPage != null)
{
userToInitialize.Messages.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.Messages.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.MailFolders != null && userToInitialize.MailFolders.CurrentPage != null)
{
userToInitialize.MailFolders.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.MailFolders.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.Calendars != null && userToInitialize.Calendars.CurrentPage != null)
{
userToInitialize.Calendars.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.Calendars.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.CalendarGroups != null && userToInitialize.CalendarGroups.CurrentPage != null)
{
userToInitialize.CalendarGroups.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.CalendarGroups.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.CalendarView != null && userToInitialize.CalendarView.CurrentPage != null)
{
userToInitialize.CalendarView.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.CalendarView.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.Events != null && userToInitialize.Events.CurrentPage != null)
{
userToInitialize.Events.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.Events.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.Contacts != null && userToInitialize.Contacts.CurrentPage != null)
{
userToInitialize.Contacts.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.Contacts.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
if (userToInitialize.ContactFolders != null && userToInitialize.ContactFolders.CurrentPage != null)
{
userToInitialize.ContactFolders.AdditionalData = userToInitialize.AdditionalData;
object nextPageLink;
userToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
userToInitialize.ContactFolders.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| garethj-msft/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/UserRequest.cs | C# | mit | 18,848 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace TestsFinal.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null) {
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) {
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null) {
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| troyman1289/TestsInXamarin | TestsFinal/TestsFinal/TestsFinal.UWP/App.xaml.cs | C# | mit | 3,992 |
using System;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VsSDK.IntegrationTestLibrary;
using Microsoft.VSSDK.Tools.VsIdeTesting;
namespace VSConsole.PowerPack_IntegrationTests
{
[TestClass()]
public class ToolWindowTest
{
private delegate void ThreadInvoker();
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
/// <summary>
///A test for showing the toolwindow
///</summary>
[TestMethod()]
[HostType("VS IDE")]
public void ShowToolWindow()
{
UIThreadInvoker.Invoke((ThreadInvoker)delegate()
{
CommandID toolWindowCmd = new CommandID(DevlinLiles.VSConsole_PowerPack.GuidList.guidVSConsole_PowerPackCmdSet, (int)DevlinLiles.VSConsole_PowerPack.PkgCmdIDList.cmdidPowerPackVsConsole);
TestUtils testUtils = new TestUtils();
testUtils.ExecuteCommand(toolWindowCmd);
Assert.IsTrue(testUtils.CanFindToolwindow(new Guid(DevlinLiles.VSConsole_PowerPack.GuidList.guidToolWindowPersistanceString)));
});
}
}
}
| DevlinLiles/VSConsole.PowerPack | VSConsole.PowerPack/VSConsole.PowerPack_IntegrationTests/ToolWindowTest.cs | C# | mit | 1,691 |
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("LightClaw.Engine")]
[assembly: AssemblyProduct("LightClaw.Engine")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyDescription("The core library of the LightClaw engine.")]
[assembly: AssemblyCompany("LightClaw")]
[assembly: AssemblyCopyright("Copyright 2014 © LightClaw Development Team")]
[assembly: AssemblyTrademark("LightClaw")]
[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(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("37a39a9e-248f-4f2c-854b-d7d905b4a079")]
// 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")]
[assembly: CLSCompliant(true)]
| LightClaw/Engine | Source/Core/LightClaw.Engine/Properties/AssemblyInfo.cs | C# | mit | 1,538 |
/*
* NotImplementedException.cs - Implementation of the
* "System.NotImplementedException" class.
*
* Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System
{
// Strictly speaking, "NotImplementedException" is not defined
// by the ECMA library specification. However, other parts of
// the ECMA specification rely upon its presence.
using System.Runtime.Serialization;
public class NotImplementedException : SystemException
{
// Constructors.
public NotImplementedException()
: base(_("Exception_NotImplemented")) {}
public NotImplementedException(String msg)
: base(msg) {}
public NotImplementedException(String msg, Exception inner)
: base(msg, inner) {}
#if CONFIG_SERIALIZATION
protected NotImplementedException(SerializationInfo info,
StreamingContext context)
: base(info, context) {}
#endif
// Get the default message to use for this exception type.
internal override String MessageDefault
{
get
{
return _("Exception_NotImplemented");
}
}
// Get the default HResult value for this type of exception.
internal override uint HResultDefault
{
get
{
return 0x80004001;
}
}
}; // class NotImplementedException
}; // namespace System
| jjenki11/blaze-chem-rendering | qca_designer/lib/pnetlib-0.8.0/runtime/System/NotImplementedException.cs | C# | mit | 1,969 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Charlotte.Tools
{
public static class ReflectTools
{
public class FieldUnit
{
public FieldInfo Value;
public FieldUnit(FieldInfo value)
{
this.Value = value;
}
/// <summary>
/// static フィールド 取得
/// </summary>
/// <returns></returns>
public object GetValue()
{
return this.Value.GetValue(null);
}
/// <summary>
/// インスタンス フィールド 取得
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public object GetValue(object instance)
{
return this.Value.GetValue(instance);
}
/// <summary>
/// static フィールド 設定
/// </summary>
/// <param name="value"></param>
public void SetValue(object value)
{
this.Value.SetValue(null, value);
}
/// <summary>
/// インスタンス フィールド 設定
/// </summary>
/// <param name="instance"></param>
/// <param name="value"></param>
public void SetValue(object instance, object value)
{
this.Value.SetValue(instance, value);
}
}
public class PropertyUnit
{
public PropertyInfo Value;
public PropertyUnit(PropertyInfo value)
{
this.Value = value;
}
/// <summary>
/// static プロパティ 取得
/// </summary>
/// <returns></returns>
public object GetValue()
{
try
{
return this.Value.GetValue(null, null);
}
catch
{
return null; // getter無し || 配列 || etc.
}
}
/// <summary>
/// インスタンス プロパティ 取得
/// </summary>
/// <param name="instance"></param>
/// <returns></returns>
public object GetValue(object instance)
{
try
{
return this.Value.GetValue(instance, null);
}
catch
{
return null; // getter無し || 配列 || etc.
}
}
/// <summary>
/// static プロパティ 設定
/// </summary>
/// <param name="value"></param>
public void SetValue(object value)
{
try
{
this.Value.SetValue(null, value, null);
}
catch
{
// setter無し || 配列 || etc.
}
}
/// <summary>
/// インスタンス プロパティ 設定
/// </summary>
/// <param name="instance"></param>
/// <param name="value"></param>
public void SetValue(object instance, object value)
{
try
{
this.Value.SetValue(instance, value, null);
}
catch
{
// setter無し || 配列 || etc.
}
}
}
public class MethodUnit
{
public MethodBase Value; // MethodInfo | ConstructorInfo
public MethodUnit(MethodBase value)
{
this.Value = value;
}
public ParameterType[] GetParameterTypes()
{
return this.Value.GetParameters().Select<ParameterInfo, ParameterType>(prmType => new ParameterType(prmType)).ToArray();
}
/// <summary>
/// invoke static method
/// </summary>
/// <param name="prms"></param>
/// <returns></returns>
public object Invoke(object[] prms)
{
return this.Value.Invoke(null, prms);
}
/// <summary>
/// invoke instance method
/// </summary>
/// <param name="instance"></param>
/// <param name="prms"></param>
/// <returns></returns>
public object Invoke(object instance, object[] prms)
{
return this.Value.Invoke(instance, prms);
}
/// <summary>
/// invoke constructor
/// </summary>
/// <param name="prms"></param>
/// <returns></returns>
public object Construct(object[] prms)
{
return ((ConstructorInfo)this.Value).Invoke(prms);
}
}
public class ParameterType
{
public ParameterInfo Value;
public ParameterType(ParameterInfo value)
{
this.Value = value;
}
}
public static FieldUnit[] GetFieldsByInstance(object instance)
{
return GetFields(instance.GetType());
}
public static PropertyUnit[] GetPropertiesByInstance(object instance)
{
return GetProperties(instance.GetType());
}
public static FieldUnit GetFieldByInstance(object instance, string name)
{
return GetField(instance.GetType(), name);
}
public static PropertyUnit GetPropertyByInstance(object instance, string name)
{
return GetProperty(instance.GetType(), name);
}
/// <summary>
/// 親クラスの private, private static を取得出来ない模様。現状名前が被った場合を考慮していないので、このままにする。
/// </summary>
private const BindingFlags _bindingFlags =
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.FlattenHierarchy;
public static FieldUnit[] GetFields(Type type)
{
return type.GetFields(_bindingFlags).Select<FieldInfo, FieldUnit>(field => new FieldUnit(field)).ToArray();
}
public static PropertyUnit[] GetProperties(Type type)
{
return type.GetProperties(_bindingFlags).Select<PropertyInfo, PropertyUnit>(prop => new PropertyUnit(prop)).ToArray();
}
public static FieldUnit GetField(Type type, string name) // ret: null == not found
{
FieldInfo field = type.GetField(name, _bindingFlags);
if (field == null)
return null;
return new FieldUnit(field);
}
public static PropertyUnit GetProperty(Type type, string name)
{
PropertyInfo prop = type.GetProperty(name, _bindingFlags);
if (prop == null)
return null;
return new PropertyUnit(prop);
}
public static bool Equals(FieldUnit a, Type b)
{
return Equals(a.Value.FieldType, b);
}
public static bool Equals(Type a, Type b)
{
return a.ToString() == b.ToString();
}
public static bool EqualsOrBase(FieldUnit a, Type b)
{
return EqualsOrBase(a.Value.FieldType, b);
}
public static bool EqualsOrBase(Type a, Type b) // ret: ? a == b || a は b を継承している。
{
foreach (Type ai in a.GetInterfaces())
if (Equals(ai, b))
return true;
do
{
if (Equals(a, b))
return true;
a = a.BaseType;
}
while (a != null);
return false;
}
public static bool IsList(Type type)
{
try
{
return typeof(List<>).IsAssignableFrom(type.GetGenericTypeDefinition());
}
catch
{
return false; // ジェネリック型じゃない || etc.
}
}
public static MethodUnit[] GetMethodsByInstance(object instance)
{
return GetMethods(instance.GetType());
}
public static MethodUnit[] GetMethods(Type type)
{
return type.GetMethods(_bindingFlags).Select<MethodInfo, MethodUnit>(method => new MethodUnit(method)).ToArray();
}
public static MethodUnit GetMethod(Type type, Predicate<MethodUnit> match)
{
MethodUnit[] ret = GetMethods(type).Where(method => match(method)).ToArray();
if (ret.Length == 0)
throw new Exception("メソッドが見つかりません。");
return ret[0];
}
public static MethodUnit GetMethod(Type type, string name)
{
return GetMethod(type, method => name == method.Value.Name);
}
public static MethodUnit GetMethod(Type type, string name, object[] prms)
{
return GetMethod(type, method => name == method.Value.Name && CheckParameters(prms, method.GetParameterTypes()));
}
public static MethodUnit[] GetConstructorsByInstance(object instance)
{
return GetConstructors(instance.GetType());
}
public static MethodUnit[] GetConstructors(Type type)
{
return type.GetConstructors(_bindingFlags).Select<ConstructorInfo, MethodUnit>(ctor => new MethodUnit(ctor)).ToArray();
}
public static MethodUnit GetConstructor(Type type, Predicate<MethodUnit> match)
{
MethodUnit[] ret = GetConstructors(type).Where(method => match(method)).ToArray();
if (ret.Length == 0)
throw new Exception("コンストラクタが見つかりません。");
return ret[0];
}
public static MethodUnit GetConstructor(Type type)
{
return GetConstructor(type, ctor => true);
}
public static MethodUnit GetConstructor(Type type, object[] prms)
{
return GetConstructor(type, ctor => CheckParameters(prms, ctor.GetParameterTypes()));
}
public static bool CheckParameters(object[] prms, ParameterType[] prmTypes)
{
return prms.Length == prmTypes.Length; // HACK
}
}
}
| stackprobe/CSharp | Chocolate/Chocolate/Tools/ReflectTools.cs | C# | mit | 8,290 |
using System;
using System.Diagnostics.Contracts;
using System.Windows.Forms;
using WinFormsOpenFileDialog = System.Windows.Forms.OpenFileDialog;
namespace WinFormsMvvm.DialogService.FrameworkDialogs.OpenFile
{
/// <summary>
/// Class wrapping System.Windows.Forms.OpenFileDialog, making it accept a IOpenFileDialog.
/// </summary>
public class OpenFileDialog : IDisposable
{
private IOpenFileDialog openFileDialog;
private WinFormsOpenFileDialog concreteOpenFileDialog;
/// <summary>
/// Initializes a new instance of the <see cref="OpenFileDialog"/> class.
/// </summary>
/// <param name="openFileDialog">The interface of a open file dialog.</param>
public OpenFileDialog(IOpenFileDialog openFileDialog)
{
}
/// <summary>
/// Runs a common dialog box with the specified owner.
/// </summary>
/// <param name="owner">
/// Any object that implements System.Windows.Forms.IWin32Window that represents the top-level
/// window that will own the modal dialog box.
/// </param>
/// <returns>
/// System.Windows.Forms.DialogResult.OK if the user clicks OK in the dialog box; otherwise,
/// System.Windows.Forms.DialogResult.Cancel.
/// </returns>
public DialogResult ShowDialog(IOpenFileDialog openFile)
{
this.openFileDialog = openFile;
// Create concrete OpenFileDialog
concreteOpenFileDialog = new WinFormsOpenFileDialog
{
AddExtension = openFileDialog.AddExtension,
CheckFileExists = openFileDialog.CheckFileExists,
CheckPathExists = openFileDialog.CheckPathExists,
DefaultExt = openFileDialog.DefaultExt,
FileName = openFileDialog.FileName,
Filter = openFileDialog.Filter,
InitialDirectory = openFileDialog.InitialDirectory,
Multiselect = openFileDialog.Multiselect,
Title = openFileDialog.Title
};
DialogResult result = concreteOpenFileDialog.ShowDialog();
// Update ViewModel
openFileDialog.FileName = concreteOpenFileDialog.FileName;
openFileDialog.FileNames = concreteOpenFileDialog.FileNames;
return result;
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting
/// unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~OpenFileDialog()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (concreteOpenFileDialog != null)
{
concreteOpenFileDialog.Dispose();
concreteOpenFileDialog = null;
}
}
}
#endregion
}
}
| austriapro/ebinterface-word-plugin | eRechnungWordPlugIn/WinFormsMvvm/DialogService/FrameworkDialogs/OpenFile/OpenFileDialog.cs | C# | mit | 2,744 |
//-----------------------------------------------------------------------------
//
// <copyright file="CompressionOption.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// CompressionOption enumeration is used as an aggregate mechanism to give users controls
// over Compression features.
//
// History:
// 07/14/2004: IgorBel: Initial creation. [Stubs Only]
//
//-----------------------------------------------------------------------------
namespace System.IO.Packaging
{
/// <summary>
/// This class is used to control Compression for package parts.
/// </summary>
public enum CompressionOption : int
{
/// <summary>
/// Compression is turned off in this mode.
/// </summary>
NotCompressed = -1,
/// <summary>
/// Compression is optimized for a resonable compromise between size and performance.
/// </summary>
Normal = 0,
/// <summary>
/// Compression is optimized for size.
/// </summary>
Maximum = 1,
/// <summary>
/// Compression is optimized for performance.
/// </summary>
Fast = 2 ,
/// <summary>
/// Compression is optimized for super performance.
/// </summary>
SuperFast = 3,
}
}
| mind0n/hive | Cache/Libs/net46/wpf/src/Base/System/IO/Packaging/CompressionOption.cs | C# | mit | 1,462 |
using CacheCowDemo.Common;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CacheCowDemo.Api.App
{
public class Db
{
private static readonly ICollection<Contact> contacts = new List<Contact>();
public IEnumerable<Contact> GetContacts(Func<IEnumerable<Contact>, IEnumerable<Contact>> query = null)
{
if (query != null)
{
return query(contacts);
}
return contacts;
}
public Contact GetContact(int id)
{
return contacts.FirstOrDefault(c => c.Id == id);
}
public void Store(Contact contact)
{
contact.Id = GetNextId();
contacts.Add(contact);
}
public void Delete(int id)
{
var contact = contacts.FirstOrDefault(c => c.Id == id);
if (contact != null)
{
contacts.Remove(contact);
}
}
private int GetNextId()
{
return contacts.Any() ? (contacts.Max(c => c.Id) + 1) : 1;
}
}
} | benfoster/CacheCowDemo | CacheCowDemo.Api/App/Db.cs | C# | mit | 1,134 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MentorGroup
{
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>();
string input = Console.ReadLine();
while (input != "end of dates")
{
string[] arguments = input.Split(' ');
bool existingStudent = false;
string studentName = arguments[0];
foreach (Student student1 in students)
{
if (student1.Name == studentName)
{
existingStudent = true;
if (arguments.Length > 1)
{
string[] dates = arguments[1].Split(',');
foreach (string date in dates)
{
student1.Attendances.Add(DateTime.ParseExact(date, "dd/MM/yyyy",
CultureInfo.InvariantCulture));
}
}
}
}
if (!existingStudent)
{
Student student = new Student();
student.Attendances = new List<DateTime>();
student.Comments = new List<string>();
student.Name = studentName;
if (arguments.Length > 1)
{
string[] dates = arguments[1].Split(',');
foreach (string date in dates)
{
student.Attendances.Add(DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture));
}
}
students.Add(student);
}
input = Console.ReadLine();
}
input = Console.ReadLine();
while (input != "end of comments")
{
string[] arguments = input.Split('-');
string studentName = arguments[0];
if (arguments.Length > 1)
{
string comment = arguments[1];
foreach (Student student in students)
{
if (student.Name == studentName)
{
student.Comments.Add(comment);
}
}
}
input = Console.ReadLine();
}
foreach (Student student in students.OrderBy(x => x.Name))
{
Console.WriteLine(student.Name);
Console.WriteLine("Comments:");
foreach (string comment in student.Comments)
{
Console.WriteLine($"- {comment}");
}
Console.WriteLine("Dates attended:");
foreach (DateTime attendance in student.Attendances.OrderBy(x => x.Date))
{
Console.WriteLine($"-- {attendance.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)}");
}
}
}
}
class Student
{
public string Name { get; set; }
public List<string> Comments { get; set; }
public List<DateTime> Attendances { get; set; }
}
}
| MinorGlitch/Programming-Fundamentals | Objects and Classes - Exercises/MentorGroup/Program.cs | C# | mit | 3,567 |
using UnityEngine;
using System.Collections;
/**
* class FreeFly: Gives keyboard control to the user to move the main camera around.
* Public variables control speed and sensitivity
*/
[AddComponentMenu("Camera-Control/Mouse Look")]
public class FreeFly : MonoBehaviour {
/* Public Declarations */
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 15F;
public float sensitivityY = 15F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -60F;
public float maximumY = 60F;
public float moveSpeed = 10;
public bool rightClick = false;
/* Private Declarations */
float rotationY = 0F;
/**
* Default Update function, run every frame. Detects user keyboard input and moves the camera accordingly
* Params: None
* Returns: void
*/
void Update ()
{
if (Input.GetKeyDown(KeyCode.Q)) {
rightClick = !rightClick;
}
if (Input.GetKeyDown (KeyCode.W) || Input.GetKey (KeyCode.W)) {
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
if (Input.GetKeyDown (KeyCode.S) || Input.GetKey (KeyCode.S)) {
transform.Translate (Vector3.back * moveSpeed * Time.deltaTime);
}
if (Input.GetKeyDown (KeyCode.A) || Input.GetKey (KeyCode.A)) {
transform.Translate (Vector3.left * moveSpeed * Time.deltaTime);
}
if (Input.GetKeyDown (KeyCode.D) || Input.GetKey (KeyCode.D)) {
transform.Translate (Vector3.right * moveSpeed * Time.deltaTime);
}
if (rightClick) {
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
}
}
/**
* Default Start function, run at the initialisation of this object. Sets the object to not rotate
* Params: None
* Returns: void
*/
void Start ()
{
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
} | craigknott/Unity3D_OpenBadges | Scripts/Movement/FreeFly.cs | C# | mit | 2,533 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a Codezu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace Mozu.Api.Urls.Platform
{
public partial class TenantDataUrl
{
/// <summary>
/// Get Resource Url for GetDBValue
/// </summary>
/// <param name="dbEntryQuery">The database entry string to create.</param>
/// <param name="responseFields">Use this field to include those fields which are not included by default.</param>
/// <returns>
/// String - Resource Url
/// </returns>
public static MozuUrl GetDBValueUrl(string dbEntryQuery, string responseFields = null)
{
var url = "/api/platform/tenantdata/{*dbEntryQuery}?responseFields={responseFields}";
var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
mozuUrl.FormatUrl( "dbEntryQuery", dbEntryQuery);
mozuUrl.FormatUrl( "responseFields", responseFields);
return mozuUrl;
}
/// <summary>
/// Get Resource Url for CreateDBValue
/// </summary>
/// <param name="dbEntryQuery">The database entry string to create.</param>
/// <returns>
/// String - Resource Url
/// </returns>
public static MozuUrl CreateDBValueUrl(string dbEntryQuery)
{
var url = "/api/platform/tenantdata/{*dbEntryQuery}";
var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
mozuUrl.FormatUrl( "dbEntryQuery", dbEntryQuery);
return mozuUrl;
}
/// <summary>
/// Get Resource Url for UpdateDBValue
/// </summary>
/// <param name="dbEntryQuery">The database entry string to create.</param>
/// <returns>
/// String - Resource Url
/// </returns>
public static MozuUrl UpdateDBValueUrl(string dbEntryQuery)
{
var url = "/api/platform/tenantdata/{*dbEntryQuery}";
var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
mozuUrl.FormatUrl( "dbEntryQuery", dbEntryQuery);
return mozuUrl;
}
/// <summary>
/// Get Resource Url for DeleteDBValue
/// </summary>
/// <param name="dbEntryQuery">The database entry string to create.</param>
/// <returns>
/// String - Resource Url
/// </returns>
public static MozuUrl DeleteDBValueUrl(string dbEntryQuery)
{
var url = "/api/platform/tenantdata/{*dbEntryQuery}";
var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
mozuUrl.FormatUrl( "dbEntryQuery", dbEntryQuery);
return mozuUrl;
}
}
}
| ezekielthao/mozu-dotnet | Mozu.Api/Urls/Platform/TenantDataUrl.cs | C# | mit | 2,863 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rainbow.Diff;
using Rainbow.Filtering;
using Rainbow.Model;
using Sitecore;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Pipelines.Save;
using Unicorn.Configuration;
using Unicorn.Data;
using Unicorn.Predicates;
using ItemData = Rainbow.Storage.Sc.ItemData;
namespace Unicorn.UI.Pipelines.SaveUi
{
/// <summary>
/// Provides a saveUI pipeline implementation to prevent unintentionally overwriting a changed serialized item on disk.
///
/// For example, if user A changes an item, then user B pulls that change from SCM but does not sync it into Sitecore,
/// then user B changes that item, without this handler user A's changes would be overwritten.
///
/// This handler verifies that the pre-save state of the item matches the field values present in the serialized item on disk (if it's present).
/// If they dont match a sheer warning is shown.
/// </summary>
/// <remarks>
/// Note that this solution does NOT save you from every possible conflict situation. Some saves do not run the saveUI pipeline, for example:
/// - Renaming any item
/// - Moving items
/// - Changing template field values (source, type) in the template builder
///
/// This handler is here to attempt to keep you from shooting yourself in the foot, but you really need to sync Unicorn after every update pulled from SCM.
/// </remarks>
public class SerializationConflictProcessor : SaveUiConfirmProcessor
{
private readonly IConfiguration[] _configurations;
public SerializationConflictProcessor()
: this(UnicornConfigurationManager.Configurations)
{
}
protected SerializationConflictProcessor(IConfiguration[] configurations)
{
_configurations = configurations;
}
protected override string GetDialogText(SaveArgs args)
{
var results = new Dictionary<Item, IList<string>>();
foreach (var item in args.Items)
{
// we grab the existing item from the database. This will NOT include the changed values we're saving.
// this is because we want to verify that the base state of the item matches serialized, NOT the state we're saving.
// if the base state and the serialized state match we can be pretty sure that the changes we are writing won't clobber anything serialized but not synced
Item existingItem = Client.ContentDatabase.GetItem(item.ID, item.Language, item.Version);
Assert.IsNotNull(existingItem, "Existing item {0} did not exist! This should never occur.", item.ID);
var existingSitecoreItem = new ItemData(existingItem);
foreach (var configuration in _configurations)
{
// ignore conflicts on items that Unicorn is not managing
if (!configuration.Resolve<IPredicate>().Includes(existingSitecoreItem).IsIncluded) continue;
IItemData serializedItemData = configuration.Resolve<ITargetDataStore>().GetByPathAndId(existingSitecoreItem.Path, existingSitecoreItem.Id, existingSitecoreItem.DatabaseName);
// not having an existing serialized version means no possibility of conflict here
if (serializedItemData == null) continue;
var fieldFilter = configuration.Resolve<IFieldFilter>();
var itemComparer = configuration.Resolve<IItemComparer>();
var fieldIssues = GetFieldSyncStatus(existingSitecoreItem, serializedItemData, fieldFilter, itemComparer);
if (fieldIssues.Count == 0) continue;
results[existingItem] = fieldIssues;
}
}
// no problems
if (results.Count == 0) return null;
var sb = new StringBuilder();
if (About.Version.StartsWith("7") || About.Version.StartsWith("6"))
{
// older Sitecores used \n to format dialog text
sb.Append("CRITICAL MESSAGE FROM UNICORN:\n");
sb.Append("You need to run a Unicorn sync. The following fields did not match the serialized version:\n");
foreach (var item in results)
{
if (results.Count > 1)
sb.AppendFormat("\n{0}: {1}", item.Key.DisplayName, string.Join(", ", item.Value));
else
sb.AppendFormat("\n{0}", string.Join(", ", item.Value));
}
sb.Append("\n\nDo you want to overwrite anyway?\nTHIS MAY CAUSE LOST WORK.");
}
else
{
// Sitecore 8.x+ uses HTML to format dialog text
sb.Append("<p style=\"font-weight: bold; margin-bottom: 1em;\">CRITICAL MESSAGE FROM UNICORN:</p>");
sb.Append("<p>You need to run a Unicorn sync. The following fields did not match the serialized version:</p><ul style=\"margin: 1em 0\">");
foreach (var item in results)
{
if (results.Count > 1)
sb.AppendFormat("<li>{0}: {1}</li>", item.Key.DisplayName, string.Join(", ", item.Value));
else
sb.AppendFormat("<li>{0}</li>", string.Join(", ", item.Value));
}
sb.Append("</ul><p>Do you want to overwrite anyway?<br>THIS MAY CAUSE LOST WORK.</p>");
}
return sb.ToString();
}
private IList<string> GetFieldSyncStatus(IItemData itemData, IItemData serializedItemData, IFieldFilter fieldFilter, IItemComparer itemComparer)
{
var comparison = itemComparer.Compare(new FilteredItem(itemData, fieldFilter), new FilteredItem(serializedItemData, fieldFilter));
var db = Factory.GetDatabase(itemData.DatabaseName);
var changedFields = comparison.ChangedSharedFields
.Concat(comparison.ChangedVersions.SelectMany(version => version.ChangedFields))
.Select(field => db.GetItem(new ID((field.SourceField ?? field.TargetField).FieldId)))
.Where(field => field != null)
.Select(field => field.DisplayName)
.ToList();
if (comparison.IsMoved) changedFields.Add("Item has been moved");
if (comparison.IsRenamed) changedFields.Add("Item has been renamed");
if (comparison.IsTemplateChanged) changedFields.Add("Item's template has changed");
if (comparison.ChangedVersions.Any(version => version.SourceVersion == null || version.TargetVersion == null)) changedFields.Add("Item versions do not match");
return changedFields;
}
}
}
| GuitarRich/Unicorn | src/Unicorn/UI/Pipelines/SaveUi/SerializationConflictProcessor.cs | C# | mit | 6,041 |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Question : MonoBehaviour
{
[SerializeField]
private List<GameObject>questionsMarks = new List<GameObject>( );
[SerializeField]
private GameObject gui;
[SerializeField]
private GameObject wrong;
[SerializeField]
private GameObject right;
private int selectedAnswer;
public int rightAnswer;
void SelectAnswer( )
{
for ( int i = 0; i < questionsMarks.Count; i++ )
{
questionsMarks[ i ].renderer.enabled = false;
}
}
void ConfirmAnswer()
{
for ( int i = 0; i < questionsMarks.Count; i++ )
{
if ( questionsMarks[ i ].renderer.enabled )
{
selectedAnswer = i;
if ( selectedAnswer == rightAnswer )
{
this.gameObject.SetActive( false );
Time.timeScale = 1;
gui.SetActive( true );
right.SetActive( true );
Debug.Log( "certa" );
}
else
{
this.gameObject.SetActive( false );
Time.timeScale = 1;
GameManager.Instance.GrowTime( );
gui.SetActive( true );
wrong.SetActive( true );
Debug.Log( "errada" );
}
}
}
}
}
| arnaldoccn/diabetes-speed-race | Assets/Scripts/Questions/Question.cs | C# | mit | 1,490 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
namespace ASP.NETWebForms.Account
{
public partial class ManageLogins : System.Web.UI.Page
{
protected string SuccessMessage
{
get;
private set;
}
protected bool CanRemoveExternalLogins
{
get;
private set;
}
private bool HasPassword(ApplicationUserManager manager)
{
return manager.HasPassword(User.Identity.GetUserId());
}
protected void Page_Load(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;
SuccessMessage = String.Empty;
successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
}
public IEnumerable<UserLoginInfo> GetLogins()
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var accounts = manager.GetLogins(User.Identity.GetUserId());
CanRemoveExternalLogins = accounts.Count() > 1 || HasPassword(manager);
return accounts;
}
public void RemoveLogin(string loginProvider, string providerKey)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
var result = manager.RemoveLogin(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
string msg = String.Empty;
if (result.Succeeded)
{
var user = manager.FindById(User.Identity.GetUserId());
signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
msg = "?m=RemoveLoginSuccess";
}
Response.Redirect("~/Account/ManageLogins" + msg);
}
}
} | todor-enikov/TelerikAcademy | ASP .NET Web Forms/1.Introduction to ASP.NET/1.Few Web applications/ASP.NETWebForms/Account/ManageLogins.aspx.cs | C# | mit | 2,201 |
/*
* Copyright (c) 2014 Håkan Edling
*
* See the file LICENSE for copying permission.
*/
using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Goldfish.Tests
{
/// <summary>
/// Integration tests for the author repository.
/// </summary>
[TestClass]
public class AuthorTests
{
public AuthorTests() {
App.Init();
}
[TestMethod, TestCategory("Repositories")]
public async Task AuthorRepository() {
var id = Guid.Empty;
// Insert author
using (var api = new Api()) {
var author = new Models.Author() {
Name = "John Doe",
Email = "[email protected]"
};
api.Authors.Add(author);
Assert.AreEqual(author.Id.HasValue, true);
Assert.IsTrue(api.SaveChanges() > 0);
id = author.Id.Value;
}
// Get by id
using (var api = new Api()) {
var author = await api.Authors.GetByIdAsync(id);
Assert.IsNotNull(author);
Assert.AreEqual(author.Name, "John Doe");
}
// Update param
using (var api = new Api()) {
var author = await api.Authors.GetByIdAsync(id);
Assert.IsNotNull(author);
author.Name = "John Moe";
api.Authors.Add(author);
Assert.IsTrue(api.SaveChanges() > 0);
}
// Get by id
using (var api = new Api()) {
var author = await api.Authors.GetByIdAsync(id);
Assert.IsNotNull(author);
Assert.AreEqual(author.Name, "John Moe");
}
// Remove author
using (var api = new Api()) {
api.Authors.Remove(id);
Assert.IsTrue(api.SaveChanges() > 0);
}
// Remove system param
using (var api = new Api()) {
var param = api.Params.GetByInternalId("ARCHIVE_PAGE_SIZE");
try {
api.Params.Remove(param);
// The above statement should throw an exception and this
// this assertion should not be reached.
Assert.IsTrue(false);
} catch (Exception ex) {
Assert.IsTrue(ex is UnauthorizedAccessException);
}
}
}
}
}
| ravindranathw/Goldfish | Core/Goldfish.Tests/AuthorTests.cs | C# | mit | 2,048 |
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("02.Stateless")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.Stateless")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2bfc188e-46d2-4a67-95b2-a8732dd9ca8a")]
// 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")]
| toteva94/SoftUni | [01]ProgrammingFundamentals/25.StringsAndTextProcessing-MoreExercises/02.Stateless/Properties/AssemblyInfo.cs | C# | mit | 1,400 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
namespace Azure.Search.Documents.Indexes.Models
{
/// <summary> Matches single or multi-word synonyms in a token stream. This token filter is implemented using Apache Lucene. </summary>
public partial class SynonymTokenFilter : TokenFilter
{
/// <summary> Initializes a new instance of SynonymTokenFilter. </summary>
/// <param name="name"> The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. </param>
/// <param name="synonyms"> A list of synonyms in following one of two formats: 1. incredible, unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma separated list of equivalent words. Set the expand option to change how this list is interpreted. </param>
public SynonymTokenFilter(string name, IEnumerable<string> synonyms) : base(name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (synonyms == null)
{
throw new ArgumentNullException(nameof(synonyms));
}
Synonyms = synonyms.ToArray();
ODataType = "#Microsoft.Azure.Search.SynonymTokenFilter";
}
/// <summary> Initializes a new instance of SynonymTokenFilter. </summary>
/// <param name="oDataType"> Identifies the concrete type of the token filter. </param>
/// <param name="name"> The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. </param>
/// <param name="synonyms"> A list of synonyms in following one of two formats: 1. incredible, unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma separated list of equivalent words. Set the expand option to change how this list is interpreted. </param>
/// <param name="ignoreCase"> A value indicating whether to case-fold input for matching. Default is false. </param>
/// <param name="expand"> A value indicating whether all words in the list of synonyms (if => notation is not used) will map to one another. If true, all words in the list of synonyms (if => notation is not used) will map to one another. The following list: incredible, unbelievable, fabulous, amazing is equivalent to: incredible, unbelievable, fabulous, amazing => incredible, unbelievable, fabulous, amazing. If false, the following list: incredible, unbelievable, fabulous, amazing will be equivalent to: incredible, unbelievable, fabulous, amazing => incredible. Default is true. </param>
internal SynonymTokenFilter(string oDataType, string name, IList<string> synonyms, bool? ignoreCase, bool? expand) : base(oDataType, name)
{
Synonyms = synonyms;
IgnoreCase = ignoreCase;
Expand = expand;
ODataType = oDataType ?? "#Microsoft.Azure.Search.SynonymTokenFilter";
}
/// <summary> A list of synonyms in following one of two formats: 1. incredible, unbelievable, fabulous => amazing - all terms on the left side of => symbol will be replaced with all terms on its right side; 2. incredible, unbelievable, fabulous, amazing - comma separated list of equivalent words. Set the expand option to change how this list is interpreted. </summary>
public IList<string> Synonyms { get; set; }
/// <summary> A value indicating whether to case-fold input for matching. Default is false. </summary>
public bool? IgnoreCase { get; set; }
/// <summary> A value indicating whether all words in the list of synonyms (if => notation is not used) will map to one another. If true, all words in the list of synonyms (if => notation is not used) will map to one another. The following list: incredible, unbelievable, fabulous, amazing is equivalent to: incredible, unbelievable, fabulous, amazing => incredible, unbelievable, fabulous, amazing. If false, the following list: incredible, unbelievable, fabulous, amazing will be equivalent to: incredible, unbelievable, fabulous, amazing => incredible. Default is true. </summary>
public bool? Expand { get; set; }
}
}
| hyonholee/azure-sdk-for-net | sdk/search/Azure.Search.Documents/src/Generated/Models/SynonymTokenFilter.cs | C# | mit | 4,785 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace DiceBot
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new cLogin());
Application.Run(new cDiceBot(args));
}
catch (Exception e)
{
try
{
using (StreamWriter sw = File.AppendText("DICEBOTLOG.txt"))
{
sw.WriteLine("########################################################################################\r\n\r\nFATAL CRASH\r\n");
sw.WriteLine(e.ToString());
sw.WriteLine("########################################################################################");
}
}
catch { }
throw e;
}
}
}
}
| Seuntjie900/DiceBot | DiceBot/Program.cs | C# | mit | 1,288 |
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Transforms;
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Osu.Objects.Drawables.Pieces;
using OpenTK;
namespace osu.Game.Modes.Osu.Objects.Drawables
{
public class DrawableHitCircle : DrawableOsuHitObject, IDrawableHitObjectWithProxiedApproach
{
private OsuHitObject osuObject;
public ApproachCircle ApproachCircle;
private CirclePiece circle;
private RingPiece ring;
private FlashPiece flash;
private ExplodePiece explode;
private NumberPiece number;
private GlowPiece glow;
public DrawableHitCircle(OsuHitObject h) : base(h)
{
Origin = Anchor.Centre;
osuObject = h;
Position = osuObject.StackedPosition;
Scale = new Vector2(osuObject.Scale);
Children = new Drawable[]
{
glow = new GlowPiece
{
Colour = osuObject.Colour
},
circle = new CirclePiece
{
Colour = osuObject.Colour,
Hit = () =>
{
if (Judgement.Result.HasValue) return false;
((PositionalJudgementInfo)Judgement).PositionOffset = Vector2.Zero; //todo: set to correct value
UpdateJudgement(true);
return true;
},
},
number = new NumberPiece()
{
Text = h is Spinner ? "S" : (HitObject.ComboIndex + 1).ToString(),
},
ring = new RingPiece(),
flash = new FlashPiece(),
explode = new ExplodePiece
{
Colour = osuObject.Colour,
},
ApproachCircle = new ApproachCircle()
{
Colour = osuObject.Colour,
}
};
//may not be so correct
Size = circle.DrawSize;
}
double hit50 = 150;
double hit100 = 80;
double hit300 = 30;
protected override void CheckJudgement(bool userTriggered)
{
if (!userTriggered)
{
if (Judgement.TimeOffset > hit50)
Judgement.Result = HitResult.Miss;
return;
}
double hitOffset = Math.Abs(Judgement.TimeOffset);
OsuJudgementInfo osuJudgement = Judgement as OsuJudgementInfo;
if (hitOffset < hit50)
{
Judgement.Result = HitResult.Hit;
if (hitOffset < hit300)
osuJudgement.Score = OsuScoreResult.Hit300;
else if (hitOffset < hit100)
osuJudgement.Score = OsuScoreResult.Hit100;
else if (hitOffset < hit50)
osuJudgement.Score = OsuScoreResult.Hit50;
}
else
Judgement.Result = HitResult.Miss;
}
protected override void UpdateInitialState()
{
base.UpdateInitialState();
//sane defaults
ring.Alpha = circle.Alpha = number.Alpha = glow.Alpha = 1;
ApproachCircle.Alpha = 0;
ApproachCircle.Scale = new Vector2(4);
explode.Alpha = 0;
}
protected override void UpdatePreemptState()
{
base.UpdatePreemptState();
ApproachCircle.FadeIn(Math.Min(TIME_FADEIN * 2, TIME_PREEMPT));
ApproachCircle.ScaleTo(1.1f, TIME_PREEMPT);
}
protected override void UpdateState(ArmedState state)
{
if (!IsLoaded) return;
base.UpdateState(state);
ApproachCircle.FadeOut();
glow.Delay(osuObject.Duration);
glow.FadeOut(400);
switch (state)
{
case ArmedState.Idle:
Delay(osuObject.Duration + TIME_PREEMPT);
FadeOut(TIME_FADEOUT);
break;
case ArmedState.Miss:
FadeOut(TIME_FADEOUT / 5);
break;
case ArmedState.Hit:
const double flash_in = 40;
flash.FadeTo(0.8f, flash_in);
flash.Delay(flash_in);
flash.FadeOut(100);
explode.FadeIn(flash_in);
Delay(flash_in, true);
//after the flash, we can hide some elements that were behind it
ring.FadeOut();
circle.FadeOut();
number.FadeOut();
FadeOut(800);
ScaleTo(Scale * 1.5f, 400, EasingTypes.OutQuad);
break;
}
}
public Drawable ProxiedLayer => ApproachCircle;
}
}
| NotKyon/lolisu | osu.Game.Modes.Osu/Objects/Drawables/DrawableHitCircle.cs | C# | mit | 5,352 |
Code Clippy Github Dataset
Dataset Description
The Code Clippy dataset consists of various public codebases from GitHub in 22 programming languages with 23 extensions totaling about 16 TB of data when uncompressed. The dataset was created from the public GitHub dataset on Google BigQuery.
How to use it
This dataset is pretty large please use the streaming parameter from the datasets
library as seen below:
from datasets import load_dataset
ds = load_dataset("CodedotAI/code_clippy_github", streaming=True)
Data Structure
Data Instances
{
'code_text': " a = mc^2",
'repo_name': 'NotEinstein',
'file_path': 'root/users/einstein.py',
'language': 'Python',
'license': 'isc',
'size': 2
}
Data Fields
Field | Type | Description |
---|---|---|
code_text | string | string of the source code contained in the code file |
repo_name | string | name of the GitHub repository |
file_path | string | path of the code file within the repository |
language | string | programming language used in the file inferred by the file extension |
license | string | license of GitHub repository |
size | int | size of source file in bytes |
Data Splits
Only a train split is provided in this dataset.
Languages
The dataset contains 22 programming languages with over 23 extensions:
{
"C": [".c"],
"C#": [".cs"],
"C++": [".cpp"],
"CSS": [".css"],
"Dart" : [".dart"],
"GO": [".go"],
"HTML":[".html"],
"Java": [".java"],
"JavaScript": [".js"],
"Jupyter Notebooks (Python)": [".ipynb"],
"Kotlin" : [".kt"],
"Lisp" : [".lisp"],
"Matlab" : [".m"],
"PHP": [".php"],
"Perl": [".pl"],
"Python": [".py"],
"R" : [".r"],
"Ruby": [".rb"],
"Rust": [".rs"],
"SQL": [".sql"],
"Shell": [".sh"],
"Swift" : [".swift"],
"TypeScript": [".ts"],
}
Licenses
Each example is also annotated with the license of the associated repository. There are in total 15 licenses:
[
'mit',
'apache-2.0',
'gpl-2.0',
'gpl-3.0',
'bsd-3-clause',
'bsd-2-clause',
'unlicense',
'apacheagpl-3.0',
'lgpl-3.0',
'cc0-1.0',
'epl-1.0',
'lgpl-2.1',
'mpl-2.0',
'isc',
'artistic-2.0'
]
Dataset Statistics
The dataset is about ~ 18 TB uncompressed. We are currently working on processing it and applying further filtering.
Dataset Creation
The dataset was created in two steps:
- Files with the extensions given in the list above were retrieved from the GitHub dataset on BigQuery using the following query:
SELECT
f.id, f.repo_name, f.path, content.copies, content.size, content.content, lic.license
FROM
`bigquery-public-data.github_repos.files` AS f
JOIN
`bigquery-public-data.github_repos.contents` as content
ON
f.id = content.id
JOIN
`bigquery-public-data.github_repos.licenses` AS lic
ON
f.repo_name = lic.repo_name
WHERE
NOT content.binary
AND (
(f.path LIKE '%.py') OR (f.path LIKE '%.java') OR (f.path LIKE '%.js')
OR (f.path LIKE '%.html') OR (f.path LIKE '%.lisp') OR (f.path LIKE '%.sh')
OR (f.path LIKE '%.r') OR (f.path LIKE '%.pl') OR (f.path LIKE '%.css')
OR (f.path LIKE '%.sql') OR (f.path LIKE '%.c') OR (f.path LIKE '%.cpp')
OR (f.path LIKE '%.ts') OR (f.path LIKE '%.cs') OR (f.path LIKE '%.go')
OR (f.path LIKE '%.rs') OR (f.path LIKE '%.swift') OR (f.path LIKE '%.php')
OR (f.path LIKE '%.dart') OR (f.path LIKE '%.kt') OR (f.path LIKE '%.m')
OR (f.path LIKE '%.rb') OR (f.path LIKE '%.ipynb')
)
-- make sure we dont go above 1 megabyte
AND (content.size BETWEEN 1024 AND 1000000)
- Currently, our CodedotAI team is working on adding additional filters and cleaning this dataset.
Personal and Sensitive Information
Since this data was collected from public repositories, there exists potential for personal and sensitive information to be included in the data through developers accidentally or on purpose uploading their secret keys, passwords, API keys, emails, etc.
Considerations for Using the Data
Social Impact of Dataset
The paper "Evaluating Large Language Models Trained on Code" from OpenAI has a good discussion on what the impact of a large language model trained on code could be. Therefore, some parts of their discussion are highlighted here as it pertains to this dataset and models that may be trained from it. As well as some differences in views from the paper, particularly around legal implications.
- Over-reliance: A language model trained on large datasets such as this one for the task of autogenerating code may generate plausible solutions that may appear correct, but are not necessarily the correct solution. Not properly evaluating the generated code may cause have negative consequences such as the introduction of bugs, or the introduction of security vulnerabilities. Therefore, it is important that users are aware of the limitations and potential negative consequences of using a language model trained on this dataset.
- Economic and labor market impacts: Large language models trained on large code datasets such as this one that are capable of generating high-quality code have the potential to automate part of the software development process. This may negatively impact software developers. However, as discussed in the paper, as shown in the Summary Report of software developers from O*NET OnLine, developers don't just write software.
- Security implications: No filtering or checking of vulnerabilities or buggy code was performed. This means that the dataset may contain code that may be malicious or contain vulnerabilities. Therefore, any model trained on this dataset may generate vulnerable, buggy, or malicious code. In safety-critical software, this could lead to software that may work improperly and could result in serious consequences depending on the software. Additionally, a model trained on this dataset may be used to generate malicious code on purpose in order to perform ransomware or other such attacks.
- Legal implications: No filtering was performed on licensed code. This means that the dataset may contain restrictive licensed code. As discussed in the paper, public Github repositories may fall under "fair use." However, there have been little to no previous cases of such usages of licensed publicly available code. Therefore, any model trained on this dataset may be required to obey license terms that align with the software it was trained on such as GPL-3.0, which is why we purposefully put this dataset under the GPL-3.0 license. It is unclear the legal ramifications of using a language model trained on this dataset.
v1.0
- The query was executed on February 1, 2022, 12:15:59 AM EST
Acknowledgements
This project would not have been possible without compute generously provided by Google through the TPU Research Cloud. We would also like to thank Dr. Razvan Bunescu and The College of Computing and Informatics at UNC Charlotte for their generous contributions to this project, specifically in funding the BigQuery and Google Cloud Storage costs. We would also like to thank the codeparrot team at Hugging face for open sourcing their documentation on github-code which we used for the readme in this dataset. For another similar dataset to this please check github-code!
- Downloads last month
- 2,928