text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using ProyectoArqui.Logica;
namespace ProyectoArqui
{
static class Program
{
//buses
public static readonly object[] BusDatos = new object[2];
public static readonly object[] BusInstrucciones = new object[2];
public static readonly object BusContextos = new object();
public static readonly object BusFinalizados = new object();
public static readonly object[] BusMemorias = new object[2];
public static readonly object[] BusDirectorios = new object[2];
public static readonly object[] BusCaches = new object[3];
public static Form1 Vista;
//public static Shared shared = new Shared();
//public static Controladora controladora = new Controladora();
/*
public static List<Nucleo> Procesador1 = new List<Nucleo>();
public static List<Nucleo> Procesador2 = new List<Nucleo>();
//contador de ciclos de reloj para la ejecucion
public static int Reloj = 0;
//public static List<Barrier> barrerasDeReloj = new List<Barrier>();//(3, barrier => Reloj++);
public static Barrier barreraReloj = new Barrier(3, barrier => TickReloj());
//cola que tendra los hilillos listos para ser ejecutados en los nucleos
public static Queue<Hilillo> ColaHilillos = new Queue<Hilillo>();
//cola que tendra los contextos de los hilillos
public static Queue<ContextoHilillo> ColaContextos = new Queue<ContextoHilillo>();
//16 bloques [0-252] = 16 bloques x 4 entradas = 64 enteros
public static int[] MCP1 = new int[64]; //Memoria compartida del procesador 1
//24 bloques [256-636] (96 instrucciones) = 24 bloques x 16 entradas = 384 enteros
public static int[] MIP1 = new int[384]; //Memoria de instrucciones del procesador 1
//8 bloques [256-380] = 8 bloques x 4 entradas = 32 enteros
public static int[] MCP2 = new int[32]; //Memoria compartida del procesador 2
//16 bloques [128-380] (64 instrucciones) = 16 bloques x 16 enteros = 256 enteros
public static int[] MIP2 = new int[256]; //Memoria de instrucciones del procesador 2
//Nucleo 1
//caché de datos, matriz de 6 filas (4 palabras + 1 para etiqueta de bloque + 1 para estado) x 4 columnas de enteros
public static int[,] CacheN1 = new int[6, 4];
//cache de instrucciones, cada celda tiene una instruccion
public static Instruccion[,] CacheInstN1 = new Instruccion[5, 4];
//contador de las instrucciones completas permitidas por hilo o simplemente, el quantum
public static Quantum QuantumN1 = new Quantum();
//Nucleo 2
//caché de datos, matriz de 6 filas (4 palabras + 1 para etiqueta de bloque + 1 para estado) x 4 columnas de enteros
public static int[,] CacheN2 = new int[6, 4];
//cache de instrucciones, cada celda tiene una instruccion
public static Instruccion[,] CacheInstN2 = new Instruccion[5, 4];
//contador de las instrucciones completas permitidas por hilo o simplemente, el quantum
public static Quantum QuantumN2 = new Quantum();
//Nucleo 3
//caché de datos, matriz de 6 filas (4 palabras + 1 para etiqueta de bloque + 1 para estado) x 4 columnas de enteros
public static int[,] CacheN3 = new int[6, 4];
//cache de instrucciones, cada celda tiene una instruccion
public static Instruccion[,] CacheInstN3 = new Instruccion[5, 4];
//contador de las instrucciones completas permitidas por hilo o simplemente, el quantum
public static Quantum QuantumN3 = new Quantum();
//Directorio procesador 1, 16 bloques x 4 columnas (estado, N0, N1, N2)
public static int[,] DirectorioP1 = new int[16, 4];
//Directorio procesador 2, 8 bloques x 4 columnas (estado, N0, N1, N2)
public static int[,] DirectorioP2 = new int[8, 4];
//funcion para simular el tick de reloj
static void TickReloj()
{
Reloj++;
//theForm.AppendReloj(Reloj.ToString());
}
*/
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/*
Queue<int> q1 = new Queue<int>();
Queue<int> q2 = new Queue<int>();
for(int i = 0; i < 1000000; ++i)
{
BusDatos[i] = new object();
}
for (int i = 0; i < 2; ++i)
{
BusInstrucciones[i] = new object();
}
*/
/*
Instruccion instr = new Instruccion
{
//35 4 11 4
CodigoOp = 35,
RF1 = 4,
RF2_RD = 11,
RD_IMM = 4
};
Nucleo nucleo = new Nucleo(1, 1);
shared.memoriasCompartida.ElementAt(0)[2] = 10;
shared.memoriasCompartida.ElementAt(0)[1] = 15;
shared.memoriasCompartida.ElementAt(0)[0] = 2;
//imprime bloque de memoria
for (int i = 0; i < 4; i++)
{
Console.Write("memoria: {0}\n", shared.memoriasCompartida.ElementAt(0)[i]);
}
Console.Write("antes del load: {0}\n", nucleo.Registros[11]);
nucleo.EjecutarLW(instr);
Console.Write("despues del load: {0}\n", nucleo.Registros[11]);
Instruccion instr2 = new Instruccion
{
//35 4 11 0
CodigoOp = 35,
RF1 = 4,
RF2_RD = 11,
RD_IMM = 0
};
nucleo.EjecutarLW(instr2);
Console.Write("load con hit: {0}\n", nucleo.Registros[11]);
*/
//incializa buses
for(int i=0;i<2;++i)
{
BusInstrucciones[i] = new object();
BusDatos[i] = new object();
BusMemorias[i] = new object();
BusDirectorios[i] = new object();
}
for (int i = 0; i<3; i++)
{
BusCaches[i] = new object();
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Vista = new Form1();
Application.Run(new Form1());
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonScript : MonoBehaviour
{
public void OnClick()
{
GameObject obj = GameObject.FindGameObjectWithTag("Ground");
GameObject pl = GameObject.Find("Player");
SystemScript sc = pl.GetComponent<SystemScript>();
sc.GenerateTarget();
PlayerController plc = pl.GetComponent<PlayerController>();
plc.sccore = 0;
obj.gameObject.SetActive(false);
}
}
|
namespace NorthwindWebAPIServices
{
using System.Web;
using System.Web.Http;
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.RegisterRoutes);
GlobalConfiguration.Configure(WebApiConfig.RegisterDependencyResolver);
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using RMAT3.Models;
namespace RMAT3.Data.Mapping
{
public class SectionQuestionTypeMap : EntityTypeConfiguration<SectionQuestionType>
{
public SectionQuestionTypeMap()
{
// Primary Key
HasKey(t => t.SectionQuestionTypeId);
// Properties
Property(t => t.AddedByUserId)
.IsRequired()
.HasMaxLength(20);
Property(t => t.UpdatedByUserId)
.IsRequired()
.HasMaxLength(20);
Property(t => t.UpdatedCommentTxt)
.HasMaxLength(100);
Property(t => t.SectionTypeTxt)
.HasMaxLength(200);
// Table & Column Mappings
ToTable("SectionQuestionType", "OLTP");
Property(t => t.SectionQuestionTypeId).HasColumnName("SectionQuestionTypeId");
Property(t => t.AddedByUserId).HasColumnName("AddedByUserId");
Property(t => t.AddTs).HasColumnName("AddTs");
Property(t => t.UpdatedByUserId).HasColumnName("UpdatedByUserId");
Property(t => t.UpdatedCommentTxt).HasColumnName("UpdatedCommentTxt");
Property(t => t.UpdatedTs).HasColumnName("UpdatedTs");
Property(t => t.IsActiveInd).HasColumnName("IsActiveInd");
Property(t => t.EffectiveFromDt).HasColumnName("EffectiveFromDt");
Property(t => t.EffectiveToDt).HasColumnName("EffectiveToDt");
Property(t => t.DisplayOrderNbr).HasColumnName("DisplayOrderNbr");
Property(t => t.SectionTypeTxt).HasColumnName("SectionTypeTxt");
Property(t => t.WarrantyTypeId).HasColumnName("WarrantyTypeId");
Property(t => t.QuestionTypeId).HasColumnName("QuestionTypeId");
Property(t => t.SectionTypeId).HasColumnName("SectionTypeId");
Property(t => t.QuestionControlTypeId).HasColumnName("QuestionControlTypeId");
// Relationships
HasOptional(t => t.QuestionControlType)
.WithMany(t => t.SectionQuestionTypes)
.HasForeignKey(d => d.QuestionControlTypeId);
HasRequired(t => t.QuestionType)
.WithMany(t => t.SectionQuestionTypes)
.HasForeignKey(d => d.QuestionTypeId);
HasRequired(t => t.SectionType)
.WithMany(t => t.SectionQuestionTypes)
.HasForeignKey(d => d.SectionTypeId);
HasOptional(t => t.WarrantyType)
.WithMany(t => t.SectionQuestionTypes)
.HasForeignKey(d => d.WarrantyTypeId);
}
}
}
|
using System;
using System.Data.Entity;
namespace Repositories
{
public interface IUnitOfWork : IDisposable
{
int Save();
DbContext Context
{ get; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace ObjectPrinting
{
public class PrintingConfig<TOwner> : IPrintingConfig<TOwner>
{
private readonly ImmutableDictionary<Type, Delegate> _changedTypes;
private readonly ImmutableHashSet<string> _forbiddenNames;
private readonly ImmutableHashSet<Type> _forbiddenTypes;
private readonly string _newLine = Environment.NewLine;
private readonly Lazy<HashSet<MemberInfo>> _printedObjects = new Lazy<HashSet<MemberInfo>>();
private readonly int _restrictionAmount = 100;
public PrintingConfig()
{
_changedTypes = ImmutableDictionary<Type, Delegate>.Empty;
_forbiddenTypes = ImmutableHashSet<Type>.Empty;
_forbiddenNames = ImmutableHashSet<string>.Empty;
}
private PrintingConfig(
ImmutableHashSet<string> names,
ImmutableHashSet<Type> types,
ImmutableDictionary<Type, Delegate> changedTypes,
int restriction = 1000)
{
_forbiddenNames = names;
_changedTypes = changedTypes;
_forbiddenTypes = types;
_restrictionAmount = restriction;
}
PrintingConfig<TOwner> IPrintingConfig<TOwner>.With<TPropType>(Func<TPropType, string> printer)
{
// if (_changedTypes.TryGetValue(typeof(TPropType), out var oldPrinter))
// {
// var temporaryPrinter = printer;
// printer = t => (string) oldPrinter.DynamicInvoke(temporaryPrinter(t));
// }
var changedTypes = _changedTypes.SetItem(typeof(TPropType), printer);
return new PrintingConfig<TOwner>(_forbiddenNames, _forbiddenTypes, changedTypes);
}
public PrintingConfig<TOwner> WithSequenceAmountRestriction(int restriction) =>
new PrintingConfig<TOwner>(_forbiddenNames, _forbiddenTypes, _changedTypes, restriction);
public PrintingConfig<TOwner> Excluding<TPropType>(Expression<Func<TOwner, TPropType>> memberSelector)
{
if (!(memberSelector.Body is MemberExpression memberExpression &&
memberExpression.Member is PropertyInfo propertyInfo))
throw new ArgumentException("Selector expression is invalid");
var name = propertyInfo.Name;
var names = _forbiddenNames.Add(name);
return new PrintingConfig<TOwner>(names, _forbiddenTypes, _changedTypes);
}
public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>() =>
new PropertyPrintingConfig<TOwner, TPropType>(this);
public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>(
Expression<Func<TOwner, TPropType>> memberSelector) =>
new PropertyPrintingConfig<TOwner, TPropType>(this);
/// <exception cref="ArgumentException">Obj may have some lööps</exception>
public string PrintToString(TOwner obj) => PrintToString(obj, 0);
internal PrintingConfig<TOwner> Excluding<TPropType>()
{
var types = _forbiddenTypes.Add(typeof(TPropType));
return new PrintingConfig<TOwner>(_forbiddenNames, types, _changedTypes);
}
private string PrintToString(object obj, int nestingLevel)
{
if (obj == null)
return "null" + _newLine;
var type = obj.GetType();
if (_changedTypes.ContainsKey(type))
return (string) _changedTypes[type]
.DynamicInvoke(obj) +
_newLine;
if (_forbiddenTypes.Contains(type))
return null;
if (type.IsFinal())
return obj + _newLine;
return PrintActualPropertiesAndFields(obj, nestingLevel, type);
}
private string PrintActualPropertiesAndFields(object obj, int nestingLevel, Type type)
{
var sb = new StringBuilder();
sb.AppendLine(type.Name);
var indentation = new string('\t', nestingLevel + 1);
foreach (var memberInfo in type.GetMembers()
.Where(m => !_forbiddenNames.Contains(m.Name)))
{
if (!memberInfo.TryGetValue(obj, out var value))
continue;
if (_printedObjects.Value.Contains(memberInfo))
throw new ArgumentException("Object has some lööps");
_printedObjects.Value.Add(memberInfo);
var innerPrint = PrintToString(value, nestingLevel + 1);
if (innerPrint != null)
sb.Append(indentation + memberInfo.Name + " = " + innerPrint);
}
if (obj is IEnumerable enumerable)
return sb + PrintEnumerableToString(enumerable, nestingLevel + 2);
return sb.ToString();
}
private string PrintEnumerableToString(IEnumerable enumerable, int nestingLevel)
{
var sb = new StringBuilder();
var indentation = new string('\t', nestingLevel);
sb.AppendLine("Containing:");
var counter = 1;
foreach (var obj in enumerable)
{
sb.Append(indentation + PrintToString(obj, nestingLevel));
if (++counter > _restrictionAmount)
break;
}
return sb.ToString();
}
}
}
|
using UnityEngine;
public class CameraControl : MonoBehaviour
{
[SerializeField]
Transform worldCamera = null;
Camera worldCameraCamera;
float defaultCameraOrthoSize;
const float CAMERA_SPEED = 8f;
const float EDGE_THRESHOLD = 0.1f;
Vector3 UP = new Vector3(1f, 0f, 1f);
Vector3 RIGHT = new Vector3(1f, 0f, -1f);
void Start()
{
worldCameraCamera = worldCamera.GetComponent<Camera>();
defaultCameraOrthoSize = worldCameraCamera.orthographicSize;
}
void Update()
{
var x = Input.GetAxis("Horizontal");
var y = Input.GetAxis("Vertical");
var mousePos = Input.mousePosition;
var mousePosX = mousePos.x;
var mousePosY = mousePos.y;
var leftEdge = Screen.width * EDGE_THRESHOLD;
var rightEdge = Screen.width * (1f - EDGE_THRESHOLD);
var bottomEdge = Screen.height * EDGE_THRESHOLD;
var topEdge = Screen.height * (1f - EDGE_THRESHOLD);
if (mousePosX < leftEdge && mousePosX >= -2f)
x = (mousePosX / Screen.width / EDGE_THRESHOLD - 1f);
else if (mousePosX > rightEdge && mousePosX <= Screen.width + 2f)
x = ((mousePosX / Screen.width) - (1f - EDGE_THRESHOLD)) / EDGE_THRESHOLD;
if (mousePosY < bottomEdge && mousePosY >= -2f)
y = (mousePosY / Screen.height / EDGE_THRESHOLD - 1f);
else if (mousePosY > topEdge && mousePosY <= Screen.height + 2f)
y = ((mousePosY / Screen.height) - (1f - EDGE_THRESHOLD)) / EDGE_THRESHOLD;
var zoomSpeedFactor = worldCameraCamera.orthographicSize / defaultCameraOrthoSize;
var movement = (new Vector3(x, 0f, -x) + new Vector3(y, 0f, y)) * CAMERA_SPEED * zoomSpeedFactor * Time.deltaTime;
worldCamera.Translate(movement, Space.World);
var scroll = Input.mouseScrollDelta.y;
worldCameraCamera.orthographicSize = Mathf.Clamp(worldCameraCamera.orthographicSize - scroll * 0.5f, 3f, 10f);
}
}
|
namespace JiraExtractor
{
public class Reporter
{
public int Id { get; set; }
public string name { get; set; }
public string emailAddress { get; set; }
public string displayName { get; set; }
}
}
|
using System;
namespace OCP.SystemTag
{
/**
* Interface ISystemTagManagerFactory
*
* Factory interface for system tag managers
*
* @package OCP\SystemTag
* @since 9.0.0
*/
public interface ISystemTagManagerFactory
{
/**
* Constructor for the system tag manager factory
*
* @param IServerContainer serverContainer server container
* @since 9.0.0
*/
//ISystemTagManagerFactory(IServerContainer serverContainer);
/**
* creates and returns an instance of the system tag manager
*
* @return ISystemTagManager
* @since 9.0.0
*/
ISystemTagManager getManager() ;
/**
* creates and returns an instance of the system tag object
* mapper
*
* @return ISystemTagObjectMapper
* @since 9.0.0
*/
ISystemTagObjectMapper getObjectMapper() ;
}
}
|
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
/*
* Used for sending tickets bought/booked by a user using email.
*/
namespace CinemaA.Mails
{
public class MailRequest
{
public string ToEmail { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public List<IFormFile> Attachments { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using ENTITY;
//<summary>
//Summary description for StockPostingInfo
//</summary>
namespace ENTITY
{
public class StockPostingInfo
{
private decimal _stockPostingId;
private DateTime _date;
private decimal _voucherTypeId;
private string _voucherNo;
private string _invoiceNo;
private decimal _productId;
private decimal _batchId;
private decimal _unitId;
private decimal _godownId;
private decimal _rackId;
private decimal _againstVoucherTypeId;
private string _againstInvoiceNo;
private string _againstVoucherNo;
private decimal _inwardQty;
private decimal _outwardQty;
private decimal _rate;
private decimal _financialYearId;
private DateTime _extraDate;
private string _extra1;
private string _extra2;
public decimal StockPostingId
{
get { return _stockPostingId; }
set { _stockPostingId = value; }
}
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
public decimal VoucherTypeId
{
get { return _voucherTypeId; }
set { _voucherTypeId = value; }
}
public string VoucherNo
{
get { return _voucherNo; }
set { _voucherNo = value; }
}
public string InvoiceNo
{
get { return _invoiceNo; }
set { _invoiceNo = value; }
}
public decimal ProductId
{
get { return _productId; }
set { _productId = value; }
}
public decimal BatchId
{
get { return _batchId; }
set { _batchId = value; }
}
public decimal UnitId
{
get { return _unitId; }
set { _unitId = value; }
}
public decimal GodownId
{
get { return _godownId; }
set { _godownId = value; }
}
public decimal RackId
{
get { return _rackId; }
set { _rackId = value; }
}
public decimal AgainstVoucherTypeId
{
get { return _againstVoucherTypeId; }
set { _againstVoucherTypeId = value; }
}
public string AgainstInvoiceNo
{
get { return _againstInvoiceNo; }
set { _againstInvoiceNo = value; }
}
public string AgainstVoucherNo
{
get { return _againstVoucherNo; }
set { _againstVoucherNo = value; }
}
public decimal InwardQty
{
get { return _inwardQty; }
set { _inwardQty = value; }
}
public decimal OutwardQty
{
get { return _outwardQty; }
set { _outwardQty = value; }
}
public decimal Rate
{
get { return _rate; }
set { _rate = value; }
}
public decimal FinancialYearId
{
get { return _financialYearId; }
set { _financialYearId = value; }
}
public DateTime ExtraDate
{
get { return _extraDate; }
set { _extraDate = value; }
}
public string Extra1
{
get { return _extra1; }
set { _extra1 = value; }
}
public string Extra2
{
get { return _extra2; }
set { _extra2 = value; }
}
}
}
|
namespace Enrollment.Common.Configuration.ExpressionDescriptors
{
public class MinOperatorDescriptor : SelectorMethodOperatorDescriptorBase
{
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.Services.Installer.Packages
{
public interface IPackageEditor
{
int PackageID { get; set; }
bool IsWizard { get; set; }
void Initialize();
void UpdatePackage();
}
}
|
using UnityEngine;
public class BossIntroState : State
{
public BossIntroState(GameObject enemy, StateType state) : base(enemy, state) { }
private Enemy enemyBehavior;
public override void OnStateEnter()
{
masks = wallsLayer | playerLayer;
enemyBehavior = enemy.GetComponent<Enemy>();
}
public override void UpdateState()
{
if (enemyBehavior.NeedChangeState(enemyBehavior.detectionRange, masks))
{
AudioManager.audioManagerInstance.PlaySFX(enemyBehavior.enemyName + " Appear");
animator.SetTrigger("appear");
enemy.GetComponent<BossHealth>().healthBar.EnableHealthBar();
enemy.GetComponent<FiniteStateMachine>().EnterNextState();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Passenger.Core.Domain;
using System.Threading.Tasks;
namespace Passenger.Infrastructure.Repositories
{
interface IDriverRepository
{
Task<Driver> GetAsync(Guid Id);
Task<IEnumerable<Driver>> GetAllAsync();
Task AddAsync(Driver driver);
Task UpdateAsync(Driver driver);
Task RemoveAsync(Guid id);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// use this to manage collisions
public class Enemy : MonoBehaviour
{
// == public fields ==
public int ScoreValue { get { return scoreValue; } }
// delegate type to use for event
public delegate void EnemyKilled(Enemy enemy);
// create static method to be implemented in the listener
public static EnemyKilled EnemyKilledEvent;
// == private fields ==
[SerializeField] private int scoreValue = 10;
[SerializeField] private AudioClip hitPlayer;
// sounds for getting hit by bullet, spawning
[SerializeField] private AudioClip dieSound;
private SoundController sc;
private MusicPlayer mp;
private SceneController scene;
// == private methods ==
private void Start()
{
sc = SoundController.FindSoundController();
mp = MusicPlayer.FindMusicPlayer();
scene = SceneController.FindSceneController();
}
private void PlaySound(AudioClip clip)
{
if (sc)
{
sc.PlayOneShot(clip);
}
}
private void OnTriggerEnter2D(Collider2D hitEnemy)
{
var bullet = hitEnemy.GetComponent<Bullet>();
var player = hitEnemy.GetComponent<Player>();
if(player)
{
Destroy(player.gameObject);
if(mp)
{
mp.PlayOneShot(hitPlayer);
//turn down volume of sounds to 0
VolumeValueChange.musicVolume=0f;
}
if(scene){
scene.GameOver();
}
}
if(bullet)
{
PlaySound(dieSound);
Destroy(bullet.gameObject);
// publish the event to the system to give the player points
PublishEnemyKilledEvent();
// destroy this game object
Destroy(gameObject);
}
}
private void PublishEnemyKilledEvent()
{
// make sure somebody is listening
if(EnemyKilledEvent != null)
{
EnemyKilledEvent(this);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class hitBoxRender : MonoBehaviour {
SpriteRenderer hitBoxColor;
// Use this for initialization
void Start () {
hitBoxColor = this.GetComponent<SpriteRenderer> ();
hitBoxColor.color = new Color (0.3f, 0.6f, 0.9f, 0.55f);
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using System.Linq;
using Toppler.Core;
using Toppler.Tests.Integration.Fixtures;
using Xunit;
namespace Toppler.Tests.Integration
{
[Collection("RedisServer")]
public class CacheTest
{
public CacheTest(RedisServerFixture redisServer)
{
redisServer.Reset();
}
[Theory]
[Trait(TestConstants.TestCategoryName, TestConstants.IntegrationTestCategory)]
[AutoMoqData]
public void BasicCache(string eventSource, string dimension)
{
var now = DateTime.UtcNow;
var current = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, DateTimeKind.Utc);
foreach (var i in Enumerable.Range(1, 10))
{
Top.Counter.HitAsync(new string[] { eventSource },1L, new string[] { dimension }, current);
current = current.AddHours(-i);
}
var res1 = Top.Ranking.AllAsync(Granularity.Hour, 5, dimension: dimension).Result;
Assert.NotNull(res1);
var res2 = Top.Ranking.AllAsync(Granularity.Hour, 5, dimension: dimension).Result;
var res3 = Top.Ranking.AllAsync(Granularity.Hour, 5, dimension: dimension).Result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaseInstaller.Models
{
public class OptionData
{
public string TrueCare_Url { get; set; }
public string OAuth2_ClientID { get; set; }
public string MSSQL_Server { get; set; }
public string MSSQL_User { get; set; }
public string MSSQL_Password { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace CoreComponents
{
public struct LazyObjectReflect<T>
where T : class
{
T myObject;
object[] myArguments;
public LazyObjectReflect(params object[] values)
{
myObject = null;
myArguments = values;
}
public LazyObjectReflect(IEnumerable<object> values)
{
myObject = null;
myArguments = values.ToArray();
}
public T Object
{
get
{
if(myObject == null)
{
int argsLength = myArguments.Length;
try
{
if(argsLength > 0)
{
myObject = (T)Activator.CreateInstance(typeof(T), myArguments);
}
else
{
myObject = Activator.CreateInstance<T>();
}
}
finally
{
myArguments = null;
}
}
return myObject;
}
}
public bool HasObject
{
get
{
return myObject != null;
}
}
public bool TryGet(out T TheObject)
{
TheObject = myObject;
return TheObject != null;
}
}
}
|
/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace IBApi {
/**
* @class ExecutionFilter
* @brief when requesting executions, a filter can be specified to receive only a subset of them
* @sa Contract, Execution, CommissionReport
*/
public class ExecutionFilter {
public enum Sides { SELL, BUY }
/**
* @brief The API client which placed the order
*/
public int ClientId { get; set; }
/**
* @brief The account to which the order was allocated to
*/
public string AcctCode { get; set; }
/**
* @brief Time from which the executions will be brough yyyymmdd hh:mm:ss
* Only those executions reported after the specified time will be returned.
*/
public string Time { get; set; }
/**
* @brief The instrument's symbol
*/
public string Symbol { get; set; }
/**
* @brief The Contract's security's type (i.e. STK, OPT...)
*/
public string SecType { get; set; }
/**
* @brief The exchange at which the execution was produced
*/
public string Exchange { get; set; }
/**
* @brief The Contract's side (Put or Call).
*/
public string Side { get; set; }
public ExecutionFilter() {
ClientId = 0;
}
public ExecutionFilter(int clientId, String acctCode, String time,
String symbol, String secType, String exchange, String side) {
ClientId = clientId;
AcctCode = acctCode;
Time = time;
Symbol = symbol;
SecType = secType;
Exchange = exchange;
Side = side;
}
public override bool Equals(Object other) {
bool l_bRetVal = false;
if(other == null) {
l_bRetVal = false;
} else if(this == other) {
l_bRetVal = true;
} else {
ExecutionFilter l_theOther = (ExecutionFilter)other;
l_bRetVal = (ClientId == l_theOther.ClientId &&
String.Compare(AcctCode, l_theOther.AcctCode, true) == 0 &&
String.Compare(Time, l_theOther.Time, true) == 0 &&
String.Compare(Symbol, l_theOther.Symbol, true) == 0 &&
String.Compare(SecType, l_theOther.SecType, true) == 0 &&
String.Compare(Exchange, l_theOther.Exchange, true) == 0 &&
String.Compare(Side, l_theOther.Side, true) == 0);
}
return l_bRetVal;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using OC.LINQ;
namespace OC.JQGrid
{
public static class JQGridHelpers
{
public static JQGridResponse<T> GetResponse<T>(JQGridRequest request, IQueryable<T> query)
{
string sidx = request.sidx;
string sord = request.sord;
int pageIndex = request.page;
int pageSize = request.rows;
//
// Count of all persons in DB (is used by the grid pager)
//
int rowsCount = query.Count();
//
// Sort all data
//
IQueryable<T> orderedQuery = query;
if (!string.IsNullOrEmpty(sidx))
{
orderedQuery = query.OrderBy(sidx, sord);
}
//
// Cut into single page (after sorting)
//
var pageData = orderedQuery.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToArray();
//
// Build summary required by the grid
//
JQGridResponse<T> response = new JQGridResponse<T>()
{
total = ((int)Math.Ceiling((double)rowsCount / pageSize)),
page = pageIndex,
records = rowsCount,
rows = pageData
};
return response;
}
}
public static class GridExtensions
{
public static JQGridBuilder JQGrid(this HtmlHelper helper, string id, string url)
{
return new JQGridBuilder(helper, id, url);
}
}
}
|
using JsonFlatFileDataStore;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Hayalpc.Fatura.Panel.External.Resources
{
public class LocService
{
private readonly IStringLocalizer _localizer;
private DataStore store = new DataStore("language.json");
public LocService(IStringLocalizerFactory factory)
{
var type = typeof(SharedResource);
var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
_localizer = factory.Create("SharedResource", assemblyName.Name);
}
public LocalizedString Get(string key)
{
var str = _localizer[key];
if (str.ResourceNotFound == true)
{
var collection = store.GetCollection<LanguageData>();
if (!collection.AsQueryable().Any(t => t.Key == key))
{
var isSuccess = collection.InsertOne(new LanguageData { Key = key, Text = key });
}
}
return str;
}
}
public class LanguageData
{
public string Key { get; set; }
public string Text { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MetaDados;
namespace DAL
{
public static class AgendaDB
{
/// <summary>
/// Insere no dbo.agenda -> Objeto agenda (id_servico, hr_agenda, id_cliente_fk, id_pet_fk)
/// </summary>
/// <param name="agenda"></param>
/// <returns></returns>
public static Response InsertSchedule(Agenda agenda)
{
string insert = "insert into dbo.agenda (id_servico, hr_agenda, id_cliente_fk, id_pet_fk) values (@id_servico, @hr_agenda, @id_cliente_fk, @id_pet_fk)";
Response resp = new Response();
SqlCommand cmd = new SqlCommand(insert, ConnectionString.Connection);
try
{
ConnectionString.Connection.Open();
cmd.Parameters.AddWithValue("@id_servico", agenda.id_servico);
cmd.Parameters.AddWithValue("@hr_agenda", agenda.hr_agenda.ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("@id_cliente_fk", agenda.id_cliente);
cmd.Parameters.AddWithValue("@id_pet_fk", agenda.id_pet);
cmd.ExecuteNonQuery();
ConnectionString.Connection.Close();
resp.Executed = true;
}
//Erro encontrado
catch (Exception e)
{
//Retorna o erro
resp.Executed = false;
resp.ErrorMessage = "Erro";
resp.Exception = e;
}
// Fecha a conexão caso esteja aberta
if (ConnectionString.Connection.State == System.Data.ConnectionState.Open)
{
ConnectionString.Connection.Close();
}
return resp;
}
/// <summary>
/// Seleciona a lista filtrada de todos os agendamentos do dia selecionado de um funcionário
/// </summary>
/// <param name="list_Agenda"></param>
/// <param name="filtro_Inicio"></param>
/// <param name="filtro_Final"></param>
/// <param name="id_funcionario"></param>
/// <returns></returns>
public static Response SelectListSchedule(out List<Agenda> list_Agenda, DateTime filtro_Inicio, DateTime filtro_Final, int id_funcionario)
{
list_Agenda = new List<Agenda>();
string select;
bool tem_filtro = false;
if (filtro_Final == DateTime.MinValue && filtro_Inicio == DateTime.MinValue)
{
select = $"select * from dbo.agenda";
}
else
{
select = $"select * from dbo.agenda where hr_agenda >= @filtro_Inicio and hr_agenda <= @filtro_Final and id_funcionario = @id_funcionario"; //colocar pra usar o id_funcionario como filtro tmb
tem_filtro = true;
}
Response resp = new Response();
SqlCommand cmd = new SqlCommand(select, ConnectionString.Connection);
try
{
ConnectionString.Connection.Open();
if (tem_filtro)
{
cmd.Parameters.AddWithValue("@filtro_Inicio", filtro_Inicio.ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("@filtro_Final", filtro_Final.ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("@id_funcionario", id_funcionario);
}
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
//colocar o que precisa na agenda
Agenda agenda = new Agenda();
agenda.id_agenda = Convert.ToInt32(dr["id_agenda"]);
agenda.id_servico = Convert.ToInt32(dr["id_servico"]);
agenda.hr_agenda = Convert.ToDateTime(dr["hr_agenda"]);
agenda.id_cliente = Convert.ToInt32(dr["id_cliente"]);
agenda.id_pet = Convert.ToInt32(dr["id_pet"]);
agenda.id_funcionario = Convert.ToInt32(dr["id_funcionario"]);
list_Agenda.Add(agenda);
}
dr.Close();
ConnectionString.Connection.Close();
resp.Executed = true;
}
//Erro encontrado
catch (Exception e)
{
//Retorna o erro
resp.Executed = false;
resp.ErrorMessage = "Erro";
resp.Exception = e;
}
// Fecha a conexão caso esteja aberta
if (ConnectionString.Connection.State == System.Data.ConnectionState.Open)
{
ConnectionString.Connection.Close();
}
return resp;
}
/// <summary>
/// Deleta os agendamentos relacionados ao pet deletado
/// </summary>
/// <param name="id_pet"></param>
/// <returns></returns>
public static Response DeleteSchedulePet(int id_pet)
{
string delete = "delete from dbo.agenda where id_pet = @id_pet";
Response resp = new Response();
SqlCommand cmd = new SqlCommand(delete, ConnectionString.Connection);
try
{
ConnectionString.Connection.Open();
cmd.Parameters.AddWithValue("@id_pet", id_pet);
cmd.ExecuteNonQuery();
ConnectionString.Connection.Close();
resp.Executed = true;
}
//Erro encontrado
catch (Exception e)
{
//Retorna o erro
resp.Executed = false;
resp.ErrorMessage = "Erro";
resp.Exception = e;
}
// Fecha a conexão caso esteja aberta
if (ConnectionString.Connection.State == System.Data.ConnectionState.Open)
{
ConnectionString.Connection.Close();
}
return resp;
}
/// <summary>
/// Deleta os agendamentos relacionados ao cliente deletado
/// </summary>
/// <param name="id_cliente"></param>
/// <returns></returns>
public static Response DeleteScheduleClient(int id_cliente)
{
string delete = "delete from dbo.agenda where id_cliente = @id_cliente";
Response resp = new Response();
SqlCommand cmd = new SqlCommand(delete, ConnectionString.Connection);
try
{
ConnectionString.Connection.Open();
cmd.Parameters.AddWithValue("@id_cliente", id_cliente);
cmd.ExecuteNonQuery();
ConnectionString.Connection.Close();
resp.Executed = true;
}
//Erro encontrado
catch (Exception e)
{
//Retorna o erro
resp.Executed = false;
resp.ErrorMessage = "Erro";
resp.Exception = e;
}
// Fecha a conexão caso esteja aberta
if (ConnectionString.Connection.State == System.Data.ConnectionState.Open)
{
ConnectionString.Connection.Close();
}
return resp;
}
/// <summary>
/// Deleta os agendamentos relacionados ao servico deletado
/// </summary>
/// <param name="id_servico"></param>
/// <returns></returns>
public static Response DeleteScheduleService(int id_servico)
{
string delete = "delete from dbo.agenda where id_servico = @id_servico";
Response resp = new Response();
SqlCommand cmd = new SqlCommand(delete, ConnectionString.Connection);
try
{
ConnectionString.Connection.Open();
cmd.Parameters.AddWithValue("@id_servico", id_servico);
cmd.ExecuteNonQuery();
ConnectionString.Connection.Close();
resp.Executed = true;
}
//Erro encontrado
catch (Exception e)
{
//Retorna o erro
resp.Executed = false;
resp.ErrorMessage = "Erro";
resp.Exception = e;
}
// Fecha a conexão caso esteja aberta
if (ConnectionString.Connection.State == System.Data.ConnectionState.Open)
{
ConnectionString.Connection.Close();
}
return resp;
}
}
}
|
/*
* @lc app=leetcode.cn id=1 lang=csharp
*
* [1] 两数之和
*/
// @lc code=start
public class Solution
{
public int[] TwoSum(int[] nums, int target)
{
return Solution2(nums, target);
}
//暴力解法
public int[] Solution1(int[] nums, int target)
{
int[] result = new int[2];
for (int i = 0; i < nums.Length; i++)
{
for (int j = 0; j < nums.Length; j++)
{
if (i == j)
{
continue;
}
if (nums[i] + nums[j] == target)
{
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
public int[] Solution2(int[] nums, int target)
{
int[] result = new int[2];
System.Collections.Generic.Dictionary<int,int> dic = new System.Collections.Generic.Dictionary<int, int>();
for(int i=0;i<nums.Length;i++){
if(dic.ContainsKey(target - nums[i])){
result[0] = dic[target - nums[i]];
result[1] = i;
break;
}
else{
dic[nums[i]] = i;
}
}
return result;
}
}
// @lc code=end
|
using System;
using DG.Tweening;
using UniRx;
using UnityEngine;
using UnityEngine.UI;
public sealed class DebugPanelPresenter : MonoBehaviour
{
[SerializeField] private GameState _gameState;
[SerializeField] private CanvasGroup _canvasGroup;
[SerializeField] private Slider _ballsLeftSlider;
[SerializeField] private Slider _maxActiveBallsSlider;
private readonly ReactiveProperty<bool> _debugVisible = new ReactiveProperty<bool>();
private void Start()
{
_gameState.BallsLeft.TwoWayBindTo(_ballsLeftSlider).AddTo(this);
_gameState.MaxActiveBalls.TwoWayBindTo(_maxActiveBallsSlider).AddTo(this);
_debugVisible.Subscribe(
v =>
{
_canvasGroup.DOFade(v ? 1f : 0f, 0.3f);
_canvasGroup.interactable = v;
})
.AddTo(this);
Observable.EveryUpdate()
.Where(_ => Input.GetKeyUp(KeyCode.D))
.Subscribe(_ => _debugVisible.Value = !_debugVisible.Value)
.AddTo(this);
}
}
public static class UIRxExtensions
{
public static IDisposable TwoWayBindTo(this IReactiveProperty<int> source, Slider slider)
{
// slider.value = source.Value; // since we're accepting a reactive property as param, we could do this
var d1 = slider.OnValueChangedAsObservable()
.Skip(1) // we don't want the initial value of the slider overriding the source value
.SubscribeWithState(source, (f, p) => p.Value = (int) f);
var d2 = source.SubscribeWithState(slider, (i, s) => s.value = i);
return StableCompositeDisposable.Create(d1, d2);
}
} |
namespace Triton.Game.Mapping
{
using ns26;
using System;
[Attribute38("FeignDeath")]
public class FeignDeath : SuperSpell
{
public FeignDeath(IntPtr address) : this(address, "FeignDeath")
{
}
public FeignDeath(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public void OnAction(SpellStateType prevStateType)
{
object[] objArray1 = new object[] { prevStateType };
base.method_8("OnAction", objArray1);
}
public GameObject m_Glow
{
get
{
return base.method_3<GameObject>("m_Glow");
}
}
public float m_Height
{
get
{
return base.method_2<float>("m_Height");
}
}
public GameObject m_RootObject
{
get
{
return base.method_3<GameObject>("m_RootObject");
}
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DataAnnotationsPropertyConvention.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.ComponentModel.DataAnnotations;
using System.Linq;
using CGI.Reflex.Core.Attributes;
using CGI.Reflex.Core.Mappings.UserTypes;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
namespace CGI.Reflex.Core.Mappings.Conventions
{
public class DataAnnotationsPropertyConvention : IPropertyConvention
{
public void Apply(IPropertyInstance instance)
{
if (instance == null) return;
if (instance.Property.PropertyType.IsEnum)
instance.Length(40);
if (instance.Property.MemberInfo.IsDefined(typeof(RequiredAttribute), true))
instance.Not.Nullable();
if (instance.Property.MemberInfo.IsDefined(typeof(UniqueAttribute), true) && instance.Property.MemberInfo.IsDefined(typeof(RequiredAttribute), true))
instance.UniqueKey(string.Format("UNQ_{0}_{1}", instance.EntityType.Name.Pluralize(), instance.Property.MemberInfo.Name));
if (instance.Property.MemberInfo.IsDefined(typeof(IndexedAttribute), true))
instance.Index(string.Format("IDX_{0}_{1}", instance.EntityType.Name.Pluralize(), instance.Property.MemberInfo.Name));
if (instance.Property.MemberInfo.IsDefined(typeof(StringLengthAttribute), true))
{
var stringLenghtAttr =
instance.Property.MemberInfo.GetCustomAttributes(typeof(StringLengthAttribute), true).Cast<StringLengthAttribute>().First();
instance.Length(stringLenghtAttr.MaximumLength);
}
if (instance.Property.MemberInfo.IsDefined(typeof(DataTypeAttribute), true))
{
var dataTypeAttr =
instance.Property.MemberInfo.GetCustomAttributes(typeof(DataTypeAttribute), true).Cast<DataTypeAttribute>().First();
if (dataTypeAttr.DataType == DataType.MultilineText)
{
if (References.ReferencesConfiguration.DatabaseType == DatabaseType.SqlServer2008)
{
instance.CustomSqlType("nvarchar(max)");
instance.CustomType("StringClob");
}
}
}
}
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DAL;
using Models;//5~1^a^s~p_x
public partial class addBlotterInfo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lb_url.Text = "添加日常记事信息";
}
}
DAL.blotter dal = new DAL.blotter();
tb_blotter model = new tb_blotter();
protected void bt_add_Click(object sender, EventArgs e)
{
model.noteDate = tb_day.Text.Trim();
model.noteSort = tb_type.Text.Trim();
model.tContent = tb_content.Text.ToString();
model.tTitle = tb_title.Text;
dal.Add(model);
}
protected void bt_back_Click(object sender, EventArgs e)
{
Response.Redirect("blotterInfo.aspx");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASPPracticas
{
public partial class Receiver : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String text1 = Request.Form.Get("text");
String text2 = Request.Form["text2"];
Response.Write(text1);
Label1.Text = text1;
Label2.Text = text2;
}
}
} |
using Contoso.XPlatform.Flow;
using Contoso.XPlatform.Tests.Helpers;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Contoso.XPlatform.Tests
{
public class FlowManagerTest
{
public FlowManagerTest()
{
serviceProvider = ServiceProviderHelper.GetServiceProvider();
}
#region Fields
private readonly IServiceProvider serviceProvider;
#endregion Fields
[Fact]
public void GetServiceScopeFactory()
{
IServiceScopeFactory serviceScopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
Assert.NotNull(serviceScopeFactory);
}
[Fact]
public void DataFromTheSameScopeMustMatch()
{
IFlowManager? flowManager2 = null;
IServiceScopeFactory serviceScopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
using (IServiceScope scope = serviceScopeFactory.CreateScope())
{
IFlowManager flowManager1 = scope.ServiceProvider.GetRequiredService<IFlowManager>();
flowManager2 = scope.ServiceProvider.GetRequiredService<IFlowManager>();
flowManager1.FlowDataCache.Items["A"] = new List<string> { "First", "Second" };
}
Assert.Equal("Second", ((List<string>)flowManager2.FlowDataCache.Items["A"])[1]);
}
[Fact]
public void DataFromDifferentScopesCanBeDifferent()
{
IFlowManager? flowManager2 = null;
IServiceScopeFactory serviceScopeFactory = serviceProvider.GetRequiredService<IServiceScopeFactory>();
using (IServiceScope scope = serviceScopeFactory.CreateScope())
{
IFlowManager flowManager1 = scope.ServiceProvider.GetRequiredService<IFlowManager>();
flowManager1.FlowDataCache.Items["A"] = new List<string> { "First", "Second" };
}
using (IServiceScope scope = serviceScopeFactory.CreateScope())
{
flowManager2 = scope.ServiceProvider.GetRequiredService<IFlowManager>();
}
Assert.Empty(flowManager2.FlowDataCache.Items);
}
[Fact]
public void CreatingScopedServicesWithoutCreatingAScopeDefaultsToSingleTon()
{
IFlowManager flowManager1 = serviceProvider.GetRequiredService<IFlowManager>();
IFlowManager flowManager2 = serviceProvider.GetRequiredService<IFlowManager>();
flowManager1.FlowDataCache.Items["A"] = new List<string> { "First", "Second" };
Assert.NotEmpty(flowManager2.FlowDataCache.Items);
}
}
}
|
namespace GetLabourManager.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class CasualListProcA : DbMigration
{
public override void Up()
{
CreateStoredProcedure("CasualListProcA",
@"select Code,(e.FirstName+' '+Isnull(e.MiddleName,' ')+' '+e.LastName) as FullName
,e.Telephone1,e.DateJoined, ec.Category from Employees e
inner join EmployeeCategories ec on e.Category = ec.Id"
);
}
public override void Down()
{
DropStoredProcedure("CasualListProcA");
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ServiceModel;
using System.Data.SqlClient;
namespace BLL集团客运综合管理.VehicleManage
{
[ServiceContract]
class FRM_JiaShiYuanXinXi
{
DALPublic.DALMethod myDALMethod = new DALPublic.DALMethod();
#region 查询驾驶员信息
[OperationContract]
public DataSet SelectJiaShiYuanXinXi()
{
SqlParameter[] SqlParameters =
{
new SqlParameter("@TYPE",SqlDbType.NChar)
};
SqlParameters[0].Value = "SelectJiaShiYuanXinXi";
DataTable dt = myDALMethod.QueryDataTable("FRM_JiaShiYuanXinXi", SqlParameters);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
#endregion
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="JenkinsConnector.cs" company="Soloplan GmbH">
// Copyright (c) Soloplan GmbH. All rights reserved.
// Licensed under the MIT License. See License-file in the project root for license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Soloplan.WhatsON.Jenkins
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NLog;
using Soloplan.WhatsON.Composition;
using Soloplan.WhatsON.Configuration;
using Soloplan.WhatsON.Jenkins.Model;
using Soloplan.WhatsON.Model;
[ConnectorType(ConnectorName, ConnectorDisplayName, Description = "Retrieve the current status of a Jenkins project.")]
[ConfigurationItem(RedirectPlugin, typeof(bool), Priority = 400)] // defines use of Display URL API Plugin https://wiki.jenkins.io/display/JENKINS/Display+URL+API+Plugin
[NotificationConfigurationItem(NotificationsVisbility, typeof(ConnectorNotificationConfiguration), Priority = 1600000000)]
public class JenkinsConnector : Connector
{
public const string ConnectorName = "Jenkins";
public const string ConnectorDisplayName = "Jenkins";
/// <summary>
/// The redirect plugin tag.
/// </summary>
public const string RedirectPlugin = "RedirectPlugin";
private const long TicksInMillisecond = 10000;
/// <summary>
/// Logger instance used by this class.
/// </summary>
private static readonly Logger log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType?.ToString());
/// <summary>
/// API class for accessing Jenkins.
/// </summary>
private readonly IJenkinsApi api;
/// <summary>
/// Initializes a new instance of the <see cref="JenkinsConnector"/> class.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <param name="api">API for Jenkins.</param>
public JenkinsConnector(ConnectorConfiguration configuration, IJenkinsApi api)
: base(configuration)
{
this.api = api;
}
private JenkinsStatus PreviousCheckStatus { get; set; }
/// <summary>
/// Checks correctness of self server URL.
/// </summary>
/// <returns>true when fine, false when url is broken.</returns>
public override async Task<bool> CheckServerURL()
{
return await this.IsReachableUrl(this.Address);
}
/// <summary>
/// Checks correctness of self project URL.
/// </summary>
/// <returns>true when fine, false when url is broken.</returns>
public override async Task<bool> CheckProjectURL()
{
return await this.IsReachableUrl(JenkinsApi.UrlHelper.ProjectUrl(this));
}
protected override async Task ExecuteQuery(CancellationToken cancellationToken)
{
await base.ExecuteQuery(cancellationToken);
if (this.PreviousCheckStatus != null && this.CurrentStatus is JenkinsStatus currentStatus && this.Snapshots.Count != 0)
{
if (currentStatus.BuildNumber - this.PreviousCheckStatus.BuildNumber <= 1)
{
return;
}
log.Error($"It was necessary to reevaluate history of jenkins job {this.Configuration.GetConfigurationByKey(Connector.Category)?.Value?.Trim()} / {this.Configuration.Name}, prev build number {this.PreviousCheckStatus.BuildNumber}, current build number {currentStatus.BuildNumber}");
for (var i = currentStatus.BuildNumber - 1; i > this.PreviousCheckStatus.BuildNumber; i--)
{
var build = await this.api.GetJenkinsBuild(this, i, cancellationToken);
if (build != null)
{
this.AddSnapshot(this.CreateStatus(build));
}
}
this.PreviousCheckStatus = this.Snapshots.FirstOrDefault()?.Status as JenkinsStatus;
}
}
protected override async Task<Status> GetCurrentStatus(CancellationToken cancellationToken)
{
var job = await this.api.GetJenkinsJob(this, cancellationToken);
if (job == null)
{
if (await this.CheckServerURL() == false)
{
var status = new Status();
status.ErrorMessage = "Server not available";
status.InvalidBuild = true;
return status;
}
if (await this.CheckProjectURL() == false)
{
var status = new Status();
status.ErrorMessage = "Project not available";
status.InvalidBuild = true;
return status;
}
}
if (job.LastBuild == null)
{
var status = new Status();
status.ErrorMessage = "No builds yet";
status.InvalidBuild = true;
return status;
}
if (job?.LastBuild?.Number == null)
{
var status = this.CreateStatus(job.LastBuild);
status.ErrorMessage = "No build number";
return status;
}
return this.CreateStatus(job.LastBuild);
}
protected override async Task<List<Status>> GetHistory(CancellationToken cancellationToken)
{
var builds = await this.api.GetBuilds(this, cancellationToken, 1, MaxSnapshots + 1);
var statuses = builds.Select(this.CreateStatus).ToList();
this.PreviousCheckStatus = statuses.OfType<JenkinsStatus>().FirstOrDefault();
return statuses;
}
protected override bool ShouldTakeSnapshot(Status status)
{
var shouldTakeSnapshot = base.ShouldTakeSnapshot(status);
if (shouldTakeSnapshot && status is JenkinsStatus jenkinsStatus)
{
this.PreviousCheckStatus = jenkinsStatus;
}
return shouldTakeSnapshot;
}
private static ObservationState GetState(JenkinsBuild build)
{
if (build.Building)
{
return ObservationState.Running;
}
if (string.IsNullOrWhiteSpace(build.Result))
{
return ObservationState.Unknown;
}
if (Enum.TryParse<ObservationState>(build.Result, true, out var state))
{
return state;
}
return ObservationState.Unknown;
}
private Status CreateStatus(JenkinsBuild latestBuild)
{
var newStatus = new JenkinsStatus(GetState(latestBuild))
{
Name = $"{latestBuild.DisplayName} ({TimeSpan.FromMilliseconds(latestBuild.Duration):g})",
Time = DateTimeOffset.FromUnixTimeMilliseconds(latestBuild.Timestamp).UtcDateTime,
Details = latestBuild.Description,
};
newStatus.BuildNumber = latestBuild.Number;
newStatus.DisplayName = latestBuild.DisplayName;
newStatus.Building = latestBuild.Building;
newStatus.Duration = new TimeSpan(latestBuild.Duration * TicksInMillisecond);
newStatus.EstimatedDuration = new TimeSpan(latestBuild.EstimatedDuration * TicksInMillisecond);
newStatus.Culprits = latestBuild.Culprits;
newStatus.Url = JenkinsApi.UrlHelper.BuildUrl(this, newStatus.BuildNumber);
newStatus.ErrorMessage = latestBuild.Result;
newStatus.CommittedToThisBuild = latestBuild.ChangeSets?.SelectMany(p => p.ChangeSetItems)
.Select(p => p.Author)
.GroupBy(p => p.FullName)
.Select(p => p.FirstOrDefault())
.ToList();
return newStatus;
}
}
}
|
using StructureMap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
namespace JoveZhao.Framework.HttpServers
{
public class HttpServer
{
HttpListener listener;
public HttpServer(string host, int port)
{
listener = new HttpListener();
listener.Prefixes.Add(string.Format("http://{0}:{1}/", host, port));
}
volatile bool status = false;
public void Start()
{
ObjectFactory.Configure(x =>
{
x.Scan(p =>
{
p.AssembliesFromApplicationBaseDirectory();
p.AddAllTypesOf<IHttpHandler>().NameBy(q =>
{
var att = q.GetCustomAttributes(typeof(HttpCodeAttribute), true).FirstOrDefault();
return (att as HttpCodeAttribute).Code.ToLower();
});
});
});
Action<HttpListener> act = p =>
{
p.Start();
//Logger.WriteLog(LogType.INFO, "http服务器监听开启");
status = true;
while (status)
{
var httpContext = p.GetContext();
ThreadPool.QueueUserWorkItem(Process, httpContext);
}
};
act.BeginInvoke(listener, null, null);
}
public void Stop()
{
listener.Stop();
status = false;
}
void Process(object context)
{
try
{
var httpContext = context as HttpListenerContext;
IHttpHandler httpHandler = HttpDistributer.Distribute(httpContext);
HttpResponse response = new HttpResponse(httpContext.Response);
HttpRequest request = new HttpRequest(httpContext.Request);
httpHandler.Process(request, response);
response.Flush();
response.Close();
}
catch (Exception ex)
{
Logger.WriteLog(LogType.ERROR, ex.Message, ex);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[SerializeField]
private GameObject poolObj;
[SerializeField, Min(0)]
private int allocateCount;
private Stack<GameObject> poolList = new Stack<GameObject>();
private void Start()
{
Allocate();
}
public void Allocate()
{
for (int i = 0; i < allocateCount; i++)
{
GameObject obj = Instantiate(poolObj, transform);
obj.SetActive(false);
poolList.Push(obj);
}
}
public GameObject Pop()
{
if (poolList.Count != 0)
{
GameObject obj = poolList.Pop();
obj.gameObject.SetActive(true);
return obj;
}
else
{
Debug.Log("스택이 비어있습니다.");
return null;
}
}
public void Push(GameObject _obj)
{
_obj.SetActive(false);
poolList.Push(_obj);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace RSMS
{
public partial class RoleAddDlg : MySubDialogBase
{
public RoleAddDlg()
{
InitializeComponent();
}
private void RoleAddDlg_Load(object sender, EventArgs e)
{
}
public void on_editCallBacAction(object o, myHelper.OPEventArgs ea)
{
editMode = ea.actionName;
int c = ea.param.Length;
string txt = "TB";
for (int i = 0; i < c; i++)
{
Control[] tmp = this.Controls.Find(txt + (i + 1).ToString(), true);
if (tmp.Length > 0)
{
((TextBox)tmp[0]).Text = ea.param[i];
if ((txt + (i + 1).ToString()) == "TB1")
{
((TextBox)tmp[0]).ReadOnly = true;
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (TB1.Text == "")
{
myHelper.emsg("提示", TB1.WaterMarkText + "不能为空!!");
return;
}
else if (TB2.Text == "")
{
myHelper.emsg("提示", TB2.WaterMarkText + "不能为空!!");
return;
}
else
{
switch (editMode)
{
case "edit":
//先查密码是否一样
SqlParameter[] sqlPa = new SqlParameter[1];
sqlPa[0] = new SqlParameter("@userid", this.TB1.Text);
DataTable tmpTab = myHelper.getDataTable("SELECT [cRoleId],[cDescInfo] FROM [Roles] where cRoleId=@userid", sqlPa);
sqlPa = new SqlParameter[2];
sqlPa[0] = new SqlParameter("@des", this.TB2.Text);
sqlPa[1] = new SqlParameter("@userid", TB1.Text);
if (myHelper.update("update Roles set cDescInfo=@des where cRoleId=@userid", sqlPa) > 0)
{
callFun(this);
OpLog("编辑", "成功", "编辑角色" + TB1.Text);
myHelper.smsg("成功", "保存成功!!");
Close();
}
else
{
OpLog( "编辑", "失败", "编辑角色" + TB1.Text);
myHelper.emsg("失败", "保存失败!!");
}
break;
case "insert":
//检查操作员ID
sqlPa = new SqlParameter[1];
sqlPa[0] = new SqlParameter("@userid", this.TB1.Text);
tmpTab = myHelper.getDataTable("SELECT [cRoleId],[cDescInfo] FROM [Roles] where cRoleId=@userid ", sqlPa);
if (tmpTab != null && tmpTab.Rows.Count <= 0)
{
//增加操作
sqlPa = new SqlParameter[2];
sqlPa[0] = new SqlParameter("@des", this.TB2.Text);
sqlPa[1] = new SqlParameter("@userid", TB1.Text);
if (myHelper.update("insert into Roles([cRoleId],[cDescInfo]) values(@userid,@des)", sqlPa) > 0)
{
callFun(this);
OpLog( "增加", "成功", "角色" + TB1.Text);
myHelper.smsg("成功", "保存成功!!");
this.clearContrlText();
}
else
{
OpLog( "增加", "失败", "角色" + TB1.Text);
myHelper.emsg("失败", "保存失败!!");
}
}
else
myHelper.emsg("增加", "ID:" + TB1.Text + "不能重复!!");
break;
}
}
}
public void clearContrlText()
{
foreach (Control tb in this.Controls)
{
if (tb is TextBox)
{
tb.Text = "";
((TextBox)tb).ReadOnly = false;
}
else if (tb is CheckBox)
{
CheckBox tmp = (CheckBox)tb;
tmp.Checked = false;
tmp.CheckState = CheckState.Unchecked;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.