content stringlengths 23 1.05M |
|---|
using LionJobs.ViewModels;
using Ninject.Modules;
using Ninject.Web.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LionJobs.Web.App_Start.NinjectModules
{
public class ViewModelModule : NinjectModule
{
public override void Load()
{
Bind<IEmployeeListViewModel>().To<EmployeesListViewModel>().InRequestScope();
Bind<ICompanyViewModel>().To<CompanyViewModel>().InRequestScope();
Bind<CreateAJobViewModel>().ToSelf().InRequestScope();
Bind<CompanyJobsViewModel>().ToSelf().InRequestScope();
}
}
} |
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
namespace Secure.SecurityDoors.Web.Middlewares
{
/// <summary>
/// Page not found middleware.
/// </summary>
public class PageNotFoundMiddleware
{
private readonly RequestDelegate _next;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="next">Request delegate.</param>
public PageNotFoundMiddleware(RequestDelegate next)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
}
/// <summary>
/// Invoke.
/// </summary>
/// <param name="context">Http context.</param>
public async Task Invoke(HttpContext context)
{
context = context ?? throw new ArgumentNullException(nameof(context));
await _next(context);
if (context.Response.StatusCode == 404 && !context.Response.HasStarted)
{
context.Request.Path = "/Error/404";
await _next(context);
}
}
}
}
|
//using Synthesis.FSM;
//using Synthesis.States;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using UnityEngine;
//namespace Assets.Scripts
//{
// public class MultiplayerStart : MonoBehaviour
// {
// private void Start()
// {
// StateMachine.SceneGlobal.ChangeState(new MultiplayerState());
// }
// }
//}
|
using System;
using System.Collections.Generic;
using Ploeh.AutoFixture.Dsl;
using TeamCityApi.Domain;
using TeamCityConsole.Options;
namespace TeamCityConsole.Tests.Helpers
{
public static class DomainExtensions
{
public static IPostprocessComposer<GetDependenciesOptions> WithForce(
this IPostprocessComposer<GetDependenciesOptions> composer, string buildConfigId)
{
return composer.With(x => x.BuildConfigId, buildConfigId).With(x => x.Force, true);
}
}
} |
using CsvHelper.Configuration;
using SpecificPlantingDateWriter.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpecificPlantingDateWriter
{
class ObservedPlantingMap : CsvClassMap<ObservedPlanting>
{
public ObservedPlantingMap()
{
Map(m => m.CropName).Name("Crop");
Map(m => m.PlantingDate).Name("Planting-Date");
Map(m => m.SimLocation).Name("Sim-Location");
}
}
}
|
using System;
using E3Series.Proxy.Abstract;
using E3Series.Proxy.Interfaces;
namespace E3Series.Proxy
{
/// <summary>
/// Proxy class (generated for E3.series 2015.1613)
/// </summary>
public sealed class E3PinProxy : E3ProxyBase, IAttributed
{
public E3PinProxy(object comObject) : base(comObject)
{
}
public int AddAttributeValue(string name, string value)
{
return ComObject.AddAttributeValue(name, value);
}
public int AddDefaultWire(IntPtr wiregroup, IntPtr wirename)
{
return ComObject.AddDefaultWire(wiregroup, wirename);
}
public int AddEndAttributeValue(int which, string name, string value)
{
return ComObject.AddEndAttributeValue(which, name, value);
}
public int AddPinsToConnector(ref object pinidarray, string name, string assignment, string location)
{
return ComObject.AddPinsToConnector(ref pinidarray, name, assignment, location);
}
public int AssignTo(ref object pinids)
{
return ComObject.AssignTo(ref pinids);
}
public int CalculateFittingForWires(ref object wirids, ref object fittinglst)
{
return ComObject.CalculateFittingForWires(ref wirids, ref fittinglst);
}
public int Create(string name, int devi, int pini, int before)
{
return ComObject.Create(name, devi, pini, before);
}
public int CreateNewConnectorForPins(ref object pinidarray, string name, string assignment, string location)
{
return ComObject.CreateNewConnectorForPins(ref pinidarray, name, assignment, location);
}
public int CreateWire(string name, string cabtyp, string wirnam, int devi, int pini, int before)
{
return ComObject.CreateWire(name, cabtyp, wirnam, devi, pini, before);
}
public int Delete()
{
return ComObject.Delete();
}
public int DeleteAttribute(string name)
{
return ComObject.DeleteAttribute(name);
}
public int DeleteDefaultWire(IntPtr wiregroup, IntPtr wirename)
{
return ComObject.DeleteDefaultWire(wiregroup, wirename);
}
public int DeleteEndAttribute(int which, string name)
{
return ComObject.DeleteEndAttribute(which, name);
}
public int DeleteForced()
{
return ComObject.DeleteForced();
}
public int DeletePanelPath()
{
return ComObject.DeletePanelPath();
}
public int FindPanelPath()
{
return ComObject.FindPanelPath();
}
public int GenerateNewWireNames(ref object ids)
{
return ComObject.GenerateNewWireNames(ref ids);
}
public int GetAllNetSegmentPaths(ref object ids, int pin1i, int pin2i)
{
return ComObject.GetAllNetSegmentPaths(ref ids, pin1i, pin2i);
}
public int GetAssignedOptionExpressions(ref object expressions, int Term = 0)
{
return ComObject.GetAssignedOptionExpressions(ref expressions, Term);
}
public int GetAssignedOptionExpressionsEx(ref object expressions, int Term = 0)
{
return ComObject.GetAssignedOptionExpressionsEx(ref expressions, Term);
}
public int GetAssignedOptionIds(ref object ids)
{
return ComObject.GetAssignedOptionIds(ref ids);
}
public int GetAttributeCount()
{
return ComObject.GetAttributeCount();
}
public int GetAttributeIds(ref object ids, string attnam = null)
{
return ComObject.GetAttributeIds(ref ids, attnam);
}
public string GetAttributeValue(string name)
{
return ComObject.GetAttributeValue(name);
}
public int GetBlockConnectionNumber()
{
return ComObject.GetBlockConnectionNumber();
}
public int GetCableDuctIds(ref object ids)
{
return ComObject.GetCableDuctIds(ref ids);
}
public int GetCCT()
{
return ComObject.GetCCT();
}
public int GetColour()
{
return ComObject.GetColour();
}
public string GetColourDescription()
{
return ComObject.GetColourDescription();
}
public string GetComponentAttributeValue(string name)
{
return ComObject.GetComponentAttributeValue(name);
}
public int GetConnectedNodeIds(ref object ids)
{
return ComObject.GetConnectedNodeIds(ref ids);
}
public int GetConnectedPinId()
{
return ComObject.GetConnectedPinId();
}
public int GetConnectedPinIds(ref object ids)
{
return ComObject.GetConnectedPinIds(ref ids);
}
public int GetConnectionType()
{
return ComObject.GetConnectionType();
}
public string GetConnectionTypeDescription()
{
return ComObject.GetConnectionTypeDescription();
}
public int GetCoreChangeIds(ref object ids)
{
return ComObject.GetCoreChangeIds(ref ids);
}
public int GetCoreChangeIds(ref object ids, ref object optids)
{
return ComObject.GetCoreChangeIds(ref ids, ref optids);
}
public string GetCoreCost()
{
return ComObject.GetCoreCost();
}
public int GetCoreCount()
{
return ComObject.GetCoreCount();
}
public int GetCoreIds(ref object ids)
{
return ComObject.GetCoreIds(ref ids);
}
public double GetCoreManufacturingLength()
{
return ComObject.GetCoreManufacturingLength();
}
public double GetCoreWeight()
{
return ComObject.GetCoreWeight();
}
public string GetCounterpart()
{
return ComObject.GetCounterpart();
}
public double GetCrossSection()
{
return ComObject.GetCrossSection();
}
public string GetCrossSectionDescription()
{
return ComObject.GetCrossSectionDescription();
}
public int GetDefaultWires(ref object wiregroups, ref object wirenames)
{
return ComObject.GetDefaultWires(ref wiregroups, ref wirenames);
}
public double GetDefinedOuterDiameter()
{
return ComObject.GetDefinedOuterDiameter();
}
public int GetDestinationCount()
{
return ComObject.GetDestinationCount();
}
public int GetDestinationIds(ref object ids)
{
return ComObject.GetDestinationIds(ref ids);
}
public int GetDevicePinIds(ref object ids)
{
return ComObject.GetDevicePinIds(ref ids);
}
public double GetDiameter()
{
return ComObject.GetDiameter();
}
public string GetDiameterDescription()
{
return ComObject.GetDiameterDescription();
}
public int GetEndAttributeCount(int which)
{
return ComObject.GetEndAttributeCount(which);
}
public int GetEndAttributeIds(int which, ref object ids, string attnam = null)
{
return ComObject.GetEndAttributeIds(which, ref ids, attnam);
}
public string GetEndAttributeValue(int which, string name)
{
return ComObject.GetEndAttributeValue(which, name);
}
public int GetEndPinId(int which, int flags = 0)
{
return ComObject.GetEndPinId(which, flags);
}
public int GetExchangeableID()
{
return ComObject.GetExchangeableID();
}
public string GetExternSignalName()
{
return ComObject.GetExternSignalName();
}
public string GetFitting()
{
return ComObject.GetFitting();
}
public int GetFittingIds(ref object ids)
{
return ComObject.GetFittingIds(ref ids);
}
public int GetFittingIds(ref object ids, ref object optids)
{
return ComObject.GetFittingIds(ref ids, ref optids);
}
public int GetFunc()
{
return ComObject.GetFunc();
}
public int GetFunctionalPortID()
{
return ComObject.GetFunctionalPortID();
}
public int GetHarnessId()
{
return ComObject.GetHarnessId();
}
public int GetId()
{
return ComObject.GetId();
}
public int GetInterruptSignalFlow()
{
return ComObject.GetInterruptSignalFlow();
}
public double GetLength()
{
return ComObject.GetLength();
}
public int GetLocking()
{
return ComObject.GetLocking();
}
public int GetLogicalEquivalenceID()
{
return ComObject.GetLogicalEquivalenceID();
}
public int GetLossAngle(ref object lossangle)
{
return ComObject.GetLossAngle(ref lossangle);
}
public int GetMaterial()
{
return ComObject.GetMaterial();
}
public string GetMaterialDescription()
{
return ComObject.GetMaterialDescription();
}
public int GetMergeSegment()
{
return ComObject.GetMergeSegment();
}
public string GetName()
{
return ComObject.GetName();
}
public int GetNameEquivalenceID()
{
return ComObject.GetNameEquivalenceID();
}
public int GetNetSegmentCount()
{
return ComObject.GetNetSegmentCount();
}
public int GetNetSegmentIds(ref object ids)
{
return ComObject.GetNetSegmentIds(ref ids);
}
public int GetNetSegmentPath(ref object ids, int pin1i, int pin2i)
{
return ComObject.GetNetSegmentPath(ref ids, pin1i, pin2i);
}
public int GetNodeIds(ref object ids)
{
return ComObject.GetNodeIds(ref ids);
}
public int GetNodeType(ref object type)
{
return ComObject.GetNodeType(ref type);
}
public int GetNumberOfWindings()
{
return ComObject.GetNumberOfWindings();
}
public int GetOriginalId()
{
return ComObject.GetOriginalId();
}
public double GetOuterDiameter()
{
return ComObject.GetOuterDiameter();
}
public int GetOverbraidId()
{
return ComObject.GetOverbraidId();
}
public int GetPanelLocation(ref object x, ref object y, ref object z)
{
return ComObject.GetPanelLocation(ref x, ref y, ref z);
}
public int GetPanelNetSegmentIds(ref object ids)
{
return ComObject.GetPanelNetSegmentIds(ref ids);
}
public int GetPanelPath(ref object xarr, ref object yarr, ref object zarr)
{
return ComObject.GetPanelPath(ref xarr, ref yarr, ref zarr);
}
public int GetPassPins(ref object ids, ref object ends, ref object ende)
{
return ComObject.GetPassPins(ref ids, ref ends, ref ende);
}
public int GetPassWires(ref object ids)
{
return ComObject.GetPassWires(ref ids);
}
public int GetPhysicalConnectionDirection()
{
return ComObject.GetPhysicalConnectionDirection();
}
public int GetPhysicalConnectionType()
{
return ComObject.GetPhysicalConnectionType();
}
public string GetPhysicalConnectionTypeDescription()
{
return ComObject.GetPhysicalConnectionTypeDescription();
}
public int GetPhysicalID()
{
return ComObject.GetPhysicalID();
}
public int GetPhysicalMaxConnections()
{
return ComObject.GetPhysicalMaxConnections();
}
public double GetPhysicalMaxCrossSection()
{
return ComObject.GetPhysicalMaxCrossSection();
}
public double GetPhysicalMinCrossSection()
{
return ComObject.GetPhysicalMinCrossSection();
}
public int GetPhysicalPosition(ref object x, ref object y, ref object z)
{
return ComObject.GetPhysicalPosition(ref x, ref y, ref z);
}
public double GetPhysicalTotalMaxCrossSection()
{
return ComObject.GetPhysicalTotalMaxCrossSection();
}
public int GetPinIndex()
{
return ComObject.GetPinIndex();
}
public string GetPortName()
{
return ComObject.GetPortName();
}
public int GetRelativePermittivity(ref object relativepermittivity)
{
return ComObject.GetRelativePermittivity(ref relativepermittivity);
}
public int GetSchemaLocation(ref object x, ref object y, ref object grid)
{
return ComObject.GetSchemaLocation(ref x, ref y, ref grid);
}
public int GetSchemaLocation(ref object x, ref object y, ref object grid, ref object column_value)
{
return ComObject.GetSchemaLocation(ref x, ref y, ref grid, ref column_value);
}
public int GetSchemaLocation(ref object x, ref object y, ref object grid, ref object column_value,
ref object row_value)
{
return ComObject.GetSchemaLocation(ref x, ref y, ref grid, ref column_value, ref row_value);
}
public int GetSchematicEndPinId(int which)
{
return ComObject.GetSchematicEndPinId(which);
}
public int GetSequenceNumber()
{
return ComObject.GetSequenceNumber();
}
public string GetSignalName()
{
return ComObject.GetSignalName();
}
public int GetSupplyInfo(ref object supid, ref object signum, ref object signam)
{
return ComObject.GetSupplyInfo(ref supid, ref signum, ref signam);
}
public int GetTemplateSymbolId()
{
return ComObject.GetTemplateSymbolId();
}
public int GetTemplateSymbolIds(ref object ids)
{
return ComObject.GetTemplateSymbolIds(ref ids);
}
public int GetTextCount()
{
return ComObject.GetTextCount();
}
public int GetTextIds(ref object ids, int txttyp = 0, string search_string = "")
{
return ComObject.GetTextIds(ref ids, txttyp, search_string);
}
public string GetTranslatedSignalName()
{
return ComObject.GetTranslatedSignalName();
}
public int GetTypeId()
{
return ComObject.GetTypeId();
}
public int GetValidCounterparts(ref object strings)
{
return ComObject.GetValidCounterparts(ref strings);
}
public int GetValidFittings(ref object strings)
{
return ComObject.GetValidFittings(ref strings);
}
public int GetVariantObjectProperties(int iObjectType, string sAttributeName, ref object arr)
{
return ComObject.GetVariantObjectProperties(iObjectType, sAttributeName, ref arr);
}
public int GetViewCount()
{
return ComObject.GetViewCount();
}
public int GetViewIds(ref object ids)
{
return ComObject.GetViewIds(ref ids);
}
public int GetWireKindId()
{
return ComObject.GetWireKindId();
}
public int GetWireType(ref object comp, ref object name)
{
return ComObject.GetWireType(ref comp, ref name);
}
public int HasAttribute(string name)
{
return ComObject.HasAttribute(name);
}
public int HasDevice()
{
return ComObject.HasDevice();
}
public int HasEndAttribute(int which, string name)
{
return ComObject.HasEndAttribute(which, name);
}
public int Highlight()
{
return ComObject.Highlight();
}
public int IsBackShell()
{
return ComObject.IsBackShell();
}
public int IsCoreEndLocked(int which)
{
return ComObject.IsCoreEndLocked(which);
}
public int IsExternal()
{
return ComObject.IsExternal();
}
public int IsInternal()
{
return ComObject.IsInternal();
}
public int IsLocked()
{
return ComObject.IsLocked();
}
public int IsNoconn()
{
return ComObject.IsNoconn();
}
public int IsOffline()
{
return ComObject.IsOffline();
}
public int IsPanelPathLocked()
{
return ComObject.IsPanelPathLocked();
}
public int IsPassWire()
{
return ComObject.IsPassWire();
}
public int IsPinView()
{
return ComObject.IsPinView();
}
public int IsRouted()
{
return ComObject.IsRouted();
}
public int IsSupply()
{
return ComObject.IsSupply();
}
public int IsView()
{
return ComObject.IsView();
}
public int LockCoreEnd(int which, int @lock)
{
return ComObject.LockCoreEnd(which, @lock);
}
public int LockObject()
{
return ComObject.LockObject();
}
public int LockPanelPath(int @lock)
{
return ComObject.LockPanelPath(@lock);
}
public int PlaceNode(int shtId, double x, double y)
{
return ComObject.PlaceNode(shtId, x, y);
}
public int ResetLength()
{
return ComObject.ResetLength();
}
public int Search(string name, int devi)
{
return ComObject.Search(name, devi);
}
public int SetAsExternal(int onoff)
{
return ComObject.SetAsExternal(onoff);
}
public int SetAsInternal(int onoff)
{
return ComObject.SetAsInternal(onoff);
}
public int SetAttributeValue(string name, string value)
{
return ComObject.SetAttributeValue(name, value);
}
public int SetColour(int color)
{
return ComObject.SetColour(color);
}
public int SetColourByDescription(string color)
{
return ComObject.SetColourByDescription(color);
}
public int SetColourDescription(string color)
{
return ComObject.SetColourDescription(color);
}
public int SetCoreChangeId(int id)
{
return ComObject.SetCoreChangeId(id);
}
public int SetCoreCost(string value)
{
return ComObject.SetCoreCost(value);
}
public int SetCounterpart(string name)
{
return ComObject.SetCounterpart(name);
}
public int SetCrossSection(double crossec)
{
return ComObject.SetCrossSection(crossec);
}
public int SetCrossSectionByDescription(string description)
{
return ComObject.SetCrossSectionByDescription(description);
}
public int SetDefaultWires(ref object wiregroups, ref object wirenames)
{
return ComObject.SetDefaultWires(ref wiregroups, ref wirenames);
}
public int SetDeviceId(int devid, int pinid, int before)
{
return ComObject.SetDeviceId(devid, pinid, before);
}
public int SetEndAttributeValue(int which, string name, string value)
{
return ComObject.SetEndAttributeValue(which, name, value);
}
public int SetEndPinId(int which, int pini)
{
return ComObject.SetEndPinId(which, pini);
}
public int SetFitting(string name)
{
return ComObject.SetFitting(name);
}
public int SetFittingId(int id)
{
return ComObject.SetFittingId(id);
}
public int SetId(int id)
{
return ComObject.SetId(id);
}
public int SetInterruptSignalFlow(int sigflow = 1)
{
return ComObject.SetInterruptSignalFlow(sigflow);
}
public int SetLength(double length)
{
return ComObject.SetLength(length);
}
public int SetLocking(int bSet)
{
return ComObject.SetLocking(bSet);
}
public int SetMergeSegment(int bSet)
{
return ComObject.SetMergeSegment(bSet);
}
public int SetName(string name)
{
return ComObject.SetName(name);
}
public int SetNameSymbol(string name)
{
return ComObject.SetNameSymbol(name);
}
public int SetNetSegmentPathIds(ref object netsegids)
{
return ComObject.SetNetSegmentPathIds(ref netsegids);
}
public int SetNodeId(int id)
{
return ComObject.SetNodeId(id);
}
public int SetOptionExpressions(ref object expressions)
{
return ComObject.SetOptionExpressions(ref expressions);
}
public double SetOuterDiameter(double newval)
{
return ComObject.SetOuterDiameter(newval);
}
public int SetPanelPath(int pnts, ref object x, ref object y, ref object z, int use_exact_coords = 0)
{
return ComObject.SetPanelPath(pnts, ref x, ref y, ref z, use_exact_coords);
}
public int SetPhysicalConnectionDirection(int conndir)
{
return ComObject.SetPhysicalConnectionDirection(conndir);
}
public int SetPhysicalConnectionType(int conntyp)
{
return ComObject.SetPhysicalConnectionType(conntyp);
}
public int SetPhysicalMaxConnections(int conncount)
{
return ComObject.SetPhysicalMaxConnections(conncount);
}
public int SetSignalName(string name)
{
return ComObject.SetSignalName(name);
}
public int SetWireType(string comp, string name)
{
return ComObject.SetWireType(comp, name);
}
public int UnassignFrom(int id)
{
return ComObject.UnassignFrom(id);
}
public int UnlockObject(string password)
{
return ComObject.UnlockObject(password);
}
}
} |
using HostApp.Core.Extensions;
using HostApp.Core.Interfaces;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
namespace HostApp.Core.Repository
{
public class ContextMongoDB<T> : IContextMongoDB<T>
{
private readonly IMongoClient _client;
private readonly IMongoDatabase _database;
private readonly string _collectionName;
/// <summary>
/// Database context for MongoDB
/// </summary>
/// <param name="connectionString"></param>
/// <param name="databasename"></param>
public ContextMongoDB(string connectionString, string databasename)
{
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
_client = new MongoClient(connectionString);
_database = _client.GetDatabase(databasename);
_collectionName = GetCollectionName(typeof(T).Name);
}
public IMongoClient Client
{
get { return _client; }
}
public IMongoCollection<BsonDocument> GetBsonCollection
{
get { return _database.GetCollection<BsonDocument>(_collectionName); }
}
public IMongoCollection<T> GetCollection
{
get { return _database.GetCollection<T>(_collectionName); }
}
private string GetCollectionName(string collectionName)
{
var workingName = collectionName.ToLower();
if (workingName.EndsWith("dto"))
{
workingName = workingName.Left(workingName.Length - 3);
}
return workingName;
}
}
}
|
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace OilStationCoreAPI.ConfigureSetup
{
public static class JwtSetup
{
public static void AddJwtSetup(this IServiceCollection services, IConfiguration configuration)
{
//读取配置文件
var audienceConfig = configuration.GetSection("Audience");
var symmetricKeyAsBase64 = audienceConfig["Secret"];
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray);
//认证
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,//参数配置
// 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
ValidateIssuer = true,
ValidIssuer = audienceConfig["Issuer"],//发行人
ValidateAudience = true,
ValidAudience = audienceConfig["Audience"],//订阅人
// 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
ValidateLifetime = true,
// 允许的服务器时间偏移量
ClockSkew = TimeSpan.FromSeconds(5),
// 是否要求Token的Claims中必须包含Expires
RequireExpirationTime = true
};
o.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
// 如果过期,则把<是否过期>添加到,返回头信息中
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
}
}
}
|
using System.Collections.Generic;
namespace Benday.EasyAuthDemo.WebUi.Models
{
public partial class SecurityLoginModel
{
public SecurityLoginModel()
{
LoginTypes = new List<SecurityLoginOption>();
}
public List<SecurityLoginOption> LoginTypes { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseWeapon : MonoBehaviour
{
// properties
[SerializeField] public Transform FirePoint;
[SerializeField] public BaseBulletBehaviour BulletBehaviour;
[SerializeField] public int FireRate = 600;
[SerializeField] public int BulletSpeed = 20;
[SerializeField] public int BulletDamage = 100;
[SerializeField] public bool Automatic = true;
private float NextFire = 0.0f;
private bool CanFire = true;
// methods
// // on start
void Start()
{
}
// // on frame update
void Update()
{
if (CanFire) FireInput();
else
{
if (Input.GetMouseButtonDown(0)) FireStop();
NextFire = 0.0f;
}
}
// // fire input
void FireInput()
{
if (Automatic)
{
if (Input.GetMouseButton(0) && Time.time >= NextFire)
{
NextFire = Time.time + (60.0f / FireRate);
FireStart();
}
else if (Input.GetMouseButtonUp(0))
{
FireStop();
}
}
else
{
if (Input.GetMouseButtonDown(0))
{
FireStart();
FireStop();
}
}
}
// // start firing
private void FireStart()
{
if (BulletBehaviour) BulletBehaviour.FireStart(this, FirePoint);
}
// // stop firing
private void FireStop()
{
if (BulletBehaviour) BulletBehaviour.FireStop();
}
}
|
using Unity.Entities;
namespace Interfaces
{
public interface ITriggerHandler
{
void OnTriggerEvent(Entity current, Entity other);
}
} |
using IdeaRS.OpenModel.Geometry3D;
namespace IdeaRS.OpenModel.Model
{
/// <summary>
/// Represents an arc segment in 3D space defined by 3 points
/// Start, End and a Point between start and end point.
/// </summary>
public class RebarSegment3DArc3Pts : RebarSegment3DBase
{
/// <summary>
/// Gets or sets the point of circular arc somewhere between start and end point.
/// </summary>
public Point3D ThirdPoint { get; set; }
}
} |
namespace Quark.AppService.Services;
public interface ICreateAppService<TEntityDto>
: ICreateAppService<TEntityDto, TEntityDto>
{
}
public interface ICreateAppService<TGetOutputDto, in TCreateInput>
{
Task<TGetOutputDto> Create(TCreateInput input);
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using UnrealBuildTool;
using Tools.DotNETCommon;
using System;
using System.Collections.Generic;
public class HololensResearchMode : ModuleRules
{
public HololensResearchMode(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
PrivatePCHHeaderFile = @"Private\HololensResearchModeCommon.h";
PrivateIncludePaths.AddRange(
new string[] {
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"ApplicationCore",
"Engine",
"Projects",
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"AugmentedReality",
}
);
PrivateIncludePathModuleNames.AddRange(
new string[]
{
}
);
PublicIncludePathModuleNames.AddRange(
new string[]
{
}
);
if (Target.Platform == UnrealTargetPlatform.HoloLens)
{
// DX-specific code for cam texture processing
PrivateDependencyModuleNames.AddRange(new string[] {
"D3D11RHI",
"D3D12RHI"
});
var EngineDir = Path.GetFullPath(Target.RelativeEnginePath);
PrivateIncludePaths.AddRange(
new string[] {
Path.Combine(EngineDir, @"Source\Runtime\Windows\D3D11RHI\Private"),
Path.Combine(EngineDir, @"Source\Runtime\Windows\D3D11RHI\Private\Windows"),
Path.Combine(EngineDir, @"Source\Runtime\D3D12RHI\Private"),
Path.Combine(EngineDir, @"Source\Runtime\D3D12RHI\Private\Windows")
});
AddEngineThirdPartyPrivateStaticDependencies(Target, "DX11");
AddEngineThirdPartyPrivateStaticDependencies(Target, "DX12");
AddEngineThirdPartyPrivateStaticDependencies(Target, "NVAPI");
AddEngineThirdPartyPrivateStaticDependencies(Target, "AMD_AGS");
AddEngineThirdPartyPrivateStaticDependencies(Target, "NVAftermath");
AddEngineThirdPartyPrivateStaticDependencies(Target, "IntelMetricsDiscovery");
AddEngineThirdPartyPrivateStaticDependencies(Target, "IntelExtensionsFramework");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using FWF.FluidEntity.ComponentModel.Streams;
using FWF.FluidEntity.Logging;
namespace FWF.FluidEntity
{
public static class ObjectExtensions
{
private static readonly BinaryFormatter _binaryFormatter = new BinaryFormatter();
public static ILog Log
{
get;
set;
}
public static byte[] BinarySerialize(this object obj)
{
using (var memoryStream = new MemoryPoolStream(1024))
{
_binaryFormatter.Serialize(memoryStream, obj);
memoryStream.Flush();
memoryStream.Position = 0;
return memoryStream.ToArray();
}
}
public static object BinaryDeserialize(this byte[] byteData)
{
using (var memoryStream = new MemoryStream(byteData))
{
memoryStream.Position = 0;
return _binaryFormatter.Deserialize(memoryStream);
}
}
public static T BinaryClone<T>(this T obj) where T : class
{
var binaryObject = obj.BinarySerialize();
return binaryObject.BinaryDeserialize() as T;
}
public static IDictionary<string, object> ParseProperties(this object obj)
{
IDictionary<string, object> listProperties = new Dictionary<string, object>();
var properties = TypeDescriptor.GetProperties(obj);
foreach (PropertyDescriptor propertyDescriptor in properties)
{
var value = propertyDescriptor.GetValue(obj);
listProperties.Add(propertyDescriptor.Name, value);
}
return listProperties;
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using jumpfs.EnvironmentAccess;
namespace jumpfs.Bookmarking
{
/// <summary>
/// A repository for bookmarks
/// </summary>
/// <remarks>
/// The repository makes certain assumptions about the persistence mechanism
/// </remarks>
public class BookmarkRepository
{
public readonly string BookmarkFile;
public readonly IEnvironment Environment;
public BookmarkRepository(IEnvironment environment)
{
Environment = environment;
BookmarkFile = Path.Combine(Folder, "jumpfs", "bookmarks.json");
}
public string Folder =>
(Environment.ShellType == ShellType.Wsl)
? Environment.GetEnvironmentVariable(EnvVariables.WslEnvVar).Trim()
: Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
public Bookmark[] Load()
{
var text = !Environment.FileExists(BookmarkFile) ? "[]" : Environment.ReadAllText(BookmarkFile);
return JsonSerializer.Deserialize<Bookmark[]>(text);
}
public Bookmark[] List(string match)
{
var all = Load();
var matches = all.Where(m => m.Name.Contains(match) || m.Path.Contains(match)).ToArray();
return matches;
}
public void Save(Bookmark[] bookmarks)
{
var text = JsonSerializer.Serialize(bookmarks, new JsonSerializerOptions {WriteIndented = true});
Environment.WriteAllText(BookmarkFile, text);
}
public void Mark(string name, string path) => Mark(name, path, 0, 0);
public void Mark(string name, string path, int line, int column)
{
var marks = Load();
var existing = marks.SingleOrDefault(m => m.Name == name);
if (existing == null)
{
existing = new Bookmark {Path = path};
marks = marks.Append(existing).ToArray();
}
existing.Path = path;
existing.Name = name;
existing.Line = line;
existing.Column = column;
Save(marks);
}
public Bookmark Find(string name)
{
var marks = Load();
var existing = marks.SingleOrDefault(m => m.Name == name)
?? new Bookmark();
return existing;
}
}
public class BookmarkSet
{
public JumpFsConfiguration Configuration { get; set; } = JumpFsConfiguration.Empty;
public Bookmark[] Bookmarks { get; set; } = Array.Empty<Bookmark>();
}
public class JumpFsConfiguration
{
public static readonly JumpFsConfiguration Empty = new();
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
namespace BinaryVisualizerWpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SearchTextBox.KeyDown += (s, e) =>
{
if (e.Key == Key.Enter) SearchButton_Click(s, null);
};
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new OpenFileDialog
{
Title = "開くファイルを選択してください",
RestoreDirectory = true
};
var result = fileDialog.ShowDialog();
if (result.HasValue && result.Value)
{
PathTextBox.Text = fileDialog.FileName;
await OpenFileAsBinary(fileDialog.FileName);
}
}
private static readonly int RowLength = 16;
private static readonly int TextWidth = 35;
private static readonly int TextHeight = 35;
private static readonly int Offest = (int)(TextWidth * 1.5);
private GridLabel _previousHexSelection;
private GridLabel _previousCharSelection;
private List<GridLabel> _hexLabels;
private List<GridLabel> _charLabels;
private async Task OpenFileAsBinary(string filePath)
{
using (var stream = new FileStream(filePath, FileMode.Open))
{
byte[] buffer = new byte[stream.Length];
await stream.ReadAsync(buffer, 0, (int)stream.Length);
int cnt = 0;
var hexLabels = new List<GridLabel>((int)stream.Length);
var charLabels = new List<GridLabel>((int) stream.Length);
foreach (var b in buffer)
{
var hex = Convert.ToString(b, 16);
if (hex.Length == 1) hex = $"0{hex}";
if (cnt % RowLength == 0)
{
hexLabels.Add(BuildRowLabel(cnt));
charLabels.Add(BuildRowLabel(cnt));
}
var hexLabel = BuildGridLabel(cnt, $"{hex}", GridType.Hex);
hexLabels.Add(hexLabel);
var charLabel = BuildGridLabel(cnt, $"{(char) b}", GridType.Char);
charLabels.Add(charLabel);
cnt++;
}
foreach (var item in hexLabels)
{
Grid1.Children.Add(item);
}
foreach (var item in charLabels)
{
Grid2.Children.Add(item);
}
_hexLabels = hexLabels;
_charLabels = charLabels;
}
}
private GridLabel BuildRowLabel(int index)
{
return new GridLabel(0, 0, GridType.RowLabel)
{
Content = Convert.ToString(index, 16),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(0, index / RowLength * TextHeight, 0, 0),
Width = TextWidth * 1.5,
Height = TextHeight + 5,
FontFamily = new FontFamily("monospace"),
FontSize = 24,
Foreground = Brushes.Gray
};
}
private GridLabel BuildGridLabel(int index, string text, GridType gridType)
{
var label = new GridLabel(index % RowLength, index / RowLength, gridType)
{
Content = text,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Margin = new Thickness(index % RowLength * TextWidth + Offest, index / RowLength * TextHeight, 0, 0),
Width = TextWidth + 5,
Height = TextHeight + 5,
FontFamily = new FontFamily("monospace"),
FontSize = 24
};
label.MouseDown += (s, e) =>
{
SelectLabel((GridLabel)s);
};
label.ToolTip = new ToolTip()
{
Content = $"0x{Convert.ToString(index, 16)}"
};
return label;
}
private void SelectLabel(GridLabel selection)
{
ResetLabel(_previousHexSelection);
ResetLabel(_previousCharSelection);
SetBackgroundColor(selection, BackgroundTheme.Black);
switch (selection.GridType)
{
case GridType.Hex:
_previousHexSelection = selection;
var charSelection = GetPreviousSelectionAccordingTo(selection, _charLabels);
if (charSelection != null)
{
_previousCharSelection = charSelection;
SetBackgroundColor(charSelection, BackgroundTheme.Black);
}
break;
case GridType.Char:
_previousCharSelection = selection;
var hexSelection = GetPreviousSelectionAccordingTo(selection, _hexLabels);
if (hexSelection != null)
{
_previousHexSelection = hexSelection;
SetBackgroundColor(hexSelection, BackgroundTheme.Black);
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private static void ResetLabel(GridLabel selection)
{
if (selection != null) SetBackgroundColor(selection, BackgroundTheme.White);
}
private static GridLabel GetPreviousSelectionAccordingTo(GridLabel target, List<GridLabel> searchTarget)
{
var selection =
searchTarget.FirstOrDefault(label => label.X == target.X && label.Y == target.Y);
return selection;
}
private enum BackgroundTheme
{
Black,
White
}
private static void SetBackgroundColor(GridLabel target, BackgroundTheme theme)
{
switch (theme)
{
case BackgroundTheme.Black:
target.Background = Brushes.Black;
target.Foreground = Brushes.White;
break;
case BackgroundTheme.White:
target.Background = Brushes.White;
target.Foreground = Brushes.Black;
break;
default:
throw new ArgumentOutOfRangeException(nameof(theme), theme, null);
}
}
private void ScrollViewer1_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
ScrollViewer2.ScrollToVerticalOffset(ScrollViewer1.VerticalOffset);
}
private void ScrollViewer2_OnScrollChanged(object sender, ScrollChangedEventArgs e)
{
ScrollViewer1.ScrollToVerticalOffset(ScrollViewer2.VerticalOffset);
}
private int searchIndex;
private string currentSearch;
private List<GridLabel> currentSearchResult;
private void SearchButton_Click(object sender, RoutedEventArgs e)
{
if(string.IsNullOrWhiteSpace(SearchTextBox.Text)) return;
var search = SearchTextBox.Text;
if (search != currentSearch)
{
searchIndex = 0;
currentSearchResult = null;
currentSearch = search;
}
if (currentSearchResult == null)
{
currentSearchResult = _hexLabels.FindAll(label => ((string)label.Content).Contains(search));
if (currentSearchResult.Count == 0)
{
MessageBox.Show("見つかりませんでした。");
currentSearchResult = null;
return;
}
}
if (searchIndex != 0 && searchIndex % currentSearchResult.Count == 0)
{
MessageBox.Show("先頭に戻りました");
}
var selection = currentSearchResult[searchIndex++ % currentSearchResult.Count];
SelectLabel(selection);
ScrollViewer1.ScrollToVerticalOffset(selection.Margin.Top); // 2 は勝手に動く
}
}
internal enum GridType
{
Hex,
Char,
RowLabel
}
public class GridLabel : Label
{
internal int X { get; }
internal int Y { get; }
internal GridType GridType { get; }
internal GridLabel(int x, int y, GridType gridType)
{
X = x;
Y = y;
GridType = gridType;
}
}
}
|
using System;
using SQLite;
namespace ScoreKeeper.Models
{
public class Player
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string AvatarFileName { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
public bool IsPlaying { get; set; }
public int AvatarID { get; set; }
public string ItemBackground { get; set; }
public string AvatarBackground { get; set; }
public int CurrentScore { get; set; }
public int NumOfWins { get; set; }
public int TurnOrder { get; set; }
}
public class CustomDice
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int LowEnd { get; set; }
public int HighEnd { get; set; }
}
} |
using System;
using Shared.Common.Storage;
namespace TestFramework.Resources
{
public class TestStepResultBlob : IJsonStorageEntity
{
public int TestRunId { get; set; }
public int TestCaseId { get; set; }
public int IterationCount { get; set; }
public int StepCount { get; set; }
public string RefToScreenshot { get; set; }
public string AddtionalInformation { get; set; }
public string Exception { get; set; }
public TestStepResultBlob() { }
public TestStepResultBlob(int stepCount, string refToScreenshot, string additionalInformation, Exception e)
{
StepCount = stepCount;
RefToScreenshot = refToScreenshot;
AddtionalInformation = additionalInformation;
if (e != null)
{
string msg = $"Exception: {e.Message}, Stack: {e.StackTrace}";
if (e.InnerException != null)
msg += $". Inner: {e.InnerException.Message}, Stack: {e.InnerException.StackTrace}";
Exception = msg;
}
}
public void SetKeys(int testRunId, int testCaseId, int iterationCount)
{
TestRunId = testRunId;
TestCaseId = testCaseId;
IterationCount = iterationCount;
}
public string GetPartitionKey()
{
return ConstructPartitionKey(this);
}
public string GetRowKey()
{
return IterationCount.ToString() + "_" + StepCount.ToString();
}
public static string ConstructPartitionKey(TestStepResultBlob obj)
{
return ConstructPartitionKey(obj.TestRunId, obj.TestCaseId);
}
public static string ConstructPartitionKey(int testRunId, int testCaseId)
{
return testRunId.ToString() + "_" + testCaseId.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using ProtoBuf.Meta;
namespace ProtoBuf
{
internal sealed class NetObjectCache
{
internal const int Root = 0;
private MutableList underlyingList;
private MutableList List => underlyingList ?? (underlyingList = new MutableList());
internal object GetKeyedObject(int key)
{
if (key-- == Root)
{
if (rootObject == null) throw new ProtoException("No root object assigned");
return rootObject;
}
BasicList list = List;
if (key < 0 || key >= list.Count)
{
Helpers.DebugWriteLine("Missing key: " + key);
throw new ProtoException("Internal error; a missing key occurred");
}
object tmp = list[key];
if (tmp == null)
{
throw new ProtoException("A deferred key does not have a value yet");
}
return tmp;
}
internal void SetKeyedObject(int key, object value)
{
if (key-- == Root)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (rootObject != null && ((object)rootObject != (object)value)) throw new ProtoException("The root object cannot be reassigned");
rootObject = value;
}
else
{
MutableList list = List;
if (key < list.Count)
{
object oldVal = list[key];
if (oldVal == null)
{
list[key] = value;
}
else if (!ReferenceEquals(oldVal, value))
{
throw new ProtoException("Reference-tracked objects cannot change reference");
} // otherwise was the same; nothing to do
}
else if (key != list.Add(value))
{
throw new ProtoException("Internal error; a key mismatch occurred");
}
}
}
private object rootObject;
internal int AddObjectKey(object value, out bool existing)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if ((object)value == (object)rootObject) // (object) here is no-op, but should be
{ // preserved even if this was typed - needs ref-check
existing = true;
return Root;
}
string s = value as string;
BasicList list = List;
int index;
if (s == null)
{
#if CF || PORTABLE // CF has very limited proper object ref-tracking; so instead, we'll search it the hard way
index = list.IndexOfReference(value);
#else
if (objectKeys == null)
{
objectKeys = new Dictionary<object, int>(ReferenceComparer.Default);
index = -1;
}
else
{
if (!objectKeys.TryGetValue(value, out index)) index = -1;
}
#endif
}
else
{
if (stringKeys == null)
{
stringKeys = new Dictionary<string, int>();
index = -1;
}
else
{
if (!stringKeys.TryGetValue(s, out index)) index = -1;
}
}
if (!(existing = index >= 0))
{
index = list.Add(value);
if (s == null)
{
#if !CF && !PORTABLE // CF can't handle the object keys very well
objectKeys.Add(value, index);
#endif
}
else
{
stringKeys.Add(s, index);
}
}
return index + 1;
}
private int trapStartIndex; // defaults to 0 - optimization for RegisterTrappedObject
// to make it faster at seeking to find deferred-objects
internal void RegisterTrappedObject(object value)
{
if (rootObject == null)
{
rootObject = value;
}
else
{
if (underlyingList != null)
{
for (int i = trapStartIndex; i < underlyingList.Count; i++)
{
trapStartIndex = i + 1; // things never *become* null; whether or
// not the next item is null, it will never
// need to be checked again
if (underlyingList[i] == null)
{
underlyingList[i] = value;
break;
}
}
}
}
}
private Dictionary<string, int> stringKeys;
#if !CF && !PORTABLE // CF lacks the ability to get a robust reference-based hash-code, so we'll do it the harder way instead
private System.Collections.Generic.Dictionary<object, int> objectKeys;
private sealed class ReferenceComparer : IEqualityComparer<object>
{
public readonly static ReferenceComparer Default = new ReferenceComparer();
private ReferenceComparer() { }
bool IEqualityComparer<object>.Equals(object x, object y)
{
return x == y; // ref equality
}
int IEqualityComparer<object>.GetHashCode(object obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
}
#endif
internal void Clear()
{
trapStartIndex = 0;
rootObject = null;
if (underlyingList != null) underlyingList.Clear();
if (stringKeys != null) stringKeys.Clear();
#if !CF && !PORTABLE
if (objectKeys != null) objectKeys.Clear();
#endif
}
}
} |
using System;
namespace Brownbag.Data.Interfaces {
public interface IAuditable {
Guid CreatedBy { get; set; }
DateTime CreatedDate { get; set; }
Guid? UpdatedBy { get; set; }
DateTime? UpdatedDate { get; set; }
}
} |
using System;
using Microsoft.Extensions.Options;
using Orleans.Runtime;
namespace Orleans.Configuration
{
internal class GrainCollectionOptionsValidator : IConfigurationValidator
{
private IOptions<GrainCollectionOptions> options;
public GrainCollectionOptionsValidator(IOptions<GrainCollectionOptions> options)
{
this.options = options;
}
public void ValidateConfiguration()
{
if (this.options.Value.CollectionQuantum <= TimeSpan.Zero)
{
throw new OrleansConfigurationException(
$"{nameof(GrainCollectionOptions.CollectionQuantum)} is set to {options.Value.CollectionQuantum}. " +
$"{nameof(GrainCollectionOptions.CollectionQuantum)} must be greater than 0");
}
if (this.options.Value.CollectionAge <= this.options.Value.CollectionQuantum)
{
throw new OrleansConfigurationException(
$"{nameof(GrainCollectionOptions.CollectionAge)} is set to {options.Value.CollectionAge}. " +
$"{nameof(GrainCollectionOptions.CollectionAge)} must be greater than {nameof(GrainCollectionOptions.CollectionQuantum)}, " +
$"which is set to {this.options.Value.CollectionQuantum}");
}
foreach(var classSpecificCollectionAge in this.options.Value.ClassSpecificCollectionAge)
{
if (classSpecificCollectionAge.Value <= this.options.Value.CollectionQuantum)
{
throw new OrleansConfigurationException(
$"{classSpecificCollectionAge.Key} CollectionAgeLimit is set to {classSpecificCollectionAge.Value}. " +
$"CollectionAgeLimit must be greater than {nameof(GrainCollectionOptions.CollectionQuantum)}, " +
$"which is set to {this.options.Value.CollectionQuantum}");
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZoomToPointComponent : MonoBehaviour {
public Vector3 targetPoint;
public float pauseTime = 0.5f;
public float timeToZoom = 0.25f;
private float originalSize;
private float targetSize;
private float elapsedTime = 0f;
private Vector3 originalPosition;
private bool isZoomingTo = true;
private bool isPausing = false;
// Use this for initialization
void Start () {
originalPosition = Camera.main.transform.position;
targetPoint.z = originalPosition.z;
originalSize = Camera.main.orthographicSize;
targetSize = originalSize/2f;
}
// Update is called once per frame
void Update () {
elapsedTime += TimeUtils.ThrottledDelta(1f/30f);
if(isPausing){
if(elapsedTime >= pauseTime){
elapsedTime = 0f;
isPausing = false;
}
}else if(isZoomingTo){
float position = elapsedTime/timeToZoom;
Camera.main.transform.position = Vector3.Lerp(originalPosition, targetPoint, position);
Camera.main.orthographicSize = Mathf.Lerp(originalSize, targetSize, position);
if(elapsedTime >= timeToZoom){
isZoomingTo = false;
isPausing = true;
elapsedTime = 0f;
}
}else{
float position = elapsedTime/(2f*timeToZoom);
Camera.main.transform.position = Vector3.Lerp(targetPoint, originalPosition, position);
Camera.main.orthographicSize = Mathf.Lerp(targetSize, originalSize, position);
if(elapsedTime >= (2f*timeToZoom)){
Destroy(this);
}
}
}
}
|
using TfsLamp.HtmlRendering.ViewModel;
namespace TfsLamp.HtmlRendering.Rendering
{
public interface IHtmlStringRenderer
{
string RenderHmtl(ChangesViewModel viewModel);
}
} |
// ZipStream.cs created with MonoDevelop
// User: alan at 15:16 20/10/2008
//
// To change standard headers go to Edit->Preferences->Coding->Standard Headers
//
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace zipsharp
{
class ZipStream : Stream
{
const int ZLIB_FILEFUNC_SEEK_CUR = 1;
const int ZLIB_FILEFUNC_SEEK_END = 2;
const int ZLIB_FILEFUNC_SEEK_SET = 0;
bool canRead;
bool canSeek;
bool canWrite;
public override bool CanRead {
get { return canRead; }
}
public override bool CanSeek {
get { return canSeek; }
}
public override bool CanWrite {
get { return canWrite; }
}
public override bool CanTimeout {
get { return false; }
}
private Stream DataStream {
get; set;
}
public ZlibFileFuncDef IOFunctions {
get; set;
}
public override long Length {
get { return DataStream.Length; }
}
bool OwnsStream {
get; set;
}
public override long Position {
get { return DataStream.Position; }
set { DataStream.Position = value; }
}
public ZipStream (Stream dataStream, bool ownsStream)
{
// FIXME: Not necessarily true
canRead = true;
canSeek = true;
canWrite = true;
DataStream = dataStream;
OwnsStream = ownsStream;
ZlibFileFuncDef f = new ZlibFileFuncDef();
f.opaque = IntPtr.Zero;
f.zclose_file = CloseFile_Native;
f.zerror_file = TestError_Native;
f.zopen_file = OpenFile_Native;
f.zread_file = ReadFile_Native;
f.zseek_file = SeekFile_Native;
f.ztell_file = TellFile_Native;
f.zwrite_file = WriteFile_Native;
IOFunctions = f;
}
protected override void Dispose(bool disposing)
{
if (!disposing)
return;
DataStream.Flush ();
if (OwnsStream)
DataStream.Dispose ();
}
public override void Flush()
{
DataStream.Flush ();
}
public override int Read(byte[] buffer, int offset, int count)
{
return DataStream.Read (buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
DataStream.Seek (offset, origin);
return DataStream.Position;
}
public override void SetLength(long value)
{
DataStream.SetLength (value);
}
public override void Write(byte[] buffer, int offset, int count)
{
DataStream.Write (buffer, offset, count);
Flush ();
}
int CloseFile_Native (IntPtr opaque, IntPtr stream)
{
Close ();
return 0;
}
IntPtr OpenFile_Native (IntPtr opaque, string filename, int mode)
{
// always success. The stream is opened in managed code
return new IntPtr (1);
}
unsafe IntPtr ReadFile_Native (IntPtr opaque, IntPtr stream, IntPtr buffer, IntPtr size)
{
int count = size.ToInt32 ();
byte[] b = new byte[count];
int read;
try {
read = Math.Max (0, Read (b, 0, count));
byte* ptrBuffer = (byte*) buffer.ToPointer ();
for (int i = 0; i < count && i < read; i ++)
ptrBuffer[i] = b[i];
} catch {
read = -1;
}
return new IntPtr (read);
}
IntPtr SeekFile_Native (IntPtr opaque, IntPtr stream, IntPtr offset, int origin)
{
SeekOrigin seek;
if (origin == ZipStream.ZLIB_FILEFUNC_SEEK_CUR)
seek = SeekOrigin.Current;
else if (origin == ZLIB_FILEFUNC_SEEK_END)
seek = SeekOrigin.End;
else if (origin == ZLIB_FILEFUNC_SEEK_SET)
seek = SeekOrigin.Begin;
else
return new IntPtr (-1);
Seek (offset.ToInt64 (), seek);
return new IntPtr (0);
}
IntPtr TellFile_Native (IntPtr opaque, IntPtr stream)
{
if (IntPtr.Size == 4)
return new IntPtr ((int)Position);
else if (IntPtr.Size == 8)
return new IntPtr (Position);
else
return new IntPtr (-1);
}
int TestError_Native (IntPtr opaque, IntPtr stream)
{
// No errors here.
return 0;
}
unsafe IntPtr WriteFile_Native (IntPtr opaque, IntPtr stream, IntPtr buffer, /* ulong */ IntPtr size)
{
int count = size.ToInt32 ();
byte[] b = new byte[count];
byte* ptrBuffer = (byte*) buffer.ToPointer ();
for (int i = 0; i < count; i ++)
b[i] = ptrBuffer[i];
try {
Write (b, 0, count);
} catch {
}
return new IntPtr (count);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace EDO.DataCategory.BookForm
{
/// <summary>
/// SelectMetaDataWindow.xaml の相互作用ロジック
/// </summary>
public partial class SelectMetaDataWindow : Window
{
private SelectMetaDataWindowVM viewModel;
public SelectMetaDataWindow(SelectMetaDataWindowVM viewModel)
{
InitializeComponent();
this.viewModel = viewModel;
DataContext = viewModel;
}
private void okButton_Clicked(object sender, RoutedEventArgs e)
{
if (viewModel.IsSelectable && viewModel.SelectedObject == null)
{
MessageBox.Show(Properties.Resources.IsNotSelected);
return;
}
this.DialogResult = true;
}
private void cancelButton_Clicked(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
viewModel.Filter(textBox.Text);
//ここでセットしなおさないとリフレッシュされない
listBox.ItemsSource = viewModel.Objects;
}
}
}
|
using System;
using System.Collections.Generic;
using QuickGraph.Algorithms.Services;
using System.Diagnostics.Contracts;
namespace QuickGraph.Algorithms.Search
{
/// <summary>
/// A depth and height first search algorithm for directed graphs
/// </summary>
/// <remarks>
/// This is a modified version of the classic DFS algorithm
/// where the search is performed both in depth and height.
/// </remarks>
/// <reference-ref
/// idref="gross98graphtheory"
/// chapter="4.2"
/// />
#if !SILVERLIGHT
[Serializable]
#endif
public sealed class BidirectionalDepthFirstSearchAlgorithm<TVertex, TEdge> :
RootedAlgorithmBase<TVertex, IBidirectionalGraph<TVertex, TEdge>>,
IVertexColorizerAlgorithm<TVertex, TEdge>,
ITreeBuilderAlgorithm<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
private IDictionary<TVertex, GraphColor> colors;
private int maxDepth = int.MaxValue;
public BidirectionalDepthFirstSearchAlgorithm(IBidirectionalGraph<TVertex, TEdge> g)
: this(g, new Dictionary<TVertex, GraphColor>())
{ }
public BidirectionalDepthFirstSearchAlgorithm(
IBidirectionalGraph<TVertex, TEdge> visitedGraph,
IDictionary<TVertex, GraphColor> colors
)
: this(null, visitedGraph, colors)
{ }
public BidirectionalDepthFirstSearchAlgorithm(
IAlgorithmComponent host,
IBidirectionalGraph<TVertex, TEdge> visitedGraph,
IDictionary<TVertex, GraphColor> colors
)
: base(host, visitedGraph)
{
Contract.Requires(colors != null);
this.colors = colors;
}
public IDictionary<TVertex, GraphColor> VertexColors
{
get
{
return this.colors;
}
}
public GraphColor GetVertexColor(TVertex vertex)
{
return this.colors[vertex];
}
public int MaxDepth
{
get
{
return this.maxDepth;
}
set
{
this.maxDepth = value;
}
}
public event VertexAction<TVertex> InitializeVertex;
private void OnInitializeVertex(TVertex v)
{
var eh = this.InitializeVertex;
if (eh != null)
eh(v);
}
public event VertexAction<TVertex> StartVertex;
private void OnStartVertex(TVertex v)
{
var eh = this.StartVertex;
if (eh != null)
eh(v);
}
public event VertexAction<TVertex> DiscoverVertex;
private void OnDiscoverVertex(TVertex v)
{
var eh = this.DiscoverVertex;
if (eh != null)
eh(v);
}
public event EdgeAction<TVertex, TEdge> ExamineEdge;
private void OnExamineEdge(TEdge e)
{
var eh = this.ExamineEdge;
if (eh != null)
eh(e);
}
public event EdgeAction<TVertex, TEdge> TreeEdge;
private void OnTreeEdge(TEdge e)
{
var eh = this.TreeEdge;
if (eh != null)
eh(e);
}
public event EdgeAction<TVertex, TEdge> BackEdge;
private void OnBackEdge(TEdge e)
{
var eh = this.BackEdge;
if (eh != null)
eh(e);
}
public event EdgeAction<TVertex, TEdge> ForwardOrCrossEdge;
private void OnForwardOrCrossEdge(TEdge e)
{
var eh = this.ForwardOrCrossEdge;
if (eh != null)
eh(e);
}
public event VertexAction<TVertex> FinishVertex;
private void OnFinishVertex(TVertex v)
{
var eh = this.FinishVertex;
if (eh != null)
eh(v);
}
protected override void InternalCompute()
{
// put all vertex to white
Initialize();
// if there is a starting vertex, start whith him:
TVertex rootVertex;
if (this.TryGetRootVertex(out rootVertex))
{
OnStartVertex(rootVertex);
Visit(rootVertex, 0);
}
// process each vertex
var cancelManager = this.Services.CancelManager;
foreach (var u in VisitedGraph.Vertices)
{
if (cancelManager.IsCancelling) return;
if (VertexColors[u] == GraphColor.White)
{
OnStartVertex(u);
Visit(u, 0);
}
}
}
protected override void Initialize()
{
base.Initialize();
this.VertexColors.Clear();
foreach (var u in VisitedGraph.Vertices)
{
VertexColors[u] = GraphColor.White;
OnInitializeVertex(u);
}
}
public void Visit(TVertex u, int depth)
{
Contract.Requires(u != null);
if (depth > this.maxDepth)
return;
VertexColors[u] = GraphColor.Gray;
OnDiscoverVertex(u);
var cancelManager = this.Services.CancelManager;
foreach (var e in VisitedGraph.OutEdges(u))
{
if (cancelManager.IsCancelling) return;
OnExamineEdge(e);
var v = e.Target;
ProcessEdge(depth, v, e);
}
foreach (var e in VisitedGraph.InEdges(u))
{
if (cancelManager.IsCancelling) return;
OnExamineEdge(e);
var v = e.Source;
ProcessEdge(depth, v, e);
}
VertexColors[u] = GraphColor.Black;
OnFinishVertex(u);
}
private void ProcessEdge(int depth, TVertex v, TEdge e)
{
GraphColor c = VertexColors[v];
if (c == GraphColor.White)
{
OnTreeEdge(e);
Visit(v, depth + 1);
}
else if (c == GraphColor.Gray)
{
OnBackEdge(e);
}
else
{
OnForwardOrCrossEdge(e);
}
}
}
}
|
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using TinyHealthCheck.Models;
namespace TinyHealthCheck.HealthChecks
{
/// <summary>
/// This health check returns a simple 'Healthy' status, as well as an uptime counter.
/// </summary>
public class BasicHealthCheckWithUptime : IHealthCheck
{
private DateTimeOffset processStartTime = DateTimeOffset.Now;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
/// <inheritdoc/>
public async Task<IHealthCheckResult> ExecuteAsync(CancellationToken cancellationToken)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
{
var responseBody = new
{
Status = "Healthy!",
Uptime = (DateTimeOffset.Now - processStartTime).ToString()
};
return new JsonHealthCheckResult(responseBody, HttpStatusCode.OK);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelController : MonoBehaviour
{
public GameObject startPlatform;
public Transform endPlatform;
public Vector3 endPlatformOffset;
public List<LevelConfig> levels;
public int levelIndex;
public LevelConfig currentLevel;
public PlatformFactory factory;
public List<GameObject> levelObjects;
public void CreateLevel(int levelIndex)
{
this.levelIndex = levelIndex;
if (levelIndex< levels.Count)
{
levelObjects = new List<GameObject>();
currentLevel = levels[levelIndex];
for(int i = 0;i< currentLevel.platforms.Count;i++)
{
PlatformConfig config = levels[levelIndex].platforms[i];
IPlatform platform = factory.GetPlatform(config);
if (i == 0)
{
if (config.overrideLevelMultiplier)
{
levelObjects.Add(platform.GetGameObj(config,startPlatform,config.levelMultiplier));
}
else
{
levelObjects.Add(platform.GetGameObj(config,startPlatform,currentLevel.levelMultiplier));
}
}
else
{
if (config.overrideLevelMultiplier)
{
levelObjects.Add(platform.GetGameObj(config,levelObjects[i -1],config.levelMultiplier));
}
else
{
levelObjects.Add(platform.GetGameObj(config,levelObjects[i -1],currentLevel.levelMultiplier));
}
}
}
Vector3 endPosition = factory.getEndingPosition(levelObjects[levelObjects.Count - 1]);
endPlatform.position = endPosition + endPlatformOffset;
endPlatform.gameObject.SetActive(true);
}
else
{
throw new Exception("Level count is: " + levels.Count + " You are passing level index: " + levelIndex);
}
}
public void DeactivateLevel()
{
foreach (var levelObject in levelObjects)
{
levelObject.SetActive(false);
factory.DeactivateObject(levelObject);
}
}
}
|
using Juce.SceneManagement.Reference;
namespace Juce.SceneManagement.Group
{
[System.Serializable]
public class SceneGroupEntry
{
public SceneReference SceneReference = default;
public bool LoadAsActive = default;
}
}
|
namespace Epinova.ElasticSearch.Core.Models.Query
{
internal class Sort
{
public bool IsStringField { get; set; }
public string FieldName { get; set; }
public string Direction { get; set; }
}
} |
using System;
using System.Threading;
public class TypeAssistant
{
public event Action<string> Idled;
string Text;
Timer Timer;
public TypeAssistant()
{
Timer = new Timer(p => Idled(Text));
}
public void TextChanged(string text)
{
Text = text;
Timer.Change(500, Timeout.Infinite);
}
}
|
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// CustScpBillAmtVO Data Structure.
/// </summary>
public class CustScpBillAmtVO : AlipayObject
{
/// <summary>
/// 费用
/// </summary>
[JsonPropertyName("fee")]
public string Fee { get; set; }
/// <summary>
/// 本金
/// </summary>
[JsonPropertyName("prin")]
public string Prin { get; set; }
}
}
|
using System;
using FlubuCore.Context;
using FlubuCore.Context.Attributes;
using FlubuCore.Context.FluentInterface.TaskExtensions;
using FlubuCore.Scripting;
namespace FlubuCore.ConsoleTestApp
{
public class TestScriptWithAsync : DefaultBuildScript
{
protected override void ConfigureTargets(ITaskContext context)
{
var firstTarget = context.CreateTarget("FirstTarget").Do(t => { Console.WriteLine("display this to."); });
var nested = context.CreateTarget("ShouldAlsoBeDisplayed").Do(t => { Console.WriteLine("Should also be displayed"); })
.SetAsHidden()
.DependsOn(firstTarget);
var doExample = context.CreateTarget("DoExample")
.Do(t => { throw new Exception("error on purpose."); });
var doExample2 = context.CreateTarget("DoExample2")
.DependsOn(nested)
.Do(t => { Console.WriteLine("from doExample2"); });
var doExample3 = context.CreateTarget("DoExample3")
.Do(t => { Console.WriteLine("from doExample3"); });
context.CreateTarget("Test")
.SetAsDefault()
.AddTask(t => t.Do(x => { Console.WriteLine("from Test"); }))
.DependsOnAsync(doExample2, doExample)
.DependsOn(doExample3);
context.CreateTarget("Test2")
.SetAsDefault()
.AddTask(t => t.Do(x => { Console.WriteLine("from Test"); }));
}
}
}
|
using DCSoft.RTF;
using System;
using System.Text;
namespace DCSoftDotfuscate
{
internal class Class203 : Encoding
{
public static Class203 class203_0 = new Class203();
public override string GetString(byte[] bytes, int index, int count)
{
StringBuilder stringBuilder = new StringBuilder();
int num = Math.Min(bytes.Length - 1, index + count - 1);
for (int i = index; i <= num; i++)
{
stringBuilder.Append(System.Convert.ToChar(bytes[i]));
}
return stringBuilder.ToString();
}
public override int GetByteCount(char[] chars, int index, int count)
{
throw new Exception(RTFResource.NotImplemented);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
throw new Exception(RTFResource.NotImplemented);
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
throw new Exception(RTFResource.NotImplemented);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
throw new Exception(RTFResource.NotImplemented);
}
public override int GetMaxByteCount(int charCount)
{
throw new Exception(RTFResource.NotImplemented);
}
public override int GetMaxCharCount(int byteCount)
{
throw new Exception(RTFResource.NotImplemented);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IntepreterProgram
{
class FilesHelper
{
static string getFilename(string path)
{
string []names = path.Split('\\');
return names[names.Length - 1];
}
public static string OpenFile(ref TabControl tabControl)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Multiselect = false;
openFile.Filter = "CMM程序|*.cmm";
string allFiles;
if (DialogResult.OK == openFile.ShowDialog())
{
allFiles = openFile.FileName;
}
else
{
return "";
}
StreamReader reader = new StreamReader(allFiles);
string Source = "";
while (!reader.EndOfStream)
{
Source += reader.ReadLine() + "\r\n";
}
TextBox textBox = new TextBox();
TabPage newtab = new TabPage();
newtab.Controls.Add(textBox);
newtab.Size = new System.Drawing.Size(tabControl.Size.Width - 9, tabControl.Size.Height - 24);
newtab.Text = getFilename(allFiles);
textBox.Name = "CMtext";
textBox.Size = newtab.Size;
textBox.Multiline = true;
textBox.Text = Source;
tabControl.Controls.Add(newtab);
textBox.ScrollBars = ScrollBars.Both;
return allFiles;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace LanguageImplementation.DataTypes
{
public class PyFunction : PyObject, IPyCallable
{
// needs a reference to:
// 1. CodeObject
// 2. Globals (and how does it get this? When would it be created?)
private CodeObject _code;
public Dictionary<string, object> Globals;
public CodeObject Code
{
get
{
return _code;
}
set
{
_code = value;
}
}
public PyFunction()
{
// Default constructor so DefaultNew will work.
}
public PyFunction(CodeObject callable, Dictionary<string, object> globals)
{
Initialize(callable, globals);
}
public void Initialize(CodeObject callable, Dictionary<string, object> globals)
{
Code = callable;
Globals = globals;
__setattr__("__call__", this);
__setattr__("__code__", this);
__setattr__("__globals__", Globals);
}
public Task<object> Call(IInterpreter interpreter, FrameContext context, object[] args)
{
return interpreter.CallInto(context, this, args, Globals);
}
public static PyFunction Create(CodeObject co, Dictionary<string, object> globals)
{
var function = PyTypeObject.DefaultNew<PyFunction>(PyFunctionClass.Instance);
function.Initialize(co, globals);
return function;
}
}
public class PyFunctionClass : PyClass
{
public PyFunctionClass(PyFunction __init__) :
base("function", __init__, new PyClass[0])
{
__instance = this;
// We have to replace PyTypeObject.DefaultNew with one that creates a PyFunctionClass.
// TODO: Can this be better consolidated?
Expression<Action<PyTypeObject>> expr = instance => DefaultNew<PyFunction>(null);
var methodInfo = ((MethodCallExpression)expr.Body).Method;
__new__ = new WrappedCodeObject("__new__", methodInfo, this);
}
private static PyFunctionClass __instance;
public static PyFunctionClass Instance
{
get
{
if (__instance == null)
{
__instance = new PyFunctionClass(null);
}
return __instance;
}
}
}
} |
using System.Linq;
using Microsoft.EntityFrameworkCore;
using HotelCalifornia.Backend.Database.Initializer.Seeders;
namespace HotelCalifornia.Backend.Database.Initializer
{
public class DbInitializer : IDbInitializer
{
private readonly DatabaseContext FDatabaseContext;
public DbInitializer(DatabaseContext ADatabaseContext) => FDatabaseContext = ADatabaseContext;
public void StartMigration() => FDatabaseContext.Database.Migrate();
public void SeedData()
{
if (!FDatabaseContext.Rooms.Any())
FDatabaseContext.Rooms.AddRange(RoomsSeeder.SeedRooms());
FDatabaseContext?.SaveChanges();
}
}
}
|
using System.Windows;
namespace MattermostAddinConnect.Security
{
/// <summary>
/// Interaction logic for PasswordDialog.xaml
/// </summary>
public partial class PasswordDialog
{
public PasswordDialog()
{
InitializeComponent();
}
private void OnOkClick(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
private void OnCancelClick(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
}
}
} |
using System.ComponentModel.DataAnnotations;
using static MobilesShop.Data.DataConstants;
namespace MobilesShop.Web.Models.CameraTypes
{
public class CameraTypeAddFormModel
{
[Required]
[StringLength(CameraTypeNameMaxLength, MinimumLength = CameraTypeNameMinLength)]
public string Name { get; init; }
}
}
|
namespace GameCreator.Stats
{
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using GameCreator.Core;
[CustomEditor(typeof(StatUI))]
public class StatUIEditor : Editor
{
private const string PROP_TARGET = "target";
private const string PROP_STAT = "stat";
private const string PROP_ICON = "icon";
private const string PROP_COLOR = "color";
private const string PROP_TITLE = "title";
private const string PROP_DESCR = "description";
private const string PROP_SHORT = "shortName";
private const string PROP_VALUE = "value";
private const string PROP_IMGFI = "imageFill";
// PROPERTIES: ----------------------------------------------------------------------------
private SerializedProperty spTarget;
private SerializedProperty spStat;
private SerializedProperty spTitle;
private SerializedProperty spDescription;
private SerializedProperty spShortName;
private SerializedProperty spIcon;
private SerializedProperty spColor;
private SerializedProperty spValue;
private SerializedProperty spImageFill;
// INITIALIZERS: --------------------------------------------------------------------------
private void OnEnable()
{
this.spTarget = serializedObject.FindProperty(PROP_TARGET);
this.spStat = serializedObject.FindProperty(PROP_STAT);
this.spIcon = serializedObject.FindProperty(PROP_ICON);
this.spColor = serializedObject.FindProperty(PROP_COLOR);
this.spTitle = serializedObject.FindProperty(PROP_TITLE);
this.spDescription = serializedObject.FindProperty(PROP_DESCR);
this.spShortName = serializedObject.FindProperty(PROP_SHORT);
this.spValue = serializedObject.FindProperty(PROP_VALUE);
this.spImageFill = serializedObject.FindProperty(PROP_IMGFI);
}
// PAINT METHODS: -------------------------------------------------------------------------
public override void OnInspectorGUI()
{
if (target == null || serializedObject == null) return;
serializedObject.Update();
EditorGUILayout.PropertyField(this.spTarget);
EditorGUILayout.PropertyField(this.spStat);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(this.spIcon);
EditorGUILayout.PropertyField(this.spColor);
EditorGUILayout.PropertyField(this.spTitle);
EditorGUILayout.PropertyField(this.spDescription);
EditorGUILayout.PropertyField(this.spShortName);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(this.spValue);
EditorGUILayout.PropertyField(this.spImageFill);
serializedObject.ApplyModifiedProperties();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Chat.Net.Protocol
{
/// <summary>
/// Represents a case when and unexpected message type was recieved
/// </summary>
public class SimpleProtocolViolationException : ProtocolViolationException
{
public SimpleProtocolViolationException(MessageType expected, MessageType recieved)
: base("Expected message of type '" + expected.Name + "', but recieved '" + recieved.Name + "'")
{
}
}
public class MissingMessageProtocolViolationException : ProtocolViolationException
{
public MissingMessageProtocolViolationException(MessageType expected)
: base("Expected message of type '" + expected.Name + "', but none was recived within the ")
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CollisionDetect3 : MonoBehaviour
{
public GameObject A;
void Start()
{
gameObject.GetComponent<PlayerController>().enabled = false;
}
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag.Equals("obstacle"))
{
SceneManager.LoadScene("LV3sel");
}
if (other.gameObject.tag.Equals("goal"))
{
A.GetComponent<Renderer>().enabled = true;
}
if (other.gameObject.tag.Equals("faster"))
{
gameObject.GetComponent<PlayerController2>().enabled = false;
gameObject.GetComponent<PlayerController>().enabled = true;
}
}
} |
using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using System.Collections.Generic;
using Verse;
namespace VFECore
{
using System.Reflection.Emit;
[StaticConstructorOnStartup]
public static class UIUtilityData
{
public static Dictionary<FactionDef, int> factionCounts = new Dictionary<FactionDef, int>();
}
[HarmonyPatch(typeof(WorldFactionsUIUtility), "DoWindowContents")]
public static class Patch_WorldFactionsUIUtility
{
[HarmonyPostfix]
public static void Postfix(ref Dictionary<FactionDef, int> factionCounts)
{
foreach (var item in factionCounts)
{
UIUtilityData.factionCounts.SetOrAdd(item.Key, item.Value);
}
}
}
[HarmonyPatch(typeof(WorldFactionsUIUtility), nameof(WorldFactionsUIUtility.DoRow))]
public static class Patch_WorldFactionsUIUtility_DoRow
{
[HarmonyTranspiler]
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
{
foreach (CodeInstruction instruction in instructions)
{
if (instruction.opcode == OpCodes.Stloc_2)
{
yield return new CodeInstruction(OpCodes.Pop);
yield return new CodeInstruction(OpCodes.Ldc_I4_0);
}
yield return instruction;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace LitCAD.Commands
{
/// <summary>
/// 命令管理器
/// </summary>
internal class CommandsMgr
{
/// <summary>
/// Presenter
/// </summary>
private Presenter _presenter = null;
public Presenter presenter
{
get { return _presenter; }
}
/// <summary>
/// 命令完成事件
/// </summary>
public delegate void CommandEvent(Command cmd);
public event CommandEvent commandFinished;
public event CommandEvent commandCanceled;
/// <summary>
/// 命令列表
/// </summary>
private List<Command> _undoCmds = new List<Command>();
private List<Command> _redoCmds = new List<Command>();
internal bool canUndo
{
get { return _undoCmds.Count > 0; }
}
internal bool canRedo
{
get { return _redoCmds.Count > 0; }
}
/// <summary>
/// 当前命令
/// </summary>
private Command _currentCmd = null;
public Command CurrentCmd
{
get { return _currentCmd; }
}
/// <summary>
/// 构造函数
/// </summary>
public CommandsMgr(Presenter presenter)
{
_presenter = presenter;
}
/// <summary>
/// 执行命令
/// </summary>
public void DoCommand(Command cmd)
{
if (_currentCmd != null)
{
return;
}
_currentCmd = cmd;
_currentCmd.cmdMgr = this;
_currentCmd.Initialize();
}
/// <summary>
/// 完成当前命令
/// </summary>
public void FinishCurrentCommand()
{
if (_currentCmd != null)
{
_currentCmd.Finish();
if (_currentCmd is Edit.UndoCmd)
{
this.Undo();
}
else if (_currentCmd is Edit.RedoCmd)
{
this.Redo();
}
else
{
_undoCmds.Add(_currentCmd);
_redoCmds.Clear();
}
commandFinished.Invoke(_currentCmd);
_currentCmd = null;
}
}
/// <summary>
/// 取消当前命令
/// </summary>
public void CancelCurrentCommand()
{
if (_currentCmd != null)
{
_currentCmd.Cancel();
commandCanceled.Invoke(_currentCmd);
_currentCmd = null;
}
}
/// <summary>
/// 撤销
/// </summary>
private void Undo()
{
if (_undoCmds.Count == 0)
{
return;
}
Command cmd = _undoCmds[_undoCmds.Count - 1];
_undoCmds.RemoveAt(_undoCmds.Count - 1);
cmd.Undo();
_redoCmds.Add(cmd);
}
/// <summary>
/// 重做
/// </summary>
private void Redo()
{
if (_redoCmds.Count == 0)
{
return;
}
Command cmd = _redoCmds[_redoCmds.Count - 1];
_redoCmds.RemoveAt(_redoCmds.Count - 1);
cmd.Redo();
_undoCmds.Add(cmd);
}
/// <summary>
/// 绘制
/// </summary>
public void OnPaint(Graphics g)
{
if (_currentCmd != null)
{
_currentCmd.OnPaint(g);
}
}
/// <summary>
/// Mouse Down
/// </summary>
public void OnMouseDown(MouseEventArgs e)
{
if (_currentCmd != null)
{
_currentCmd.OnMouseDown(e);
}
}
/// <summary>
/// Mouse Up
/// </summary>
public void OnMouseUp(MouseEventArgs e)
{
if (_currentCmd != null)
{
_currentCmd.OnMouseUp(e);
}
}
/// <summary>
/// Mouse Move
/// </summary>
public void OnMouseMove(MouseEventArgs e)
{
if (_currentCmd != null)
{
_currentCmd.OnMouseMove(e);
}
}
/// <summary>
/// Key Down
/// </summary>
public void OnKeyDown(KeyEventArgs e)
{
if (_currentCmd != null)
{
Command.EventResult eRet = _currentCmd.OnKeyDown(e);
if (eRet.status == Command.EventResultStatus.Unhandled)
{
if (e.KeyCode == Keys.Escape)
{
this.CancelCurrentCommand();
}
}
}
}
/// <summary>
/// Key Up
/// </summary>
public void OnKeyUp(KeyEventArgs e)
{
if (_currentCmd != null)
{
Command.EventResult eRet = _currentCmd.OnKeyUp(e);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _05.Clock
{
class Program
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
var widht = 2 * n + 1;
var height = 2 * n + 1;
var dots_on_top = widht - 4;
//upper 2 rows
Console.WriteLine(new string('*', 2 * n + 1));
Console.Write(".*");
Console.Write(new string(' ', dots_on_top));
Console.WriteLine("*.");
//first half
var first_half_height = n - 2;
var dots_on_top_first_half = 2;
var stars_on_top_first_half = 1;
var monkey_first_half = (2 * n + 1) - 2 * (dots_on_top_first_half - stars_on_top_first_half) - 4;
for (int i = 1; i <= first_half_height; i++)
{
Console.Write(new string('.', dots_on_top_first_half));
Console.Write("*");
Console.Write(new string('@', monkey_first_half));
Console.Write("*");
Console.WriteLine(new string('.', dots_on_top_first_half));
dots_on_top_first_half++;
monkey_first_half = monkey_first_half - 2;
}
//middle row
Console.WriteLine("{0}{1}{0}", new string('.', n), "*");
//second half
var dots_second_half = n - 1;
var second_half_height = n - 2;
var dots_inside = 0;
for (int i = 1; i <=second_half_height; i++)
{
Console.Write(new string('.', dots_second_half));
Console.Write("*");
Console.Write(new string(' ',dots_inside));
Console.Write("@");
Console.Write(new string(' ', dots_inside));
Console.Write("*");
Console.WriteLine(new string('.', dots_second_half));
dots_second_half--;
dots_inside++;
}
//bottom 2 rows
Console.Write(".*");
Console.Write(new string('@',2*n+1-4));
Console.WriteLine("*.");
Console.WriteLine(new string('*', 2 * n + 1));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace RefrienderCore {
static class LongEnumerable {
internal static IEnumerable<long> Range(long start, long count) {
while(count-- != 0)
yield return start++;
}
internal static IEnumerable<T> ParallelRange<T>(long start, long count,
Func<ParallelQuery<long>, ParallelQuery<T>> query
) {
var ret = Enumerable.Empty<T>();
const int chunk = 0x40000000;
for(var i = start; i < count; i += chunk)
ret = ret.Concat(query(Enumerable.Range(0, (int) Math.Min(count - i, chunk)).AsParallel()
.Select(j => i + j)).ToList());
return ret;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LevelManagerSTUB : MonoBehaviour
{
public GameObject gameOverPanel;
public Text textLife;
private PlayerLife playerLife;
private string currentSceneName;
void Awake()
{
playerLife = FindObjectOfType<PlayerLife>();
RevivePlayer();
playerLife.OnLifeChange += ResolveLifeChange;
}
void OnApplicationQuit()
{
playerLife.OnLifeChange -= ResolveLifeChange;
}
private void ResolveLifeChange(Player player, int currentLife)
{
//textLife.text = playerLife.currentLife.ToString();
if (currentLife <= 0)
{
GameOver();
}
}
void Start()
{
GameManager.Instance.ReadyTheBall();
}
public void RevivePlayer()
{
playerLife.SetLifeToMax();
//textLife.text = playerLife.currentLife.ToString();
gameOverPanel.SetActive(false);
}
public void ReloadScene()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void GameOver()
{
gameOverPanel.SetActive(true);
}
}
|
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
<body>
<ul class="menu">
<li>@Html.ActionLink("Basic Form Demo","index","BasicDemo" )</li>
<li>@Html.ActionLink("Simple Ajax Demo", "Simple", "AjaxDemo")</li>
<li>@Html.ActionLink("Form Ajax Demo", "Form", "AjaxDemo")</li>
<li>@Html.ActionLink("Custom ActionResult Demo", "index", "CustomActionDemo")</li>
<li>@Html.ActionLink("Custom View Enmgine Demo", "TransformedView", "CustomViewEngine")</li>
<li>@Html.ActionLink("Jasmine Tests","Run","Jasmine")</li>
</ul>
@RenderBody()
</body>
<script></script>
</html>
|
using System.Threading.Tasks;
using Refit;
using RefitVsRestSharp.Server.Views;
using RefitVsRestSharp.Test.Apis;
using RestSharp;
using Xunit;
namespace RefitVsRestSharp.Test
{
public class SimpleGet
{
[Fact]
public async Task DoWithRestSharp()
{
var client = new RestClient("http://localhost:5000");
var request = new RestRequest("api/users/{username}");
request.AddUrlSegment("username", "TestUser");
IRestResponse<User> response = await client.ExecuteAsync<User>(request);
User user = response.Data;
AssertResult(user);
}
[Fact]
public async Task DoWithRefit()
{
var api = RestService.For<IUsers>("http://localhost:5000");
User user = await api.Get("TestUser");
AssertResult(user);
}
private void AssertResult(User user)
{
Assert.NotNull(user);
Assert.Equal("TestUser", user.Name);
}
}
} |
using UnityEngine;
[RequireComponent(typeof(SphereCollider))]
public class SightLine : MonoBehaviour
{
public Transform EyePoint;
public string TargetTag = "Player";
public float FieldOfView = 45f;
public bool IsTargetInSightLine { get; set; } = false;
public Vector3 LastKnowSighting { get; set; } = Vector3.zero;
private SphereCollider ThisCollider;
void Awake()
{
ThisCollider = GetComponent<SphereCollider>();
LastKnowSighting = transform.position;
}
void OnTriggerStay(Collider Other)
{
if (Other.CompareTag(TargetTag))
{
UpdateSight(Other.transform);
}
}
void OnTriggerExit(Collider Other)
{
if (Other.CompareTag(TargetTag)) { IsTargetInSightLine = false; }
}
private bool HasClearLineofSightToTarget(Transform Target)
{
RaycastHit Info;
Vector3 DirToTarget = (Target.position - EyePoint.position).normalized;
if (Physics.Raycast(EyePoint.position, DirToTarget, out Info, ThisCollider.radius))
{
if (Info.transform.CompareTag(TargetTag))
{
return true;
}
}
return false;
}
private bool TargetInFOV(Transform Target)
{
Vector3 DirToTarget = Target.position - EyePoint.position;
float Angle = Vector3.Angle(EyePoint.forward, DirToTarget);
if (Angle <= FieldOfView)
{
return true;
}
return false;
}
private void UpdateSight(Transform Target)
{
IsTargetInSightLine = HasClearLineofSightToTarget(Target) && TargetInFOV(Target);
if (IsTargetInSightLine)
{
LastKnowSighting = Target.position;
}
}
}
|
// Copyright 2009 Andy Kernahan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics;
using System.IO;
using AK.F1.Timing.Messages.Feed;
using AK.F1.Timing.Serialization;
namespace AK.F1.Timing.Playback
{
/// <summary>
/// Provides a <see cref="AK.F1.Timing.IMessageReader"/> decorator which records
/// the <see cref="AK.F1.Timing.Message"/>s read from an inner
/// <see cref="AK.F1.Timing.IMessageReader"/>.
/// </summary>
public class RecordingMessageReader : MessageReaderBase
{
#region Private Fields.
/// <summary>
/// The minimum delay to insert between messages. Delays smaller than this value are
/// ignored. This field is <see langword="readonly"/>.
/// </summary>
private static readonly TimeSpan MinMessageDelay = TimeSpan.FromMilliseconds(1);
#endregion
#region Public Interface.
/// <summary>
/// Initialises a new instance of the <see cref="RecordingMessageReader"/> class and
/// specified the inner message reader and the output file path.
/// </summary>
/// <param name="inner">The inner message reader.</param>
/// <param name="path">The output file path.</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when <paramref name="inner"/> or <paramref name="path"/> is
/// <see langword="null"/>.
/// </exception>
/// <exception cref="System.IO.IOException">
/// Thrown when an IO error occurs whilst creating the internal
/// <see cref="System.IO.FileStream"/> using the supplied arguments.
/// </exception>
public RecordingMessageReader(IMessageReader inner, string path)
{
Guard.NotNull(inner, "inner");
Initialise(inner, new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None), true);
}
/// <summary>
/// Initialises a new instance of the <see cref="RecordingMessageReader"/> class and
/// specified the inner message reader, the output stream and a value indicating if the
/// decorator owns the output.
/// </summary>
/// <param name="inner">The inner message reader.</param>
/// <param name="output">The output stream.</param>
/// <param name="ownsOutput"><see langword="true"/> if the decorator owns the specified output
/// stream, otherwise; <see langword="false"/>.</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when <paramref name="inner"/> or <paramref name="output"/> is
/// <see langword="null"/>.
/// </exception>
public RecordingMessageReader(IMessageReader inner, Stream output, bool ownsOutput)
{
Guard.NotNull(inner, "inner");
Guard.NotNull(output, "output");
Initialise(inner, output, ownsOutput);
}
#endregion
/// <inheritdoc/>
protected override Message ReadImpl()
{
Message message;
if((message = Inner.Read()) != null)
{
WriteDelay();
Write(message);
}
else
{
// An end message delay is not required.
Write(null);
}
return message;
}
/// <inheritdoc/>
protected override void DisposeOfManagedResources()
{
DisposeOf(Writer);
DisposeOf(Inner);
if(OwnsOutput)
{
DisposeOf(Output);
}
}
#region Private Impl.
private void Initialise(IMessageReader inner, Stream output, bool ownsOutput)
{
Inner = inner;
Output = output;
OwnsOutput = ownsOutput;
Writer = new DecoratedObjectWriter(output);
Stopwatch = new Stopwatch();
}
private void WriteDelay()
{
if(Stopwatch.IsRunning)
{
var elapsed = Stopwatch.Elapsed;
var delay = elapsed - LastElapsed;
LastElapsed = elapsed;
if(delay >= MinMessageDelay)
{
Write(new SetNextMessageDelayMessage(delay));
}
}
else
{
Stopwatch.Start();
}
}
private void Write(Message message)
{
Writer.WriteMessage(message);
}
private IMessageReader Inner { get; set; }
private Stream Output { get; set; }
private IObjectWriter Writer { get; set; }
private Stopwatch Stopwatch { get; set; }
private TimeSpan LastElapsed { get; set; }
private bool OwnsOutput { get; set; }
#endregion
}
} |
using System;
using System.Collections.Generic;
using Caique.Parsing;
using Caique.Semantics;
namespace Caique.CheckedTree
{
public partial class CheckedBlockExpression : CheckedExpression
{
public List<CheckedStatement> Statements { get; }
public SymbolEnvironment Environment { get; }
public bool ReturnsLastExpression { get; }
public CheckedBlockExpression(List<CheckedStatement> statements,
SymbolEnvironment environment,
IDataType dataType,
bool returnsLastExpression) : base(dataType)
{
Statements = statements;
Environment = environment;
ReturnsLastExpression = returnsLastExpression;
}
}
} |
namespace Vodamep.Legacy.Model
{
public class VereinDTO
{
public string Vereinsnummer { get; set; }
public string Bezeichnung { get; set; }
}
}
|
//{[{
using Param_RootNamespace.Models;
//}]}
.ConfigureServices((context, services) =>
{
// Configuration
//{[{
services.Configure<LocalSettingsOptions>(context.Configuration.GetSection(nameof(LocalSettingsOptions)));
//}]}
|
using Duck.Content;
namespace Duck.Graphics.Shaders;
public class FragmentShader : AssetBase<FragmentShader>
{
#region Methods
public FragmentShader(AssetImportData importData)
: base(importData)
{
}
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace King_of_Thieves.Actors.Items.decoration
{
class CPot : CLiftable
{
public CPot() :
base()
{
_hitBox = new Collision.CHitBox(this, 16, 32, 16, 16);
swapImage("PotChillinLikeaVillain");
_velocity = new Microsoft.Xna.Framework.Vector2(1.5f, 1);
}
public override void timer1(object sender)
{
base.timer1(sender);
swapImage("PotBreaking");
}
protected override void _initializeResources()
{
base._initializeResources();
_imageIndex.Add("PotChillinLikeaVillain", new Graphics.CSprite("items:decor:potSmall"));
_imageIndex.Add("PotBreaking", new Graphics.CSprite("items:decor:potSmallBreak"));
}
}
}
|
using Craft.Net.Common;
using Craft.Net.Logic.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Craft.Net.Logic
{
public class PlayerEntity : LivingEntity
{
public PlayerEntity(string username) : base()
{
Username = username;
Food = 20;
Inventory = new InventoryWindow();
Abilities = new PlayerAbilities(this);
SelectedSlot = InventoryWindow.HotbarIndex;
}
public const double Width = 0.6;
public const double Height = 1.62;
public const double Depth = 0.6;
public override Size Size
{
get { return new Size(Width, Height, Depth); }
}
public override short MaxHealth
{
get { return 20; }
}
public string Username { get; set; }
public bool IsSprinting { get; set; }
public bool IsCrouching { get; set; }
public double PositiveDeltaY { get; set; }
public PlayerAbilities Abilities { get; set; }
public InventoryWindow Inventory { get; set; }
protected short _SelectedSlot;
public short SelectedSlot
{
get { return _SelectedSlot; }
set
{
_SelectedSlot = value;
OnPropertyChanged("SelectedSlot");
}
}
public ItemStack SelectedItem
{
get { return Inventory[SelectedSlot]; }
}
public ItemStack ItemInMouse { get; set; }
protected Vector3 _SpawnPoint;
public Vector3 SpawnPoint
{
get { return _SpawnPoint; }
set
{
_SpawnPoint = value;
OnPropertyChanged("SpawnPoint");
}
}
protected short _Food;
public short Food
{
get { return _Food; }
set
{
_Food = value;
OnPropertyChanged("Food");
}
}
protected float _FoodSaturation;
public float FoodSaturation
{
get { return _FoodSaturation; }
set
{
_FoodSaturation = value;
OnPropertyChanged("FoodSaturation");
}
}
protected float _FoodExhaustion;
public float FoodExhaustion
{
get { return _FoodExhaustion; }
set
{
_FoodExhaustion = value;
OnPropertyChanged("FoodExhaustion");
}
}
public event EventHandler<EntityEventArgs> PickUpItem;
public void OnPickUpItem(ItemEntity item)
{
if (PickUpItem != null) PickUpItem(this, new EntityEventArgs(item));
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Pallavolo.DA;
using Pallavolo.DA.Models;
namespace Pallavolo.WEB.Controllers {
public class SquadraController : Controller {
private readonly AppDbContext _context;
public SquadraController(AppDbContext _context) {
this._context = _context;
}
private bool SquadraExists(int id) {
return _context.Squadre.Any(squadra => squadra.Id == id);
}
// GET
public async Task<IActionResult> Index() {
return
View(await _context.Squadre.ToListAsync());
}
public async Task<IActionResult> Details(int? id) {
if (id == null) {
return NotFound();
}
var squarda = await _context.Squadre
.FirstOrDefaultAsync(squadra => squadra.Id == id);
if (squarda == null) {
return NotFound();
}
return View(squarda);
}
public IActionResult Create() {
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Nome,Id,Added,Modified,Deleted")]
Squadra squadra) {
if (ModelState.IsValid) {
_context.Add(squadra);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(squadra);
}
public async Task<IActionResult> Edit(int? id) {
if (id == null) {
return NotFound();
}
var squadra = await _context.Squadre.FindAsync(id);
if (squadra == null) {
return NotFound();
}
return View(squadra);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Nome,Id,Added,Modified,Deleted")]
Squadra squadra) {
if (id != squadra.Id) {
return NotFound();
}
if (ModelState.IsValid) {
try {
_context.Update(squadra);
await _context.SaveChangesAsync();
} catch (DbUpdateConcurrencyException) {
if (!SquadraExists(squadra.Id)) {
return NotFound();
} else {
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(squadra);
}
public async Task<IActionResult> Delete(int? id) {
if (id == null) {
return NotFound();
}
var squadra = await _context.Squadre.FirstOrDefaultAsync(s => s.Id == id);
if (squadra == null) {
return NotFound();
}
return View(squadra);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id) {
var squadra = await _context.Squadre.FindAsync(id);
_context.Squadre.Remove(squadra);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
} |
namespace CodeSearcher.Interfaces
{
public interface ISingleResultPrinter
{
void Print(string fileName, string searchedWord);
int NumbersToShow { get; set; }
}
}
|
//-------------------------------------------------------------
// <copyright company=�Microsoft Corporation�>
// Copyright � Microsoft Corporation. All Rights Reserved.
// </copyright>
//-------------------------------------------------------------
// @owner=alexgor, deliant
//=================================================================
// File: EmbedBorder.cs
//
// Namespace: System.Web.UI.WebControls[Windows.Forms].Charting.Borders3D
//
// Classes: EmbedBorder, FrameTitle1Border, FrameTitle2Border,
// FrameTitle3Border, FrameTitle4Border, FrameTitle5Border,
// FrameTitle6Border, FrameTitle7Border, FrameTitle8Border,
// FrameThin2Border, FrameThin3Border, FrameThin4Border,
// FrameThin5Border, FrameThin6Border, FrameThin1Border,
// RaisedBorder, SunkenBorder
//
// Purpose: Classes that implement different 3D border styles.
//
// Reviewed: AG - August 7, 2002
//
//===================================================================
#region Used namespaces
using System;
using System.Resources;
using System.Reflection;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel.Design;
#if WINFORMS_CONTROL
using System.Windows.Forms.DataVisualization.Charting;
using System.Windows.Forms.DataVisualization.Charting.Data;
using System.Windows.Forms.DataVisualization.Charting.ChartTypes;
using System.Windows.Forms.DataVisualization.Charting.Utilities;
using System.Windows.Forms.DataVisualization.Charting.Borders3D;
#else
using System.Web.UI.DataVisualization.Charting; using System.Web.UI.DataVisualization.Charting.Data;
using System.Web.UI.DataVisualization.Charting.Utilities;
#endif
#endregion
#if WINFORMS_CONTROL
namespace System.Windows.Forms.DataVisualization.Charting.Borders3D
#else
namespace System.Web.UI.DataVisualization.Charting.Borders3D
#endif
{
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameTitle1Border : FrameThin1Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameTitle1Border()
{
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize*2f);
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameTitle1";}}
public override float Resolution
{
set
{
base.Resolution = value;
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize * 2f);
}
}
/// <summary>
/// Returns the position of the rectangular area in the border where
/// title should be displayed. Returns empty rect if title can't be shown in the border.
/// </summary>
/// <returns>Title position in border.</returns>
public override RectangleF GetTitlePositionInBorder()
{
return new RectangleF(
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 1.6f);
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameTitle2Border : FrameThin2Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameTitle2Border()
{
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize*2f);
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameTitle2";}}
public override float Resolution
{
set
{
base.Resolution = value;
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize * 2f);
}
}
/// <summary>
/// Returns the position of the rectangular area in the border where
/// title should be displayed. Returns empty rect if title can't be shown in the border.
/// </summary>
/// <returns>Title position in border.</returns>
public override RectangleF GetTitlePositionInBorder()
{
return new RectangleF(
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 1.6f);
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameTitle3Border : FrameThin3Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameTitle3Border()
{
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize*2f);
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameTitle3";}}
public override float Resolution
{
set
{
base.Resolution = value;
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize * 2f);
}
}
/// <summary>
/// Returns the position of the rectangular area in the border where
/// title should be displayed. Returns empty rect if title can't be shown in the border.
/// </summary>
/// <returns>Title position in border.</returns>
public override RectangleF GetTitlePositionInBorder()
{
return new RectangleF(
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 1.6f);
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameTitle4Border : FrameThin4Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameTitle4Border()
{
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize*2f);
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameTitle4";}}
public override float Resolution
{
set
{
base.Resolution = value;
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize * 2f);
}
}
/// <summary>
/// Returns the position of the rectangular area in the border where
/// title should be displayed. Returns empty rect if title can't be shown in the border.
/// </summary>
/// <returns>Title position in border.</returns>
public override RectangleF GetTitlePositionInBorder()
{
return new RectangleF(
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 1.6f);
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameTitle5Border : FrameThin5Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameTitle5Border()
{
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize*2f);
this.drawScrews = true;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameTitle5";}}
public override float Resolution
{
set
{
base.Resolution = value;
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize * 2f);
}
}
/// <summary>
/// Returns the position of the rectangular area in the border where
/// title should be displayed. Returns empty rect if title can't be shown in the border.
/// </summary>
/// <returns>Title position in border.</returns>
public override RectangleF GetTitlePositionInBorder()
{
return new RectangleF(
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 1.6f);
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameTitle6Border : FrameThin6Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameTitle6Border()
{
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize*2f);
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameTitle6";}}
public override float Resolution
{
set
{
base.Resolution = value;
sizeLeftTop = new SizeF(sizeLeftTop.Width, defaultRadiusSize * 2f);
}
}
/// <summary>
/// Returns the position of the rectangular area in the border where
/// title should be displayed. Returns empty rect if title can't be shown in the border.
/// </summary>
/// <returns>Title position in border.</returns>
public override RectangleF GetTitlePositionInBorder()
{
return new RectangleF(
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 0.25f,
defaultRadiusSize * 1.6f);
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameTitle7Border : FrameTitle1Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameTitle7Border()
{
this.sizeRightBottom = new SizeF(0, sizeRightBottom.Height);
float[] corners = {15f, 1f, 1f, 1f, 1f, 15f, 15f, 15f};
innerCorners = corners;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameTitle7";}}
public override float Resolution
{
set
{
base.Resolution = value;
this.sizeRightBottom = new SizeF(0, sizeRightBottom.Height);
float largeRadius = 15f * resolution / 96.0f;
float smallRadius = 1 * resolution / 96.0f;
float[] corners = { largeRadius, smallRadius, smallRadius, smallRadius, smallRadius, largeRadius, largeRadius, largeRadius };
innerCorners = corners;
}
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameTitle8Border : FrameTitle1Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameTitle8Border()
{
this.sizeLeftTop = new SizeF(0, sizeLeftTop.Height);
this.sizeRightBottom = new SizeF(0, sizeRightBottom.Height);
float[] corners = {1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f};
innerCorners = corners;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameTitle8";}}
public override float Resolution
{
set
{
base.Resolution = value;
this.sizeLeftTop = new SizeF(0, sizeLeftTop.Height);
this.sizeRightBottom = new SizeF(0, sizeRightBottom.Height);
float radius = 1 * resolution / 96.0f;
float[] corners = { radius, radius, radius, radius, radius, radius, radius, radius };
innerCorners = corners;
}
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameThin2Border : FrameThin1Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameThin2Border()
{
float[] corners = {15f, 15f, 15f, 1f, 1f, 1f, 1f, 15f};
cornerRadius = corners;
innerCorners = corners;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameThin2";}}
public override float Resolution
{
set
{
base.Resolution = value;
float largeRadius = 15f * resolution / 96.0f;
float smallRadius = 1 * resolution / 96.0f;
float[] corners = { largeRadius, largeRadius, largeRadius, smallRadius, smallRadius, smallRadius, smallRadius, largeRadius };
cornerRadius = corners;
innerCorners = corners;
}
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameThin3Border : FrameThin1Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameThin3Border()
{
float[] corners = {1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f};
cornerRadius = corners;
innerCorners = corners;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameThin3";}}
public override float Resolution
{
set
{
base.Resolution = value;
float radius = resolution / 96.0f;
float[] corners = { radius, radius, radius, radius, radius, radius, radius, radius };
cornerRadius = corners;
innerCorners = corners;
}
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameThin4Border : FrameThin1Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameThin4Border()
{
float[] corners = {1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f};
cornerRadius = corners;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameThin4";}}
public override float Resolution
{
set
{
base.Resolution = value;
float radius = 1f * resolution / 96.0f;
cornerRadius = new float[] { radius, radius, radius, radius, radius, radius, radius, radius };
}
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameThin5Border : FrameThin1Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameThin5Border()
{
drawScrews = true;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameThin5";}}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameThin6Border : FrameThin1Border
{
#region Border properties and methods
/// <summary>
/// Default constructor
/// </summary>
public FrameThin6Border()
{
float[] corners = {1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f};
innerCorners = corners;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameThin6";}}
public override float Resolution
{
set
{
base.Resolution = value;
float radius = resolution / 96.0f;
float[] corners = { radius, radius, radius, radius, radius, radius, radius, radius };
innerCorners = corners;
}
}
#endregion
}
/// <summary>
/// Implements frame border.
/// </summary>
internal class FrameThin1Border : RaisedBorder
{
#region Border properties and methods
/// <summary>
/// Inner corners radius array
/// </summary>
internal float[] innerCorners = { 15f, 15f, 15f, 15f, 15f, 15f, 15f, 15f };
/// <summary>
/// Default constructor
/// </summary>
public FrameThin1Border()
{
sizeLeftTop = new SizeF(defaultRadiusSize * .8f, defaultRadiusSize * .8f);
sizeRightBottom = new SizeF(defaultRadiusSize * .8f, defaultRadiusSize * .8f);
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "FrameThin1";}}
public override float Resolution
{
set
{
base.Resolution = value;
float radius = 15.0f * resolution / 96.0f;
innerCorners = new float[] { radius, radius, radius, radius, radius, radius, radius, radius };
sizeLeftTop = new SizeF(defaultRadiusSize * .8f, defaultRadiusSize * .8f);
sizeRightBottom = new SizeF(defaultRadiusSize * .8f, defaultRadiusSize * .8f);
}
}
/// <summary>
/// Draws 3D border.
/// </summary>
/// <param name="graph">Graphics to draw the border on.</param>
/// <param name="borderSkin">Border skin object.</param>
/// <param name="rect">Rectangle of the border.</param>
/// <param name="backColor">Color of rectangle</param>
/// <param name="backHatchStyle">Hatch style</param>
/// <param name="backImage">Back Image</param>
/// <param name="backImageWrapMode">Image mode</param>
/// <param name="backImageTransparentColor">Image transparent color.</param>
/// <param name="backImageAlign">Image alignment</param>
/// <param name="backGradientStyle">Gradient type</param>
/// <param name="backSecondaryColor">Gradient End Color</param>
/// <param name="borderColor">Border Color</param>
/// <param name="borderWidth">Border Width</param>
/// <param name="borderDashStyle">Border Style</param>
public override void DrawBorder(
ChartGraphics graph,
BorderSkin borderSkin,
RectangleF rect,
Color backColor,
ChartHatchStyle backHatchStyle,
string backImage,
ChartImageWrapMode backImageWrapMode,
Color backImageTransparentColor,
ChartImageAlignmentStyle backImageAlign,
GradientStyle backGradientStyle,
Color backSecondaryColor,
Color borderColor,
int borderWidth,
ChartDashStyle borderDashStyle)
{
drawBottomShadow = true;
sunken = false;
outsideShadowRate = .9f;
drawOutsideTopLeftShadow = false;
bool oldScrewsFlag = this.drawScrews;
this.drawScrews = false;
base.DrawBorder(
graph,
borderSkin,
rect,
borderSkin.BackColor,
borderSkin.BackHatchStyle,
borderSkin.BackImage,
borderSkin.BackImageWrapMode,
borderSkin.BackImageTransparentColor,
borderSkin.BackImageAlignment,
borderSkin.BackGradientStyle,
borderSkin.BackSecondaryColor,
borderSkin.BorderColor,
borderSkin.BorderWidth,
borderSkin.BorderDashStyle);
this.drawScrews = oldScrewsFlag;
rect.X += sizeLeftTop.Width;
rect.Y += sizeLeftTop.Height;
rect.Width -= sizeRightBottom.Width + sizeLeftTop.Width;
rect.Height -= sizeRightBottom.Height + sizeLeftTop.Height;
if(rect.Width > 0 && rect.Height > 0 )
{
float[] oldCorners = new float[8];
oldCorners = (float[])cornerRadius.Clone();
cornerRadius = innerCorners;
drawBottomShadow = false;
sunken = true;
drawOutsideTopLeftShadow = true;
outsideShadowRate = 1.4f;
Color oldPageColor = borderSkin.PageColor;
borderSkin.PageColor = Color.Transparent;
base.DrawBorder(
graph,
borderSkin,
rect,
backColor,
backHatchStyle,
backImage,
backImageWrapMode,
backImageTransparentColor,
backImageAlign,
backGradientStyle,
backSecondaryColor,
borderColor,
borderWidth,
borderDashStyle );
borderSkin.PageColor = oldPageColor;
cornerRadius = oldCorners;
}
}
#endregion
}
/// <summary>
/// Implements raised border.
/// </summary>
internal class RaisedBorder : SunkenBorder
{
#region Border properties and methods
/// <summary>
/// Public constructor
/// </summary>
public RaisedBorder()
{
sunken = false;
}
/// <summary>
/// Chart type name
/// </summary>
public override string Name { get{ return "Raised";}}
#endregion
}
/// <summary>
/// Implements embed 3D border.
/// </summary>
internal class SunkenBorder : IBorderType
{
#region Border properties and methods
/// <summary>
/// Radius for rounded rectangle
/// </summary>
internal float defaultRadiusSize = 15f;
/// <summary>
/// Outside shadow rate
/// </summary>
internal float outsideShadowRate = .9f;
/// <summary>
/// Indicates that sunken shadows should be drawn
/// </summary>
internal bool sunken = true;
/// <summary>
/// Indicates that bottom shadow should be drawn
/// </summary>
internal bool drawBottomShadow = true;
/// <summary>
/// Indicates that top left outside dark shadow must be drawn
/// </summary>
internal bool drawOutsideTopLeftShadow = false;
/// <summary>
/// Array of corner radius
/// </summary>
internal float[] cornerRadius = { 15f, 15f, 15f, 15f, 15f, 15f, 15f, 15f };
/// <summary>
/// Border top/left size
/// </summary>
internal SizeF sizeLeftTop = SizeF.Empty;
/// <summary>
/// Border right/bottom size
/// </summary>
internal SizeF sizeRightBottom = SizeF.Empty;
/// <summary>
/// Indicates that ----s should be drawn in the corners of the frame
/// </summary>
internal bool drawScrews = false;
internal float resolution = 96f;
/// <summary>
/// Public constructor
/// </summary>
public SunkenBorder()
{
}
/// <summary>
/// Chart type name
/// </summary>
public virtual string Name { get{ return "Sunken";}}
public virtual float Resolution
{
set
{
resolution = value;
defaultRadiusSize = 15 * resolution / 96;
//X = defaultRadiusSize;
//Y = defaultRadiusSize;
cornerRadius = new float[] { defaultRadiusSize, defaultRadiusSize, defaultRadiusSize, defaultRadiusSize, defaultRadiusSize, defaultRadiusSize, defaultRadiusSize, defaultRadiusSize };
}
}
/// <summary>
/// Returns the position of the rectangular area in the border where
/// title should be displayed. Returns empty rect if title can't be shown in the border.
/// </summary>
/// <returns>Title position in border.</returns>
public virtual RectangleF GetTitlePositionInBorder()
{
return RectangleF.Empty;
}
/// <summary>
/// Adjust areas rectangle coordinate to fit the 3D border
/// </summary>
/// <param name="graph">Graphics to draw the border on.</param>
/// <param name="areasRect">Position to adjust.</param>
public virtual void AdjustAreasPosition(ChartGraphics graph, ref RectangleF areasRect)
{
SizeF relSizeLeftTop = new SizeF(sizeLeftTop);
SizeF relSizeRightBottom = new SizeF(sizeRightBottom);
relSizeLeftTop.Width += defaultRadiusSize * 0.7f;
relSizeLeftTop.Height += defaultRadiusSize * 0.85f;
relSizeRightBottom.Width += defaultRadiusSize * 0.7f;
relSizeRightBottom.Height += defaultRadiusSize * 0.7f;
relSizeLeftTop = graph.GetRelativeSize(relSizeLeftTop);
relSizeRightBottom = graph.GetRelativeSize(relSizeRightBottom);
if(relSizeLeftTop.Width > 30f)
relSizeLeftTop.Width = 0;
if(relSizeLeftTop.Height > 30f)
relSizeLeftTop.Height = 0;
if(relSizeRightBottom.Width > 30f)
relSizeRightBottom.Width = 0;
if(relSizeRightBottom.Height > 30f)
relSizeRightBottom.Height = 0;
areasRect.X += relSizeLeftTop.Width;
areasRect.Width -= (float)Math.Min(areasRect.Width, relSizeLeftTop.Width + relSizeRightBottom.Width);
areasRect.Y += relSizeLeftTop.Height;
areasRect.Height -= (float)Math.Min(areasRect.Height, relSizeLeftTop.Height + relSizeRightBottom.Height);
if(areasRect.Right > 100f)
{
if(areasRect.Width > 100f - areasRect.Right)
areasRect.Width -= 100f - areasRect.Right;
else
areasRect.X -= 100f - areasRect.Right;
}
if(areasRect.Bottom > 100f)
{
if(areasRect.Height > 100f - areasRect.Bottom)
areasRect.Height -= 100f - areasRect.Bottom;
else
areasRect.Y -= 100f - areasRect.Bottom;
}
}
/// <summary>
/// Draws 3D border
/// </summary>
/// <param name="graph">Graphics to draw the border on.</param>
/// <param name="borderSkin">Border skin object.</param>
/// <param name="rect">Rectangle of the border.</param>
/// <param name="backColor">Color of rectangle</param>
/// <param name="backHatchStyle">Hatch style</param>
/// <param name="backImage">Back Image</param>
/// <param name="backImageWrapMode">Image mode</param>
/// <param name="backImageTransparentColor">Image transparent color.</param>
/// <param name="backImageAlign">Image alignment</param>
/// <param name="backGradientStyle">Gradient type</param>
/// <param name="backSecondaryColor">Gradient End Color</param>
/// <param name="borderColor">Border Color</param>
/// <param name="borderWidth">Border Width</param>
/// <param name="borderDashStyle">Border Style</param>
public virtual void DrawBorder(
ChartGraphics graph,
BorderSkin borderSkin,
RectangleF rect,
Color backColor,
ChartHatchStyle backHatchStyle,
string backImage,
ChartImageWrapMode backImageWrapMode,
Color backImageTransparentColor,
ChartImageAlignmentStyle backImageAlign,
GradientStyle backGradientStyle,
Color backSecondaryColor,
Color borderColor,
int borderWidth,
ChartDashStyle borderDashStyle)
{
RectangleF absolute = graph.Round( rect );
RectangleF shadowRect = absolute;
// Calculate shadow colors (0.2 - 0.6)
float colorDarkeningIndex = 0.3f + (0.4f * (borderSkin.PageColor.R + borderSkin.PageColor.G + borderSkin.PageColor.B) / 765f);
Color shadowColor = Color.FromArgb(
(int)(backColor.R*colorDarkeningIndex),
(int)(backColor.G*colorDarkeningIndex),
(int)(backColor.B*colorDarkeningIndex));
colorDarkeningIndex += 0.2f;
Color shadowLightColor = Color.FromArgb(
(int)(borderSkin.PageColor.R*colorDarkeningIndex),
(int)(borderSkin.PageColor.G*colorDarkeningIndex),
(int)(borderSkin.PageColor.B*colorDarkeningIndex));
if(borderSkin.PageColor == Color.Transparent)
{
shadowLightColor = Color.FromArgb(60, 0, 0, 0);
}
// Calculate rounded rect radius
float radius = defaultRadiusSize;
radius = (float)Math.Max(radius, 2f * resolution / 96.0f);
radius = (float)Math.Min(radius, rect.Width/2f);
radius = (float)Math.Min(radius, rect.Height/2f);
radius = (float)Math.Ceiling(radius);
// Fill page background color
using (Brush brush = new SolidBrush(borderSkin.PageColor))
{
graph.FillRectangle(brush, rect);
}
if(drawOutsideTopLeftShadow)
{
// Top/Left outside shadow
shadowRect = absolute;
shadowRect.X -= radius * 0.3f;
shadowRect.Y -= radius * 0.3f;
shadowRect.Width -= radius * .3f;
shadowRect.Height -= radius * .3f;
graph.DrawRoundedRectShadowAbs(shadowRect, cornerRadius, radius, Color.FromArgb(128, Color.Black), borderSkin.PageColor, outsideShadowRate);
}
// Bottom/Right outside shadow
shadowRect = absolute;
shadowRect.X += radius * 0.3f;
shadowRect.Y += radius * 0.3f;
shadowRect.Width -= radius * .3f;
shadowRect.Height -= radius * .3f;
graph.DrawRoundedRectShadowAbs(shadowRect, cornerRadius, radius, shadowLightColor, borderSkin.PageColor, outsideShadowRate);
// Background
shadowRect = absolute;
shadowRect.Width -= radius * .3f;
shadowRect.Height -= radius * .3f;
GraphicsPath path = graph.CreateRoundedRectPath(shadowRect, cornerRadius);
graph.DrawPathAbs(
path,
backColor,
backHatchStyle,
backImage,
backImageWrapMode,
backImageTransparentColor,
backImageAlign,
backGradientStyle,
backSecondaryColor,
borderColor,
borderWidth,
borderDashStyle,
PenAlignment.Inset );
// Dispose Graphic path
if( path != null )
path.Dispose();
// Draw ----s imitation in the corners of the farame
if(drawScrews)
{
// Left/Top ----
RectangleF screwRect = RectangleF.Empty;
float offset = radius * 0.4f;
screwRect.X = shadowRect.X + offset;
screwRect.Y = shadowRect.Y + offset;
screwRect.Width = radius * 0.55f;
screwRect.Height = screwRect.Width;
DrawScrew(graph, screwRect);
// Right/Top ----
screwRect.X = shadowRect.Right - offset - screwRect.Width;
DrawScrew(graph, screwRect);
// Right/Bottom ----
screwRect.X = shadowRect.Right - offset - screwRect.Width;
screwRect.Y = shadowRect.Bottom - offset - screwRect.Height;
DrawScrew(graph, screwRect);
// Left/Bottom ----
screwRect.X = shadowRect.X + offset;
screwRect.Y = shadowRect.Bottom - offset - screwRect.Height;
DrawScrew(graph, screwRect);
}
// Bottom/Right inner shadow
Region innerShadowRegion = null;
if(drawBottomShadow)
{
shadowRect = absolute;
shadowRect.Width -= radius * .3f;
shadowRect.Height -= radius * .3f;
innerShadowRegion = new Region(
graph.CreateRoundedRectPath(
new RectangleF(
shadowRect.X - radius,
shadowRect.Y - radius,
shadowRect.Width + 0.5f*radius,
shadowRect.Height + 0.5f*radius),
cornerRadius));
innerShadowRegion.Complement(graph.CreateRoundedRectPath(shadowRect, cornerRadius));
graph.Clip = innerShadowRegion;
shadowRect.X -= 0.5f*radius;
shadowRect.Width += 0.5f*radius;
shadowRect.Y -= 0.5f*radius;
shadowRect.Height += 0.5f*radius;
graph.DrawRoundedRectShadowAbs(
shadowRect,
cornerRadius,
radius,
Color.Transparent,
Color.FromArgb(175, (sunken) ? Color.White : shadowColor),
1.0f);
graph.Clip = new Region();
}
// Top/Left inner shadow
shadowRect = absolute;
shadowRect.Width -= radius * .3f;
shadowRect.Height -= radius * .3f;
innerShadowRegion = new Region(
graph.CreateRoundedRectPath(
new RectangleF(
shadowRect.X + radius*.5f,
shadowRect.Y + radius*.5f,
shadowRect.Width - .2f*radius,
shadowRect.Height - .2f*radius),
cornerRadius));
RectangleF shadowWithOffset = shadowRect;
shadowWithOffset.Width += radius;
shadowWithOffset.Height += radius;
innerShadowRegion.Complement(graph.CreateRoundedRectPath(shadowWithOffset, cornerRadius));
innerShadowRegion.Intersect(graph.CreateRoundedRectPath(shadowRect, cornerRadius));
graph.Clip = innerShadowRegion;
graph.DrawRoundedRectShadowAbs(
shadowWithOffset,
cornerRadius,
radius,
Color.Transparent,
Color.FromArgb(175, (sunken) ? shadowColor : Color.White),
1.0f);
graph.Clip = new Region();
}
/// <summary>
/// Helper function, which draws a ---- on the frame
/// </summary>
/// <param name="graph">Chart graphics to use.</param>
/// <param name="rect">---- position.</param>
private void DrawScrew(ChartGraphics graph, RectangleF rect)
{
// Draw ----
Pen screwPen = new Pen(Color.FromArgb(128,255,255,255), 1);
graph.DrawEllipse(screwPen, rect.X, rect.Y, rect.Width, rect.Height);
graph.DrawLine(screwPen, rect.X + 2 * resolution / 96.0f, rect.Y + rect.Height - 2 * resolution / 96.0f, rect.Right - 2 * resolution / 96.0f, rect.Y + 2 * resolution / 96.0f);
screwPen = new Pen(Color.FromArgb(128, Color.Black), 1);
graph.DrawEllipse(screwPen, rect.X + 1 * resolution / 96.0f, rect.Y + 1 * resolution / 96.0f, rect.Width, rect.Height);
graph.DrawLine(screwPen, rect.X + 3 * resolution / 96.0f, rect.Y + rect.Height - 1 * resolution / 96.0f, rect.Right - 1 * resolution / 96.0f, rect.Y + 3 * resolution / 96.0f);
}
#endregion
}
}
|
#region History
#if HISTORY_COMMENT
// <[History]>
Update 2014-12-07
=================
- DataAccess : OleDbConfig
- Re-Implement Database Config classes for OleDb (abstract).
======================================================================================================================
Update 2013-03-08
=================
- DataAccess : OleDb
- All OleDb data access classes is redesign.
- Change name space to NLib.Data and NLib.Data.Design
======================================================================================================================
Update 2010-02-03
=================
- DataAccess : OleDb
- OleDbFactory ported and re-implements uses new generic base class.
- OleDbConfig class ported and re-implements.
- OleDb sql model and related class ported.
======================================================================================================================
Update 2008-11-23
=================
- DataAccess : OleDb
- Add try-catch in CreateParameter when set Precision/Scale.
======================================================================================================================
Update 2008-10-21
=================
- Sql Model (OleDb) updated.
[OleDb(abstract)]
- Add new class OleDbSqlModel.OleDbDDLFormatter for handle DDL generate script.
- Implement method CreateDDLFormatter.
- Implement method GenerateViewScript (incompleted) in it's DDLFormatter
(alway return string.Empty).
- Implement method GenerateTableScript in it's DDLFormatter.
- Implement method GenerateTableColumnScript in it's DDLFormatter.
- Implement method GenerateTableConstraintScript in it's DDLFormatter.
======================================================================================================================
Update 2008-10-20
=================
- DataAccess : OleDb
- Fixed Connection check null bug (in case original code used logical operator && instead of ||).
======================================================================================================================
Update 2008-09-27
=================
- New Class added
- OracleConnectionFactory class added. This class is re-implement DerivedParameters method.
======================================================================================================================
Update 2008-06-08
=================
- New Class added
- CsvReader class added.
======================================================================================================================
Update 2008-04-11
=================
- OleDb classes changed.
- All SqlValueFormatter that related with OleDb config is no longer access via public.
======================================================================================================================
Update 2008-03-26
=================
- New Class added
- DBF Reader/Writer class added. This 2 class is provide Native access to DBF File.
- Feature added
- Add related SqlValueFormatter class for each Provider.
======================================================================================================================
// </[History]>
#endif
#endregion
#region Using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using NLib;
using NLib.Design;
using NLib.Data;
using NLib.Data.Design;
using NLib.Reflection;
using NLib.Xml;
using NLib.Utils;
#endregion
namespace NLib.Data
{
#region OleDbConfig
/// <summary>
/// OleDb based Connection Config class (abstract).
/// </summary>
[Serializable]
//[TypeConverter(typeof(PropertySorterSupportExpandableTypeConverter))]
public abstract class OleDbConfig : NDbConfig
{
#region Constructor and Destructor
/// <summary>
/// Constructor.
/// </summary>
public OleDbConfig()
: base()
{
}
/// <summary>
/// Destructor.
/// </summary>
~OleDbConfig()
{
}
#endregion
}
#endregion
}
|
using System;
using System.Collections;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Text;
public class HashDefPrecompiler
{
static public bool Compile(ref string code, string scriptFile, bool IsPrimaryScript, Hashtable context)
{
var hashDefs = new Dictionary<string, string>();
var content = new StringBuilder();
string line;
using (var sr = new StringReader(code))
while ((line = sr.ReadLine()) != null)
{
if (line.Trim().StartsWith("#define ")) //#define <pattern> <replacement>
{
string[] tokens = line.Split(" ".ToCharArray(), 3, StringSplitOptions.RemoveEmptyEntries);
hashDefs.Add(tokens[1], tokens[2]);
content.AppendLine("//" + line);
}
else
content.AppendLine(line);
}
code = content.ToString();
foreach (string key in hashDefs.Keys.Reverse())
code = code.Replace(key, hashDefs[key]);
return true;
}
} |
namespace Basic.Tests.Expressions
{
using Basic.Runtime.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class ConstantTests
{
[TestMethod]
public void Constant_WithNull_StoresNull()
{
var constant = new Constant(null);
Assert.IsNull(constant.Value);
}
[TestMethod]
public void Constant_WithStringWithQuote_StoresItAsIs()
{
var constant = new Constant("string with a \" character");
Assert.AreEqual("string with a \" character", constant.Value);
}
[TestMethod]
public void Constant_WithDouble_StoresItAsIs()
{
var constant = new Constant("3.14159265");
var actual = constant.Value;
Assert.AreEqual(3.14159265, actual);
}
[TestMethod]
public void ToString_WithNull_ReturnsEmptyString()
{
var constant = new Constant(null);
var actual = constant.ToString();
Assert.AreEqual("", actual);
}
[TestMethod]
public void ToString_WithStringWithQuote_DoublesQuote()
{
var constant = new Constant("string with a \" character");
var actual = constant.ToString();
Assert.AreEqual("\"string with a \"\" character\"", actual);
}
[TestMethod]
public void ToString_WithDouble_ReturnsItWithDecimalPoint()
{
var constant = new Constant("3.14159265");
var actual = constant.ToString();
Assert.AreEqual("3.14159265", actual);
}
}
}
|
namespace Cinema
{
using System.IO;
using Microsoft.EntityFrameworkCore;
using Data;
using DataProcessor;
public class StartUp
{
public static void Main(string[] args)
{
using var context = new CinemaContext();
}
private static void ResetDatabase(CinemaContext context)
{
context.Database.EnsureDeleted();
context.Database.Migrate();
var moviesJson = File.ReadAllText(@".\..\..\..\Datasets\movies.json");
var moviesResult = Deserializer.ImportMovies(context, moviesJson);
var hallsSeatsJson = File.ReadAllText(@".\..\..\..\Datasets\halls-seats.json");
var hallsSeatsResult = Deserializer.ImportHallSeats(context, hallsSeatsJson);
var projectionsXml = File.ReadAllText(@".\..\..\..\Datasets\projections.xml");
var projectionsResult = Deserializer.ImportProjections(context, projectionsXml);
var customersTicketsXml = File.ReadAllText(@".\..\..\..\Datasets\customers-tickets.xml");
var customersTicketsResult = Deserializer.ImportCustomerTickets(context, customersTicketsXml);
}
}
} |
using System;
using System.Configuration;
using System.IO;
using System.Xml;
namespace OpenCVR
{
static internal class SecretConfigurationFetcher
{
public static string ReadEchangeServicePassword()
{
return FindValue("ExchangeServicePassword");
}
public static string ReadCvrPassword()
{
return FindValue("CvrPassword");
}
public static string ReadExchangeHost()
{
return FindValue("ExchangeServiceHost");
}
public static string ReadExchangeServiceUserName()
{
return FindValue("ExchangeServiceUserName");
}
public static string ReadEmailAddress()
{
return FindValue("EmailAddress");
}
private static string FindValue(string key)
{
var path = Environment.ExpandEnvironmentVariables(ConfigurationManager.AppSettings["secretsLocation"]);
var doc = new XmlDocument();
doc.Load(path);
var selectSingleNode = doc.SelectSingleNode("/CvrConfiguration/@" + key);
if (selectSingleNode != null)
return selectSingleNode.Value;
throw new Exception("Could not find configuration for " + key + " in file: " + path);
}
}
} |
using Ksnm.ExtensionMethods.System.Collections.Generic.Enumerable;
using System;
using System.Collections.Generic;
using System.Linq;
namespace CSharpTest.System
{
public class LinqTest
{
public static void All()
{
SelectManyTest();
}
public static void SelectManyTest()
{
Console.WriteLine($"====================");
Ksnm.Debug.WriteLineCallerInfo();
var list = new List<int[]>();
list.Add(new int[] { 1, 2, 3 });
list.Add(new int[] { 4, 5, 6 });
list.Add(new int[] { 7, 8, 9 });
var expected = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var actual = list.SelectMany(item => item);
Console.WriteLine($"{expected.ToJoinedString(",")}");
Console.WriteLine($"{actual.ToJoinedString(",")}");
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using VentCalc.Models;
namespace VentCalc.Persistence
{
public class RoomTypeValueRepository : IRoomTypeValueRepository
{
private readonly VentCalcDbContext context;
public RoomTypeValueRepository(VentCalcDbContext context)
{
this.context = context;
}
}
} |
namespace DirtBot.Services.Options
{
public class CustomStatusServiceOptions
{
public string[] Statuses { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PalvelutoriModel.Translation;
using PalvelutoriModel.Controllers;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace PalvelutoriSite.Controllers
{
public class TestPageController : UIController
{
public TestPageController()
{
}
public IActionResult ListTestEntity()
{
return UIView("ListTestEntity");
}
public IActionResult CreateTestEntity()
{
return UIView("CreateTestEntity",false);
}
public IActionResult EditTestEntity()
{
return UIView("CreateTestEntity", true);
}
}
}
|
using RMS.Core;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
namespace RMS.Persistence.Ef.DataProviders
{
public class SqlCeDataProvider : IDataProvider
{
public void InitializeDatabase()
{
var connectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
//TODO fix compilation warning (below)
#pragma warning disable 0618
Database.DefaultConnectionFactory = connectionFactory;
var initializer = new CreateCeDatabaseIfNotExists<EfObjectContext>();
Database.SetInitializer(initializer);
}
/// <summary>
/// Gets a support database parameter object (used by stored procedures)
/// </summary>
/// <returns>Parameter</returns>
public virtual DbParameter GetParameter()
{
return new SqlParameter();
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.TrafficManager.Fluent
{
/// <summary>
/// An immutable client-side representation of an Azure traffic manager profile Azure endpoint.
/// </summary>
public interface ITrafficManagerAzureEndpoint :
Microsoft.Azure.Management.TrafficManager.Fluent.ITrafficManagerEndpoint
{
/// <summary>
/// Gets the resource id of the target Azure resource.
/// </summary>
string TargetAzureResourceId { get; }
/// <summary>
/// Gets the type of the target Azure resource.
/// </summary>
Microsoft.Azure.Management.TrafficManager.Fluent.TargetAzureResourceType TargetResourceType { get; }
}
} |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using UnityEngine.UI;
namespace UniverseLib.Analyzers.Unity
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class InputFieldOnEndEditAnalyzer : DiagnosticAnalyzer
{
public const string ID = "ULib002";
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
ID,
"InputField.onEndEdit should be accessed with InputField.GetOnEndEdit()",
"InputField.onEndEdit was accessed directly, it should be accessed with InputField.GetOnEndEdit()",
"UniverseLib.Unity",
DiagnosticSeverity.Warning,
true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSyntaxNodeAction(AnalyzeSimpleMemberAccess, SyntaxKind.SimpleMemberAccessExpression);
}
private void AnalyzeSimpleMemberAccess(SyntaxNodeAnalysisContext context)
{
var memberAccess = (MemberAccessExpressionSyntax)context.Node;
var symbol = context.SemanticModel.GetSymbolInfo(memberAccess.Name, context.CancellationToken).Symbol;
if (symbol == null)
return;
if (context.ContainingSymbol?.ContainingType is ITypeSymbol contextType)
{
if (contextType.NamespaceEquals("UniverseLib") && contextType.Name == "UnityHelpers")
return;
}
if (symbol.Name == "onEndEdit"
&& symbol.ContainingType.Name == "InputField"
&& symbol.NamespaceEquals("UnityEngine.UI"))
context.ReportDiagnostic(Diagnostic.Create(Rule, memberAccess.Name.GetLocation()));
}
}
} |
namespace Presentation
{
partial class Form1
{
/// <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.txtWord = new System.Windows.Forms.TextBox();
this.btnReverseArray = new System.Windows.Forms.Button();
this.btnTwoPoints = new System.Windows.Forms.Button();
this.lblResult = new System.Windows.Forms.Label();
this.numTimesToRun = new System.Windows.Forms.NumericUpDown();
this.lblTimesToRun = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.numTimesToRun)).BeginInit();
this.SuspendLayout();
//
// txtWord
//
this.txtWord.Location = new System.Drawing.Point(12, 12);
this.txtWord.MaxLength = 524288;
this.txtWord.Multiline = true;
this.txtWord.Name = "txtWord";
this.txtWord.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtWord.Size = new System.Drawing.Size(748, 266);
this.txtWord.TabIndex = 0;
//
// btnReverseArray
//
this.btnReverseArray.Location = new System.Drawing.Point(12, 284);
this.btnReverseArray.Name = "btnReverseArray";
this.btnReverseArray.Size = new System.Drawing.Size(140, 23);
this.btnReverseArray.TabIndex = 1;
this.btnReverseArray.Text = "Reverse Array";
this.btnReverseArray.UseVisualStyleBackColor = true;
this.btnReverseArray.Click += new System.EventHandler(this.btnReverseArray_Click);
//
// btnTwoPoints
//
this.btnTwoPoints.Location = new System.Drawing.Point(158, 284);
this.btnTwoPoints.Name = "btnTwoPoints";
this.btnTwoPoints.Size = new System.Drawing.Size(140, 23);
this.btnTwoPoints.TabIndex = 2;
this.btnTwoPoints.Text = "Two points";
this.btnTwoPoints.UseVisualStyleBackColor = true;
this.btnTwoPoints.Click += new System.EventHandler(this.btnTwoPoints_Click);
//
// lblResult
//
this.lblResult.AutoSize = true;
this.lblResult.CausesValidation = false;
this.lblResult.ForeColor = System.Drawing.Color.Red;
this.lblResult.Location = new System.Drawing.Point(304, 287);
this.lblResult.Name = "lblResult";
this.lblResult.Size = new System.Drawing.Size(62, 17);
this.lblResult.TabIndex = 3;
this.lblResult.Text = "lblResult";
//
// numTimesToRun
//
this.numTimesToRun.Location = new System.Drawing.Point(636, 284);
this.numTimesToRun.Maximum = new decimal(new int[] {
200000,
0,
0,
0});
this.numTimesToRun.Name = "numTimesToRun";
this.numTimesToRun.Size = new System.Drawing.Size(77, 22);
this.numTimesToRun.TabIndex = 4;
this.numTimesToRun.Value = new decimal(new int[] {
10000,
0,
0,
0});
//
// lblTimesToRun
//
this.lblTimesToRun.AutoSize = true;
this.lblTimesToRun.CausesValidation = false;
this.lblTimesToRun.ForeColor = System.Drawing.Color.Black;
this.lblTimesToRun.Location = new System.Drawing.Point(719, 287);
this.lblTimesToRun.Name = "lblTimesToRun";
this.lblTimesToRun.Size = new System.Drawing.Size(41, 17);
this.lblTimesToRun.TabIndex = 5;
this.lblTimesToRun.Text = "times";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(772, 319);
this.Controls.Add(this.lblTimesToRun);
this.Controls.Add(this.numTimesToRun);
this.Controls.Add(this.lblResult);
this.Controls.Add(this.btnTwoPoints);
this.Controls.Add(this.btnReverseArray);
this.Controls.Add(this.txtWord);
this.Name = "Form1";
this.Text = "Form1";
((System.ComponentModel.ISupportInitialize)(this.numTimesToRun)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtWord;
private System.Windows.Forms.Button btnReverseArray;
private System.Windows.Forms.Button btnTwoPoints;
private System.Windows.Forms.Label lblResult;
private System.Windows.Forms.NumericUpDown numTimesToRun;
private System.Windows.Forms.Label lblTimesToRun;
}
}
|
@page
@using Volo.CmsKit.Admin.Web.Pages.CmsKit.Menus.MenuItems
@using Volo.CmsKit.Admin.Web.Pages
@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal
@inherits CmsKitAdminPageBase
@model CreateModalModel
@{
Layout = null;
}
<form asp-page="/CmsKit/Menus/MenuItems/CreateModal">
<abp-modal id="menu-create-modal">
<abp-modal-header title="@L["New"].Value"></abp-modal-header>
<abp-modal-body>
<abp-tabs tab-style="Tab">
<abp-tab name="url" title="@L["Url"]">
<abp-input asp-for="ViewModel.Url"/>
</abp-tab>
<abp-tab title="@L["Page"]">
<label class="form-label" asp-for="ViewModel.PageId"></label>
<select class="form-control" asp-for="ViewModel.PageId"></select>
<span asp-validation-for="ViewModel.PageId"></span>
</abp-tab>
</abp-tabs>
<hr/>
<abp-input asp-for="ViewModel.ParentId"/>
<abp-input asp-for="ViewModel.DisplayName"/>
<abp-input asp-for="ViewModel.IsActive"/>
<abp-input asp-for="ViewModel.Icon"/>
<abp-input asp-for="ViewModel.Order"/>
<abp-input asp-for="ViewModel.Target"/>
<abp-input asp-for="ViewModel.ElementId"/>
<abp-input asp-for="ViewModel.CssClass"/>
</abp-modal-body>
<abp-modal-footer buttons="@(AbpModalButtons.Cancel | AbpModalButtons.Save)"></abp-modal-footer>
</abp-modal>
</form> |
namespace Mages.Repl.Modules
{
using Mages.Core;
using Mages.Plugins.Modules;
using System;
sealed class MagesModuleFileReader : IModuleFileReader
{
private static readonly String[] AllowedExtensions = new[] { ".ms", ".mages", ".txt", ".m" };
private readonly IFileSystem _fs;
public MagesModuleFileReader(IFileSystem fs)
{
_fs = fs;
}
public Action<Engine> Prepare(String path)
{
var content = _fs.RealText(path);
return engine => engine.Interpret(content);
}
public Boolean TryGetPath(String fileName, String directory, out String path)
{
path = null;
return ModuleHelpers.HasExtension(AllowedExtensions, fileName) &&
ModuleHelpers.TryFindPath(fileName, directory, out path);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssemblyDefender.PE
{
public static class PEConstants
{
public const int NumberOfRvaAndSizes = 16;
public const ushort DosSignature = 0x5A4D; // MZ
public const uint NTSignature = 0x00004550; // PE00
public const ushort PEMagic32 = 0x10b;
public const ushort PEMagic64 = 0x20b;
#region Header Sizes
public static readonly int DosHeaderSize;
public static readonly int COFFHeaderSize;
public static readonly int PEHeaderSize;
public static readonly int PEHeader64Size;
public static readonly int SectionHeaderSize;
#endregion
#region Stubs
/// <summary>
/// This is the stub program that says it can't be run in DOS mode
/// it is x86 specific, but so is dos so I suppose that is OK
/// </summary>
public static readonly byte[] DosX86Stub = new byte[]
{
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
#endregion
#region Ctor
static unsafe PEConstants()
{
DosHeaderSize = sizeof(DOSHeader);
COFFHeaderSize = sizeof(COFFHeader);
PEHeaderSize = sizeof(PEHeader);
PEHeader64Size = sizeof(PEHeader64);
SectionHeaderSize = sizeof(SectionHeader);
}
#endregion
}
}
|
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
/****************************************************************************
* PLEASE NOTE: The code in this file is under extremely active development
* and is likely to change quite frequently. It is not recommended to modify
* the code in this file, as your changes are likely to be overwritten by
* the next product update when it is published.
* **************************************************************************/
public class dfMarkupEntity
{
// http://www.w3schools.com/html/html_entities.asp
// http://www.w3schools.com/tags/ref_entities.asp
#region Static variables
private static List<dfMarkupEntity> HTML_ENTITIES = new List<dfMarkupEntity>
{
new dfMarkupEntity( " ", " " ),
new dfMarkupEntity( """, "\"" ),
new dfMarkupEntity( "&", "&" ),
new dfMarkupEntity( "<", "<" ),
new dfMarkupEntity( ">", ">" ),
new dfMarkupEntity( "'", "'" ),
new dfMarkupEntity( "™", "™" ),
new dfMarkupEntity( "©", "©" ),
new dfMarkupEntity( " ", " " ) // Hard space to normal space
};
private static StringBuilder buffer = new StringBuilder();
#endregion
public string EntityName;
public string EntityChar;
public dfMarkupEntity( string entityName, string entityChar )
{
this.EntityName = entityName;
this.EntityChar = entityChar;
}
#region Static methods
public static string Replace( string text )
{
buffer.EnsureCapacity( text.Length );
buffer.Length = 0;
buffer.Append( text );
for( int i = 0; i < HTML_ENTITIES.Count; i++ )
{
var entity = HTML_ENTITIES[ i ];
buffer.Replace( entity.EntityName, entity.EntityChar );
}
return buffer.ToString();
}
#endregion
}
[AttributeUsage( AttributeTargets.Class, Inherited = true, AllowMultiple = true )]
public class dfMarkupTagInfoAttribute : System.Attribute
{
public string TagName { get; set; }
public dfMarkupTagInfoAttribute( string tagName )
{
this.TagName = tagName;
}
}
/// <summary>
/// Base class for pseudo-HTML markup elements
/// </summary>
public abstract class dfMarkupElement
{
public dfMarkupElement Parent { get; protected set; }
protected List<dfMarkupElement> ChildNodes { get; private set; }
public dfMarkupElement()
{
this.ChildNodes = new List<dfMarkupElement>();
}
public void AddChildNode( dfMarkupElement node )
{
node.Parent = this;
ChildNodes.Add( node );
}
public void PerformLayout( dfMarkupBox container, dfMarkupStyle style )
{
//@Profiler.BeginSample( "Perform markup layout: " + this.GetType().Name );
_PerformLayoutImpl( container, style );
//@Profiler.EndSample();
}
internal virtual void Release()
{
Parent = null;
ChildNodes.Clear();
}
protected abstract void _PerformLayoutImpl( dfMarkupBox container, dfMarkupStyle style );
}
/// <summary>
/// Represents a section of raw text
/// </summary>
public class dfMarkupString : dfMarkupElement
{
#region Static variables
private static StringBuilder buffer = new StringBuilder();
private static Regex whitespacePattern = new Regex( "\\s+" );
private static Queue<dfMarkupString> objectPool = new Queue<dfMarkupString>();
#endregion
#region Public properties
public string Text { get; private set; }
public bool IsWhitespace
{
get { return isWhitespace; }
}
#endregion
#region Private variables
private bool isWhitespace = false;
#endregion
#region Constructor
public dfMarkupString( string text )
: base()
{
this.Text = processWhitespace( dfMarkupEntity.Replace( text ) );
this.isWhitespace = whitespacePattern.IsMatch( this.Text );
}
#endregion
#region System.Object overrides
public override string ToString()
{
return this.Text;
}
#endregion
#region Public methods
internal dfMarkupElement SplitWords()
{
//@Profiler.BeginSample( "dfMarkupString.SplitWords()" );
var tag = dfMarkupTagSpan.Obtain();
var i = 0;
var x = 0;
var length = Text.Length;
while( i < length )
{
#region Words
while( i < length && !char.IsWhiteSpace( Text[ i ] ) )
{
i += 1;
}
if( i > x )
{
tag.AddChildNode( dfMarkupString.Obtain( Text.Substring( x, i - x ) ) );
x = i;
}
#endregion
#region Non-newline whitespace
while( i < length && Text[ i ] != '\n' && char.IsWhiteSpace( Text[ i ] ) )
{
i += 1;
}
if( i > x )
{
tag.AddChildNode( dfMarkupString.Obtain( Text.Substring( x, i - x ) ) );
x = i;
}
#endregion
#region Newlines
if( i < length && Text[ i ] == '\n' )
{
tag.AddChildNode( dfMarkupString.Obtain( "\n" ) );
x = ++i;
}
#endregion
}
//@Profiler.EndSample();
return tag;
}
#endregion
#region dfMarkupElement overrides
protected override void _PerformLayoutImpl( dfMarkupBox container, dfMarkupStyle style )
{
if( style.Font == null )
return;
var effectiveText = style.PreserveWhitespace || !isWhitespace ? this.Text : " ";
var box = dfMarkupBoxText.Obtain( this, dfMarkupDisplayType.inline, style );
box.SetText( effectiveText );
container.AddChild( box );
}
#endregion
#region Object pooling
internal static dfMarkupString Obtain( string text )
{
if( objectPool.Count > 0 )
{
var instance = objectPool.Dequeue();
instance.Text = dfMarkupEntity.Replace( text );
instance.isWhitespace = whitespacePattern.IsMatch( instance.Text );
return instance;
}
return new dfMarkupString( text );
}
internal override void Release()
{
base.Release();
objectPool.Enqueue( this );
}
#endregion
#region Private utility methods
private string processWhitespace( string text )
{
// http://www.w3.org/TR/CSS21/text.html#white-space-prop
buffer.Length = 0;
buffer.Append( text );
buffer.Replace( "\r\n", "\n" );
buffer.Replace( "\r", "\n" );
buffer.Replace( "\t", " " );
return buffer.ToString();
}
#endregion
}
/// <summary>
/// Represents a key/value pair attribute defined inside of a dfMarkupTag element
/// </summary>
public class dfMarkupAttribute
{
public string Name { get; set; }
public string Value { get; set; }
public dfMarkupAttribute( string name, string value )
{
this.Name = name;
this.Value = value;
}
public override string ToString()
{
return string.Format( "{0}='{1}'", Name, Value );
}
}
|
using System;
using System.IO;
using System.Reflection;
namespace Squirrel
{
/// <summary>
/// Convenience class which provides runtime information about the current executing process,
/// in a way that is safe in older and newer versions of the framework, including SingleFileBundles
/// </summary>
public static class AssemblyRuntimeInfo
{
/// <summary> The path on disk of the entry assembly </summary>
public static string EntryExePath { get; }
/// <summary> Gets the directory that the assembly resolver uses to probe for assemblies. </summary>
public static string BaseDirectory { get; }
/// <summary> The name of the currently executing assembly </summary>
public static AssemblyName ExecutingAssemblyName => Assembly.GetExecutingAssembly().GetName();
/// <summary> Check if the current application is a published SingleFileBundle </summary>
public static bool IsSingleFile { get; }
static AssemblyRuntimeInfo()
{
EntryExePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
BaseDirectory = AppContext.BaseDirectory;
// if Assembly.Location does not exist, we're almost certainly bundled into a dotnet SingleFile
// is there a better way to check for this?
var assyPath = (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly())?.Location;
if (String.IsNullOrEmpty(assyPath) || !File.Exists(assyPath))
IsSingleFile = true;
}
}
}
|
// Built from tag v3.5.0
using System;
using System.Collections.Generic;
using FINT.Model.Administrasjon.Kodeverk;
namespace FINT.Model.Administrasjon.Kodeverk
{
public class Kontrakt : Kontodimensjon {
public enum Relasjonsnavn
{
FULLMAKT
}
}
}
|
using GemBox.Email;
using GemBox.Email.Exchange;
using GemBox.Email.Imap;
using GemBox.Email.Pop;
using GemBox.Email.Smtp;
class Program
{
static void Main()
{
// If using Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
// Create a new POP client.
using (var pop = new PopClient("<ADDRESS> (e.g. pop.gmail.com)"))
{
// Connect and sign to POP server using OAuth 2.0.
pop.Connect();
pop.Authenticate("<USERNAME>", "<ACCESS-TOKEN>", PopAuthentication.XOAuth2);
}
// Create a new IMAP client.
using (var imap = new ImapClient("<ADDRESS> (e.g. imap.gmail.com)"))
{
// Connect and sign to IMAP server using OAuth 2.0.
imap.Connect();
imap.Authenticate("<USERNAME>", "<ACCESS-TOKEN>", ImapAuthentication.XOAuth2);
}
// Create a new SMTP client.
using (var smtp = new SmtpClient("<ADDRESS> (e.g. smtp.gmail.com)"))
{
// Connect and sign to SMTP server using OAuth 2.0.
smtp.Connect();
smtp.Authenticate("<USERNAME>", "<ACCESS-TOKEN>", SmtpAuthentication.XOAuth2);
}
// Create a new Exchange client.
var exchangeClient = new ExchangeClient("<HOST> (e.g. https://outlook.office365.com/EWS/Exchange.asmx)");
// Authenticate the client using OAuth 2.0.
exchangeClient.Authenticate("<USERNAME>", "<ACCESS-TOKEN>", ExchangeAuthentication.OAuth2);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GPA_Calculator.Util
{
public class GradeScale
{
public virtual double A_PLUS { get; }
public virtual double A { get; }
public virtual double A_MINUS { get; }
public virtual double B_PLUS { get; }
public virtual double B { get; }
public virtual double B_MINUS { get; }
public virtual double C_PLUS { get; }
public virtual double C { get; }
public virtual double C_MINUS { get; }
public virtual double D_PLUS { get; }
public virtual double D { get; }
public virtual double D_MINUS { get; }
public virtual Dictionary<string, double> GradeLetterMapping { get; protected set; }
public virtual Dictionary<double, double> GradeLowestNumericMapping { get; protected set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Curriculum.Models.Entities
{
public interface IFirebaseContext
{
DbSet<Information> Informations { get; set; }
DbSet<Knowledge> Knowledges { get; set; }
DbSet<Project> Projects { get; set; }
DbSet<Certification> Certifications { get; set; }
DbSet<Reference> References { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Items/Player Item Type")]
public class PlayerItemType : ItemType {
public string verb_future = "use";
public string verb_present = "use";
public string verb_past = "used";
public int width = 1;
public int height = 1;
public List<ItemAffect> affect;
}
|
// RequireJS.NET
// Copyright VeriTech.io
// http://veritech.io
// Dual licensed under the MIT and GPL licenses:
// http://www.opensource.org/licenses/mit-license.php
// http://www.gnu.org/licenses/gpl.html
using System;
using System.IO;
using System.Linq;
using System.Web;
namespace RequireJsNet.Helpers
{
internal static class PathHelpers
{
public static string MapPath(this HttpContextBase context, string path)
{
if (path.StartsWith("~"))
{
path = context.Server.MapPath(path);
}
return path;
}
public static void VerifyFileExists(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException("Could not find config file", path);
}
}
public static string GetPathWithoutExtension(this string path)
{
if (path != null)
{
int i;
if ((i = path.LastIndexOf('.')) == -1)
{
return path; // No path extension found
}
else
{
return path.Substring(0, i);
}
}
return null;
}
public static string GetOverridePath(string originalPath)
{
var beforeExtension = originalPath.LastIndexOf(".");
if (beforeExtension == -1)
{
return null;
}
var newName = originalPath.Substring(0, beforeExtension)
+ ".override"
+ originalPath.Substring(beforeExtension, originalPath.Length - beforeExtension);
return newName;
}
public static string GetRequirePath(this string path)
{
return path.GetPathWithoutExtension().Replace("\\\\", "/").Replace("\\", "/");
}
public static string ToModuleName(this string relativePath)
{
var initial = relativePath;
relativePath = initial.Replace('/', Path.DirectorySeparatorChar);
var directory = Path.GetDirectoryName(relativePath);
var file = relativePath.EndsWith(".js") ? Path.GetFileNameWithoutExtension(relativePath)
: Path.GetFileName(relativePath);
var name = file;
if (!string.IsNullOrEmpty(directory))
{
name = directory.ToLower() + Path.DirectorySeparatorChar + name;
}
name = name.Replace(Path.DirectorySeparatorChar, '/');
return name;
}
public static string GetRelativePath(string filespec, string folder)
{
var pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
folder += Path.DirectorySeparatorChar;
}
var folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}
public static string GetRequireRelativePath(string folder, string file)
{
return GetRelativePath(file, folder).ToModuleName();
}
// will return the exact fileName for a supplied file path
// not this only returns for the fileName, the directory part of the path will be the same as the one supplied
public static string GetExactFilePath(string suppliedName)
{
return Directory.GetFiles(
Path.GetDirectoryName(suppliedName),
Path.GetFileName(suppliedName))
.FirstOrDefault();
}
}
}
|
using MGXRM.Common.Framework.Interfaces;
using Microsoft.Xrm.Sdk;
namespace MGXRM.Common.Framework.Model
{
public abstract class ModelBase<T> where T : Entity
{
protected IImageManager<T> Images { get; }
protected IContextManager<T> Context { get; }
protected IRepository Repository { get; }
protected ModelBase(IImageManager<T> images, IContextManager<T> context, IRepository repository)
{
Images = images;
Context = context;
Repository = repository;
}
}
}
|
using Xunit;
using System;
using It.FattureInCloud.Sdk.FilterHelper;
namespace It.FattureInCloud.Sdk.Test.FilterHelper
{
/// <summary>
/// Class for testing Filter
/// </summary>
public class FilterTest : IDisposable
{
/// <summary>
/// Test a Filter instance
/// </summary>
[Fact]
public void FilterInstanceTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression e = new Condition<string>("nation", Operator.EQ, "IT");
f = new Filter(e);
Assert.Equal(e, f.Expression);
Expression e1 = new Condition<string>("company", Operator.EQ, "MadBit Entertainment S.r.l.");
f.Expression = e1;
Assert.Equal(e1, f.Expression);
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test the Where method
/// </summary>
[Fact]
public void WhereTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression e = new Condition<string>("nation", Operator.EQ, "IT");
f.Where("nation", Operator.EQ, "IT");
Assert.Equal(e, f.Expression);
Expression e1 = new Condition<string>("company", Operator.EQ, "MadBit Entertainment S.r.l.");
f.Where("company", Operator.EQ, "MadBit Entertainment S.r.l.");
Assert.Equal(e1, f.Expression);
}
/// <summary>
/// Test the WhereExpression method
/// </summary>
[Fact]
public void WhereExpressionTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression e = new Condition<string>("nation", Operator.EQ, "IT");
f.WhereExpression(e);
Assert.Equal(e, f.Expression);
Expression e1 = new Condition<string>("company", Operator.EQ, "MadBit Entertainment S.r.l.");
f.WhereExpression(e1);
Assert.Equal(e1, f.Expression);
}
/// <summary>
/// Test the And method
/// </summary>
[Fact]
public void AndTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression c1 = new Condition<string>("city", Operator.EQ, "Warsaw");
Expression c2 = new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media");
Conjunction conj = new Conjunction(c1, c2);
Exception ex = Assert.Throws<Exception>(() =>
f.And("company", Operator.EQ, "Reply")
);
Assert.Equal("Cannot create a conjunction for an empty expression.", ex.Message);
f.Where("city", Operator.EQ, "Warsaw")
.And("company", Operator.EQ, "Przewodniczka Social Media");
Assert.Equal(conj, f.Expression);
}
/// <summary>
/// Test the AndExpression method
/// </summary>
[Fact]
public void AndExpressionTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression c1 = new Condition<string>("city", Operator.EQ, "Warsaw");
Expression c2 = new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media");
Conjunction conj = new Conjunction(c1, c2);
Exception thrownLeft = Assert.Throws<Exception>(() =>
f.AndExpression(c2)
);
Assert.Equal("Cannot create a conjunction for an empty expression.", thrownLeft.Message);
Exception thrownRight = Assert.Throws<Exception>(() =>
f.WhereExpression(c1)
.AndExpression(null)
);
Assert.Equal("Cannot create a conjunction for an empty expression.", thrownRight.Message);
f.WhereExpression(c1).AndExpression(c2);
Assert.Equal(conj, f.Expression);
}
/// <summary>
/// Test the AndFilter method
/// </summary>
[Fact]
public void AndFilterTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression c1 = new Condition<string>("city", Operator.EQ, "Warsaw");
Expression c2 = new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media");
Conjunction conj = new Conjunction(c1, c2);
Exception thrownLeft = Assert.Throws<Exception>(() =>
f.AndFilter(new Filter(c2))
);
Assert.Equal("Cannot create a conjunction for an empty expression.", thrownLeft.Message);
Exception thrownRight = Assert.Throws<Exception>(() =>
f.WhereExpression(c1)
.AndFilter(new Filter())
);
Assert.Equal("Cannot create a conjunction for an empty expression.", thrownRight.Message);
Exception thrownNull = Assert.Throws<Exception>(() =>
f.WhereExpression(c1)
.AndFilter(null)
);
f.WhereExpression(c1).AndFilter(new Filter(c2));
Assert.Equal(conj, f.Expression);
}
/// <summary>
/// Test the Or method
/// </summary>
[Fact]
public void OrTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression c1 = new Condition<string>("city", Operator.EQ, "Warsaw");
Expression c2 = new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media");
Disjunction disj = new Disjunction(c1, c2);
Exception ex = Assert.Throws<Exception>(() =>
f.Or("company", Operator.EQ, "Reply")
);
Assert.Equal("Cannot create a disjunction for an empty expression.", ex.Message);
f.Where("city", Operator.EQ, "Warsaw")
.Or("company", Operator.EQ, "Przewodniczka Social Media");
Assert.Equal(disj, f.Expression);
}
/// <summary>
/// Test the OrExpression method
/// </summary>
[Fact]
public void OrExpressionTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression c1 = new Condition<string>("city", Operator.EQ, "Warsaw");
Expression c2 = new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media");
Disjunction disj = new Disjunction(c1, c2);
Exception thrownLeft = Assert.Throws<Exception>(() =>
f.OrExpression(c2)
);
Assert.Equal("Cannot create a disjunction for an empty expression.", thrownLeft.Message);
Exception thrownRight = Assert.Throws<Exception>(() =>
f.WhereExpression(c1)
.OrExpression(null)
);
Assert.Equal("Cannot create a disjunction for an empty expression.", thrownRight.Message);
f.WhereExpression(c1).OrExpression(c2);
Assert.Equal(disj, f.Expression);
}
/// <summary>
/// Test the OrFilter method
/// </summary>
[Fact]
public void OrFilterTest()
{
Filter f = new Filter();
Assert.Null(f.Expression);
Expression c1 = new Condition<string>("city", Operator.EQ, "Warsaw");
Expression c2 = new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media");
Disjunction disj = new Disjunction(c1, c2);
Exception thrownLeft = Assert.Throws<Exception>(() =>
f.OrFilter(new Filter(c2))
);
Assert.Equal("Cannot create a disjunction for an empty expression.", thrownLeft.Message);
Exception thrownRight = Assert.Throws<Exception>(() =>
f.WhereExpression(c1)
.OrFilter(new Filter())
);
Assert.Equal("Cannot create a disjunction for an empty expression.", thrownRight.Message);
Exception thrownNull = Assert.Throws<Exception>(() =>
f.WhereExpression(c1)
.OrFilter(null)
);
f.WhereExpression(c1).OrFilter(new Filter(c2));
Assert.Equal(disj, f.Expression);
}
/// <summary>
/// Test the BuildQuery method
/// </summary>
[Fact]
public void BuildQueryTest()
{
Filter f = new Filter();
Assert.Empty(f.BuildQuery());
f = new Filter(new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media"));
Assert.Equal("company = 'Przewodniczka Social Media'", f.BuildQuery());
}
/// <summary>
/// Test the BuildUrlEncodedQuery method
/// </summary>
[Fact]
public void BuildUrlEncodedQueryTest()
{
Filter f = new Filter();
Assert.Empty(f.BuildUrlEncodedQuery());
f = new Filter(new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media"));
Assert.Equal("company+%3d+%27Przewodniczka+Social+Media%27", f.BuildUrlEncodedQuery());
}
/// <summary>
/// Test the ToString method
/// </summary>
[Fact]
public void ToStringTest()
{
Filter f = new Filter();
Assert.Empty(f.ToString());
f = new Filter(new Condition<string>("company", Operator.EQ, "Przewodniczka Social Media"));
Assert.Equal("company = 'Przewodniczka Social Media'", f.ToString());
}
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using VSCommanding = Microsoft.VisualStudio.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal partial class RenameCommandHandler :
VSCommanding.ICommandHandler<SelectAllCommandArgs>
{
public VSCommanding.CommandState GetCommandState(SelectAllCommandArgs args)
{
return GetCommandState();
}
public bool ExecuteCommand(SelectAllCommandArgs args, CommandExecutionContext context)
{
return ExecuteSelectAll(args.SubjectBuffer, args.TextView);
}
private bool ExecuteSelectAll(ITextBuffer subjectBuffer, ITextView view)
{
if (_renameService.ActiveSession == null)
{
return false;
}
var caretPoint = view.GetCaretPoint(subjectBuffer);
if (caretPoint.HasValue)
{
if (_renameService.ActiveSession.TryGetContainingEditableSpan(caretPoint.Value, out var span))
{
if (view.Selection.Start.Position != span.Start.Position ||
view.Selection.End.Position != span.End.Position)
{
view.SetSelection(span);
return true;
}
}
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using GeometricAlgebraSymbolicsLib.Cas.Mathematica;
using GeometricAlgebraSymbolicsLib.Maps.Bilinear;
using GeometricAlgebraSymbolicsLib.Metrics;
using GeometricAlgebraSymbolicsLib.Multivectors;
using GeometricAlgebraSymbolicsLib.Multivectors.Intermediate;
namespace GeometricAlgebraSymbolicsLib.Products
{
public abstract class GaSymBilinearProduct : IGaSymMapBilinear
{
public MathematicaInterface CasInterface
=> GaSymbolicsUtils.Cas;
public MathematicaConnection CasConnection
=> GaSymbolicsUtils.Cas.Connection;
public MathematicaEvaluator CasEvaluator
=> GaSymbolicsUtils.Cas.Evaluator;
public MathematicaConstants CasConstants
=> GaSymbolicsUtils.Cas.Constants;
public abstract IGaSymMetric Metric { get; }
public int TargetVSpaceDimension
=> Metric.VSpaceDimension;
public ulong TargetGaSpaceDimension
=> Metric.GaSpaceDimension;
public int DomainVSpaceDimension
=> Metric.VSpaceDimension;
public ulong DomainGaSpaceDimension
=> Metric.GaSpaceDimension;
public int DomainVSpaceDimension2
=> Metric.VSpaceDimension;
public ulong DomainGaSpaceDimension2
=> Metric.GaSpaceDimension;
public abstract IGaSymMultivector this[ulong id1, ulong id2] { get; }
public GaSymMultivector this[GaSymMultivector mv1, GaSymMultivector mv2]
=> MapToTemp(mv1, mv2).ToMultivector();
public abstract IGaSymMultivectorTemp MapToTemp(ulong id1, ulong id2);
public abstract IGaSymMultivectorTemp MapToTemp(GaSymMultivector mv1, GaSymMultivector mv2);
public abstract IEnumerable<Tuple<ulong, ulong, IGaSymMultivector>> BasisBladesMaps();
public abstract IEnumerable<Tuple<ulong, ulong, IGaSymMultivector>> BasisVectorsMaps();
}
} |
using Newtonsoft.Json;
using SQLite;
using SQLite.Net.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ow.Model
{
[Table("Contacts")]
public class Contact
{
[Column("Id")]
[PrimaryKey]
[JsonProperty("id")]
public int Id { get; set; }
[Column("FirstName")]
[JsonProperty("first_name")]
public string FirstName { get; set; }
[Column("LastName")]
[JsonProperty("last_name")]
public string LastName { get; set; }
[Column("CountryCode")]
[JsonProperty("country_code")]
public string CountryCode { get; set; }
[Column("PhoneNumber")]
[JsonProperty("phone_number")]
public string PhoneNumber { get; set; }
}
}
|
using SqlSugar;
namespace GatewayServer.AsyncProxyConfig.Entities
{
[SugarTable("destination")]
public class ClusterDestinationEntity : EntityBase
{
[SugarColumn(ColumnName = "id", IsPrimaryKey = true, IsIdentity = true)]
public long Id { get; set; }
/// <summary>
/// 关联的集群
/// </summary>
[SugarColumn(ColumnName = "cluster_code")]
public string ClusterCode { get; set; } = "";
/// <summary>
/// 匹配地址
/// </summary>
[SugarColumn(ColumnName = "address")]
public string Address { get; set; } = "";
/// <summary>
/// 健康检查地址
/// </summary>
[SugarColumn(ColumnName = "helth_check_path")]
public string HelthCheckPath { get; set; } = "";
[SugarColumn(ColumnName = "is_deleted")]
public short IsDeleted { get; set; }
[SugarColumn(ColumnName = "name")]
public string Name { get; set; } = "";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Common;
using Mechsoft.GeneralUtilities;
using log4net;
/// <summary>
/// Summary description for Cls_Calculator
/// </summary>
public class Cls_Calculator
{
#region
static ILog logger = LogManager.GetLogger(typeof(Cls_Calculator));
DataTable dt;
public int FromStateID { get; set; }
public int ToStateID { get; set; }
#endregion
public Cls_Calculator()
{
//
// TODO: Add constructor logic here
//
}
public DataTable GetCharges()
{
DbCommand objCmd = null;
try
{
objCmd = Cls_DataAccess.getInstance().GetCommand(CommandType.StoredProcedure, "SpGetCharges");
Cls_DataAccess.getInstance().AddInParameter(objCmd, "FromStateID", DbType.Int32, FromStateID);
Cls_DataAccess.getInstance().AddInParameter(objCmd, "ToStateID", DbType.Int32, ToStateID);
return Cls_DataAccess.getInstance().GetDataTable(objCmd);
}
catch (Exception ex)
{
logger.Error("Get Charges Err - " + ex.Message);
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using Prometheus.Compile;
using Prometheus.Exceptions.Compiler;
using Prometheus.Exceptions.Executor;
using Prometheus.Grammar;
using Prometheus.Nodes;
using Prometheus.Nodes.Types;
using Prometheus.Nodes.Types.Bases;
using Prometheus.Parser.Executors;
using Prometheus.Parser.Executors.Attributes;
namespace Prometheus.Runtime
{
/// <summary>
/// Implements the operators for greater than and less than.
/// </summary>
// ReSharper disable UnusedParameter.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable ClassNeverInstantiated.Global
public class Relational : ExecutorGrammar, iOptimizer
{
/// <summary>
/// A list of relational operators
/// </summary>
private static readonly HashSet<GrammarSymbol> _compareSymbols = new HashSet<GrammarSymbol>
{
GrammarSymbol.GtOperator,
GrammarSymbol.LtOperator,
GrammarSymbol.GteOperator,
GrammarSymbol.LteOperator,
GrammarSymbol.EqualOperator,
GrammarSymbol.NotEqualOperator,
GrammarSymbol.AndOperator,
GrammarSymbol.OrOperator
};
/// <summary>
/// Checks if a node performs math operations on two constant values.
/// </summary>
/// <param name="pNode">The node to check</param>
/// <returns>True if it can be reduced.</returns>
private static bool CanReduce(Node pNode)
{
return (_compareSymbols.Contains(pNode.Symbol)
&& pNode.Children[0].Symbol == GrammarSymbol.Value
&& pNode.Children[1].Symbol == GrammarSymbol.Value);
}
/// <summary>
/// Constructor
/// </summary>
public Relational(Executor pExecutor)
: base(pExecutor)
{
}
/// <summary>
/// Filter what nodes this optimizer is executed for.
/// </summary>
public bool Optimizable(GrammarSymbol pType)
{
return _compareSymbols.Contains(pType);
}
/// <summary>
/// Called for each node in the tree. Implement this to
/// modify just the node.
/// </summary>
/// <returns>True if tree was modified.</returns>
public bool OptimizeNode(Node pNode)
{
if (pNode.Children.Count != 2
|| pNode.Data.Count != 0
|| !CanReduce(pNode))
{
return false;
}
if (pNode.Children[0].Data.Count != 1
|| pNode.Children[1].Data.Count != 1)
{
return false;
}
DataType valueA = pNode.Children[0].Data[0];
DataType valueB = pNode.Children[1].Data[0];
pNode.Children.Clear();
switch (pNode.Symbol)
{
case GrammarSymbol.GtOperator:
pNode.Data.Add(GreaterThan(pNode, valueA, valueB));
break;
case GrammarSymbol.LtOperator:
pNode.Data.Add(LessThan(pNode, valueA, valueB));
break;
case GrammarSymbol.GteOperator:
pNode.Data.Add(GreaterThanEqual(pNode, valueA, valueB));
break;
case GrammarSymbol.LteOperator:
pNode.Data.Add(LessThanEqual(pNode, valueA, valueB));
break;
case GrammarSymbol.EqualOperator:
pNode.Data.Add(Equal(pNode, valueA, valueB));
break;
case GrammarSymbol.NotEqualOperator:
pNode.Data.Add(NotEqual(pNode, valueA, valueB));
break;
case GrammarSymbol.AndOperator:
pNode.Data.Add(AndOp(pNode, valueA, valueB));
break;
case GrammarSymbol.OrOperator:
pNode.Data.Add(OrOp(pNode, valueA, valueB));
break;
default:
throw new UnsupportedDataTypeException(
string.Format("Cannot optimize <{0}> value type", pNode.Symbol), pNode.Location);
}
pNode.Symbol = GrammarSymbol.Value;
return true;
}
/// <summary>
/// Inspect a node
/// </summary>
/// <param name="pParent"></param>
/// <param name="pChild"></param>
/// <returns>Same node, a new node or null to remove it.</returns>
public bool OptimizeChild(Node pParent, Node pChild)
{
return false;
}
/// <summary>
/// Called when a parent node matches the handled type. Implement this to
/// modify the parent to child relationship.
/// </summary>
/// <returns>True if tree was modified.</returns>
public bool OptimizeParent(Node pParent, Node pChild)
{
return false;
}
/// <summary>
/// Inspect a node after optimization has finished. This method
/// is called only once per node.
/// </summary>
public void OptimizePost(Node pNode)
{
}
/// <summary>
/// Checks if an array contains a data type using relational equals operator.
/// </summary>
public static bool Contains(ArrayType pArr, DataType pValue)
{
for (int i = 0, c = pArr.Values.Count; i < c; i++)
{
if (DataEqual(pArr.Values[i], pValue))
{
return true;
}
}
return false;
}
/// <summary>
/// Used to recursively compare arrays.
/// </summary>
public static bool DataEqual(DataType pValue1, DataType pValue2)
{
// same object reference
if (pValue1 == pValue2)
{
return true;
}
// compare strings
StringType str1 = pValue1 as StringType;
StringType str2 = pValue2 as StringType;
if (str1 != null && str2 != null)
{
return str1.IgnoreCase || str2.IgnoreCase
? String.Compare(str1.Value, str2.Value, StringComparison.CurrentCultureIgnoreCase) == 0
: String.CompareOrdinal(str1.Value, str2.Value) == 0;
}
// compare numbers
NumericType num1 = pValue1 as NumericType;
NumericType num2 = pValue2 as NumericType;
if (num1 != null && num2 != null)
{
if (num1.Type == num2.Type && num1.isLong)
{
return num1.Long == num2.Long;
}
return System.Math.Abs(num1.Double - num2.Double) < 0.0000000000001;
}
// compare boolean
BooleanType bool1 = pValue1 as BooleanType;
BooleanType bool2 = pValue2 as BooleanType;
if (bool1 != null && bool2 != null)
{
return bool1.Value == bool2.Value;
}
// compare pointers
InstanceType inst1 = pValue1 as InstanceType;
InstanceType inst2 = pValue2 as InstanceType;
if (inst1 != null && inst2 != null)
{
return inst1 == inst2;
}
// compare with undefined
UndefinedType undefined1 = pValue1 as UndefinedType;
UndefinedType undefined2 = pValue2 as UndefinedType;
if (undefined1 != null && undefined2 != null)
{
return true;
}
if (undefined1 != null || undefined2 != null)
{
return false;
}
// TODO: This might get stuck in a recursion loop if the array contains a reference to the same array twice
// compare array
ArrayType array1 = pValue1 as ArrayType;
ArrayType array2 = pValue2 as ArrayType;
if (array1 != null && array2 != null)
{
if (array1.Count != array2.Count)
{
return false;
}
bool result = true;
for (int i = 0, c = array1.Count; i < c; i++)
{
result &= DataEqual(array1[i], array2[i]);
}
return result;
}
return false;
}
/// <summary>
/// AND operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.AndOperator)]
public DataType AndOp(Node pNode, DataType pValue1, DataType pValue2)
{
pValue1 = Resolve(pValue1);
pValue2 = Resolve(pValue2);
BooleanType bool1 = pValue1 as BooleanType;
BooleanType bool2 = pValue2 as BooleanType;
if (bool1 != null && bool2 != null)
{
return new BooleanType(bool1.Value && bool2.Value);
}
throw DataTypeException.InvalidTypes("AND", pValue1, pValue2);
}
/// <summary>
/// ~ operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.BitInvertOperator)]
public DataType Bitwise(Node pNode, DataType pValue)
{
pValue = Resolve(pValue);
NumericType num = pValue as NumericType;
if (num != null && num.isLong)
{
return new NumericType(~num.Long);
}
throw DataTypeException.InvalidTypes("~", pValue);
}
/// <summary>
/// Equal
/// </summary>
[ExecuteSymbol(GrammarSymbol.EqualOperator)]
public DataType Equal(Node pNode, DataType pValue1, DataType pValue2)
{
DataType data1 = Resolve(pValue1);
DataType data2 = Resolve(pValue2);
return new BooleanType(DataEqual(data1, data2));
}
/// <summary>
/// Not operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.NotOperator)]
public DataType Equal(Node pNode, DataType pValue1)
{
pValue1 = Resolve(pValue1);
BooleanType bool1 = pValue1 as BooleanType;
if (bool1 != null)
{
return new BooleanType(!bool1.Value);
}
throw DataTypeException.InvalidTypes("NOT", pValue1);
}
/// <summary>
/// Greater Than
/// </summary>
[ExecuteSymbol(GrammarSymbol.GtOperator)]
public DataType GreaterThan(Node pNode, DataType pValue1, DataType pValue2)
{
pValue1 = Resolve(pValue1);
pValue2 = Resolve(pValue2);
StringType str1 = pValue1 as StringType;
StringType str2 = pValue2 as StringType;
if (str1 != null && str2 != null)
{
return new BooleanType(String.CompareOrdinal(str1.Value, str2.Value) > 0);
}
NumericType num1 = pValue1 as NumericType;
NumericType num2 = pValue2 as NumericType;
if (num1 != null && num2 != null)
{
if (num1.Type == num2.Type && num1.Type == typeof (long))
{
return new BooleanType(num1.Long > num2.Long);
}
return new BooleanType(num1.Double > num2.Double);
}
throw DataTypeException.InvalidTypes(">", pValue1, pValue2);
}
/// <summary>
/// Greater Than
/// </summary>
[ExecuteSymbol(GrammarSymbol.GteOperator)]
public DataType GreaterThanEqual(Node pNode, DataType pValue1, DataType pValue2)
{
pValue1 = Resolve(pValue1);
pValue2 = Resolve(pValue2);
StringType str1 = pValue1 as StringType;
StringType str2 = pValue2 as StringType;
if (str1 != null && str2 != null)
{
return new BooleanType(String.CompareOrdinal(str1.Value, str2.Value) >= 0);
}
NumericType num1 = pValue1 as NumericType;
NumericType num2 = pValue2 as NumericType;
if (num1 != null && num2 != null)
{
if (num1.Type == num2.Type && num1.Type == typeof (long))
{
return new BooleanType(num1.Long >= num2.Long);
}
return new BooleanType(num1.Double >= num2.Double);
}
throw DataTypeException.InvalidTypes(">=", pValue1, pValue2);
}
/// <summary>
/// Greater Than
/// </summary>
[ExecuteSymbol(GrammarSymbol.LtOperator)]
public DataType LessThan(Node pNode, DataType pValue1, DataType pValue2)
{
pValue1 = Resolve(pValue1);
pValue2 = Resolve(pValue2);
StringType str1 = pValue1 as StringType;
StringType str2 = pValue2 as StringType;
if (str1 != null && str2 != null)
{
return new BooleanType(String.CompareOrdinal(str1.Value, str2.Value) < 0);
}
NumericType num1 = pValue1 as NumericType;
NumericType num2 = pValue2 as NumericType;
if (num1 != null && num2 != null)
{
if (num1.Type == num2.Type && num1.Type == typeof (long))
{
return new BooleanType(num1.Long < num2.Long);
}
return new BooleanType(num1.Double < num2.Double);
}
throw DataTypeException.InvalidTypes("<", pValue1, pValue2);
}
/// <summary>
/// Greater Than
/// </summary>
[ExecuteSymbol(GrammarSymbol.LteOperator)]
public DataType LessThanEqual(Node pNode, DataType pValue1, DataType pValue2)
{
pValue1 = Resolve(pValue1);
pValue2 = Resolve(pValue2);
StringType str1 = pValue1 as StringType;
StringType str2 = pValue2 as StringType;
if (str1 != null && str2 != null)
{
return new BooleanType(String.CompareOrdinal(str1.Value, str2.Value) <= 0);
}
NumericType num1 = pValue1 as NumericType;
NumericType num2 = pValue2 as NumericType;
if (num1 != null && num2 != null)
{
if (num1.Type == num2.Type && num1.Type == typeof (long))
{
return new BooleanType(num1.Long <= num2.Long);
}
return new BooleanType(num1.Double <= num2.Double);
}
throw DataTypeException.InvalidTypes("<=", pValue1, pValue2);
}
/// <summary>
/// - operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.NegOperator)]
public DataType Negative(Node pNode, DataType pValue)
{
pValue = Resolve(pValue);
NumericType num = pValue as NumericType;
if (num != null)
{
return num.isLong
? new NumericType(-num.Long)
: new NumericType(-num.Double);
}
throw DataTypeException.InvalidTypes("-", pValue);
}
/// <summary>
/// Not equal
/// </summary>
[ExecuteSymbol(GrammarSymbol.NotEqualOperator)]
public DataType NotEqual(Node pNode, DataType pValue1, DataType pValue2)
{
pValue1 = Resolve(pValue1);
pValue2 = Resolve(pValue2);
return new BooleanType(!DataEqual(pValue1, pValue2));
}
/// <summary>
/// OR operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.OrOperator)]
public DataType OrOp(Node pNode, DataType pValue1, DataType pValue2)
{
pValue1 = Resolve(pValue1);
pValue2 = Resolve(pValue2);
BooleanType bool1 = pValue1 as BooleanType;
BooleanType bool2 = pValue2 as BooleanType;
if (bool1 != null && bool2 != null)
{
return new BooleanType(bool1.Value || bool2.Value);
}
throw DataTypeException.InvalidTypes("OR", pValue1, pValue2);
}
/// <summary>
/// + operator
/// Doesn't change the value, but can only work on numeric types.
/// </summary>
[ExecuteSymbol(GrammarSymbol.PlusOperator)]
public DataType Plus(Node pNode, DataType pValue)
{
pValue = Resolve(pValue);
NumericType num = pValue as NumericType;
if (num != null)
{
return num;
}
throw DataTypeException.InvalidTypes("+", pValue);
}
/// <summary>
/// x-- operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.PostDecOperator)]
public DataType PostDec(Node pNode, QualifiedType pValue)
{
iVariablePointer pointer = Cursor.Resolve(pValue);
NumericType num = pointer.Read() as NumericType;
if (num == null)
{
throw DataTypeException.InvalidTypes("--", pValue);
}
num = num.isLong
? new NumericType(num.Long - 1)
: new NumericType(num.Double - 1.0);
pointer.Write(num);
return num;
}
/// <summary>
/// x++ operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.PostIncOperator)]
public DataType PostInc(Node pNode, QualifiedType pValue)
{
iVariablePointer pointer = Cursor.Resolve(pValue);
NumericType num = pointer.Read() as NumericType;
if (num == null)
{
throw DataTypeException.InvalidTypes("++", pValue);
}
num = num.isLong
? new NumericType(num.Long + 1)
: new NumericType(num.Double + 1.0);
pointer.Write(num);
return num;
}
/// <summary>
/// --x operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.PreDecOperator)]
public DataType PreDec(Node pNode, QualifiedType pValue)
{
iVariablePointer pointer = Cursor.Resolve(pValue);
NumericType num = pointer.Read() as NumericType;
if (num == null)
{
throw DataTypeException.InvalidTypes("--", pValue);
}
pointer.Write(num.isLong
? new NumericType(num.Long - 1)
: new NumericType(num.Double - 1.0));
return num;
}
/// <summary>
/// ++x operator
/// </summary>
[ExecuteSymbol(GrammarSymbol.PreIncOperator)]
public DataType PreInc(Node pNode, QualifiedType pValue)
{
iVariablePointer pointer = Cursor.Resolve(pValue);
NumericType num = pointer.Read() as NumericType;
if (num == null)
{
throw DataTypeException.InvalidTypes("++", pValue);
}
pointer.Write(num.isLong
? new NumericType(num.Long + 1)
: new NumericType(num.Double + 1.0));
return num;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace Unity.QuickSearch
{
class StringListView : TreeView
{
private string[] m_Models;
private string m_InitialValue;
public event Action<int> elementActivated;
static class Styles
{
public static readonly GUIStyle label = new GUIStyle(EditorStyles.label)
{
richText = true
};
}
public StringListView(string initialValue, string[] models, TreeViewState treeViewState = null)
: base(treeViewState ?? new TreeViewState())
{
m_Models = models;
m_InitialValue = initialValue;
showAlternatingRowBackgrounds = true;
Reload();
}
protected override TreeViewItem BuildRoot()
{
var root = new TreeViewItem { id = 0, depth = -1, displayName = "Root" };
var allItems = new List<TreeViewItem>();
var selectionIds = new List<int>();
for (var i = 0; i < m_Models.Length; i++)
{
if (m_Models[i] == m_InitialValue)
selectionIds.Add(i + 1);
allItems.Add(new TreeViewItem { id = i + 1, depth = 0, displayName = m_Models[i]});
}
SetupParentsAndChildrenFromDepths(root, allItems);
EditorApplication.delayCall += () =>
{
SetSelection(selectionIds);
if (selectionIds.Count > 0)
FrameItem(selectionIds.Last());
Repaint();
};
return root;
}
protected override void RowGUI(RowGUIArgs args)
{
GUI.Label(args.rowRect, args.item.displayName, Styles.label);
}
protected override void DoubleClickedItem(int id)
{
var item = FindItem(id, rootItem);
elementActivated?.Invoke(item.id - 1);
}
protected override void KeyEvent()
{
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return)
{
var selection = GetSelection();
if (selection.Count == 0)
return;
var item = FindItem(selection[0], rootItem);
elementActivated?.Invoke(item.id - 1);
}
}
public bool IsFirstItemSelected()
{
var selection = GetSelection();
if (selection.Count == 0)
return false;
var allRows = GetRows();
if (allRows.Count == 0)
return false;
var selectedItems = FindRows(selection);
return allRows[0] == selectedItems[0];
}
}
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Libuv.Native
{
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
sealed unsafe class Async : NativeHandle
{
static readonly uv_work_cb WorkCallback = OnWorkCallback;
readonly Action<object> callback;
readonly object state;
public Async(Loop loop, Action<object> callback, object state)
: base(uv_handle_type.UV_ASYNC)
{
Debug.Assert(loop != null);
Debug.Assert(callback != null);
IntPtr handle = NativeMethods.Allocate(uv_handle_type.UV_ASYNC);
try
{
int result = NativeMethods.uv_async_init(loop.Handle, handle, WorkCallback);
NativeMethods.ThrowIfError(result);
}
catch
{
NativeMethods.FreeMemory(handle);
throw;
}
GCHandle gcHandle = GCHandle.Alloc(this, GCHandleType.Normal);
((uv_handle_t*)handle)->data = GCHandle.ToIntPtr(gcHandle);
this.Handle = handle;
this.callback = callback;
this.state = state;
}
public void Send()
{
if (!this.IsValid)
{
return;
}
int result = NativeMethods.uv_async_send(this.Handle);
NativeMethods.ThrowIfError(result);
}
void OnWorkCallback()
{
try
{
this.callback(this.state);
}
catch (Exception exception)
{
Logger.Error($"{this.HandleType} {this.Handle} callback error.", exception);
}
}
static void OnWorkCallback(IntPtr handle)
{
var workHandle = GetTarget<Async>(handle);
workHandle?.OnWorkCallback();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AppBarragem.VO
{
public class Menu
{
public int Id { get; set; }
public string NameOption { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string Area { get; set; }
public string ImageClass { get; set; }
public string ParentId { get; set; }
public string IsParent { get; set; }
public string Activeli { get; set; }
public string Status { get; set; }
}
}
|
<!DOCTYPE html>
<html>
<head>
@using PierresBakery.Models;
<title>Welcome Pierre</title>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>
</head>
<body>
<p>@Model["vendor"].VendorTitle</p>
<p>@Model["vendor"].Description</p>
<a href='/vendors/new'>Add New Vendor</a>
<a href='/vendors'>View Vendors List</a>
<a href='/vendors/@Model["vendor"].Id/orders/new'>Add Order</a>
<ol>
@foreach (Order order in @Model["orders"])
{
<li><a href='/vendors/@Model["vendor"].Id/orders/@order.Id'>@order.Title</a></li>
}
</ol>
</body> |
using PerPush.Api.DtoParameters;
using PerPush.Api.Entities;
using PerPush.Api.Helpers;
using PerPush.Api.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PerPush.Api.Services
{
public interface IUserService
{
//--------------------Account Management----------------
Task<User> GetUserInfoAsync(Guid userId);
void UpdateUserInfo(User user);
Task<bool> RegisteredUser(User user);
//---------------------Paper------------------
//public or private File under user name
Task<PagedList<Paper>> GetUserPrivatePapersAsync(Guid userId, PaperDtoParameters parameters);
Task<IEnumerable<Paper>> GetUserPrivatePapersAsync(Guid userId, IEnumerable<Guid> papersId);
Task<PagedList<Paper>> GetUserPublicPaperAsync(Guid userId, PaperDtoParameters parameters);
Task<IEnumerable<Paper>> GetUserPublicPaperAsync(Guid userId, IEnumerable<Guid> papersId);
Task<Paper> GetPaperAsync(Guid userId, Guid paperId);
Task<Guid> GetUserIdAsync(string userName);
//------------ Need to execute SaveAsync Method
void AddPaper(Guid userId, Paper paper);
void UpdatePaper(Paper paper);
void DeletePaper(Paper paper);
//--------------------------------------------
Task<bool> UserExistsAsync(Guid userId);
//Save Data to DataBase
Task<bool> SaveAsync();
//----------Determine whether the login parameters are valid-------
Guid IsValid(LoginRequestDto req);
}
}
|
using System;
namespace Onion.Application.DTOs
{
/// <summary>
/// Paginated record response model.
/// </summary>
/// <typeparam name="T">Type of the record data.</typeparam>
public class PagedResponse<T> : Response<T>
{
/// <summary>
/// Gets or sets current page number.
/// </summary>
public int PageNumber { get; set; }
/// <summary>
/// Gets or sets record count per page.
/// </summary>
public int PageSize { get; set; }
/// <summary>
/// Gets or sets first page URL.
/// </summary>
public Uri? FirstPage { get; set; }
/// <summary>
/// Gets or sets last page URL.
/// </summary>
public Uri? LastPage { get; set; }
/// <summary>
/// Gets or sets total page count.
/// </summary>
public int TotalPages { get; set; }
/// <summary>
/// Gets or sets total record count.
/// </summary>
public int TotalRecords { get; set; }
/// <summary>
/// Gets or sets next page URL.
/// </summary>
public Uri? NextPage { get; set; }
/// <summary>
/// Gets or sets previous page URL.
/// </summary>
public Uri? PreviousPage { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="PagedResponse{T}"/> class.
/// </summary>
/// <param name="data">Paginated record dara.</param>
/// <param name="pageNumber">Current page number.</param>
/// <param name="pageSize">Record count per page.</param>
public PagedResponse(T data, int pageNumber, int pageSize)
: base(data, null)
{
PageNumber = pageNumber;
PageSize = pageSize;
Message = null;
Succeeded = true;
Errors = null;
}
}
} |
/* $Id $ */
/*
* Copyright (C) 2018-2018 Teluu Inc. (http://www.teluu.com)
*
* 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
*/
using System;
using pjsua2xamarin.pjsua2;
namespace pjsua2xamarin
{
public class MyAccount : Account
{
~MyAccount()
{
Console.WriteLine("*** Account is being deleted");
}
override public void onRegState(OnRegStateParam prm)
{
AccountInfo ai = getInfo();
Console.WriteLine("***" + (ai.regIsActive? "": "Un") +
"Register: code=" + prm.code);
}
}
public class MyLogWriter : LogWriter
{
override public void write(LogEntry entry)
{
Console.WriteLine(entry.msg);
}
}
public class sample
{
public static Endpoint ep = new Endpoint();
public static MyLogWriter writer = new MyLogWriter();
public sample()
{
}
public void test1()
{
try {
ep.libCreate();
// Init library
EpConfig epConfig = new EpConfig();
epConfig.logConfig.writer = writer;
ep.libInit(epConfig);
// Create transport
TransportConfig tcfg = new TransportConfig();
tcfg.port = 5080;
ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_UDP,
tcfg);
ep.transportCreate(pjsip_transport_type_e.PJSIP_TRANSPORT_TCP,
tcfg);
// Start library
ep.libStart();
Console.WriteLine("*** PJSUA2 STARTED ***");
// Add account
AccountConfig accCfg = new AccountConfig();
accCfg.idUri = "sip:test1@pjsip.org";
accCfg.regConfig.registrarUri = "sip:sip.pjsip.org";
accCfg.sipConfig.authCreds.Add(
new AuthCredInfo("digest", "*", "test1", 0, "test1") );
MyAccount acc = new MyAccount();
acc.create(accCfg);
Console.WriteLine("*** DESTROYING PJSUA2 ***");
// Explicitly delete account when unused
acc.Dispose();
ep.libDestroy();
} catch (Exception err) {
Console.WriteLine("Exception: " + err.Message);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.