text stringlengths 13 6.01M |
|---|
using System;
using System.ComponentModel.DataAnnotations;
namespace ShoppingGuide.DbModels
{
public class Customers
{
[Key]
public Guid CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Patronimic { get; set; }
//public CustomersAdditional Additional { get; set; }
}
}
|
using ApiGetBooks.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace ApiGetBooks.Test {
public class ManageJsonTest {
public List<EntitysTest> TestarTudoClasseManageJsonTest() {
LoadAllJsonTest();
return ListaDeTestes;
}
string classTestingHere = "ManageJson";
List<EntitysTest> ListaDeTestes = new List<EntitysTest>();
private string methodTestingHere;
private object result;
private enum Result { Ok, Falhou }
public void LoadAllJsonTest() {
methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", "");
List<Books> jsonFile = ManageJson.LoadAllJson();
result = jsonFile.Count == 5 ? result = Result.Ok : result = Result.Falhou;
ListaDeTestes.Add(new EntitysTest() {
Classe = classTestingHere,
Metodo = methodTestingHere,
Resultado = result.ToString()
});
//Próximo metodo
}
}
}
|
using RRExpress.AppCommon;
using RRExpress.AppCommon.Attributes;
namespace RRExpress.ViewModels {
[Regist(InstanceMode.Singleton)]
public class ForgetPwdViewModel : BaseVM {
public override string Title {
get {
return "找回密码";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Hahn.ApplicatonProcess.December2020.Domain.Application.Dto.Model
{
public class AddResponse
{
public string Url { get; set; }
}
}
|
using System;
using System.Collections.Concurrent;
using Azure.Storage.Blobs;
using Rebus.AzureBlobs.Retries;
using Rebus.AzureBlobs.Tests.Extensions;
using Rebus.Retry;
using Rebus.Retry.Simple;
using Rebus.Tests.Contracts.Errors;
using Rebus.Tests.Contracts.Extensions;
using Rebus.Transport.InMem;
namespace Rebus.AzureBlobs.Tests.Retries;
public class AzureBlobsErrorTrackerFactory : IErrorTrackerFactory
{
readonly ConcurrentStack<IDisposable> _disposables = new();
public IErrorTracker Create(RetryStrategySettings settings, IExceptionLogger exceptionLogger)
{
var blobContainerClient = new BlobContainerClient(AzureConfig.ConnectionString, Guid.NewGuid().ToString("n"));
_disposables.Push(blobContainerClient.AsDisposable(c => c.DeleteIfExists()));
return new AzureBlobsErrorTracker(blobContainerClient, settings, new InMemTransport(new(), "queue-name"), exceptionLogger);
}
public void Dispose() => _disposables.Dispose();
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CentricTeam2.Models
{
public class Recognition
{
[Key]
public int EmployeeRecognitionID { get; set; }
[Display(Name = "Core value recognized")]
[Required]
public CoreValue RecognitionId { get; set; }
public enum CoreValue
{
Excellence = 1,
Integrity = 2,
Stewardship = 3,
Innovate = 4,
Balance = 5
}
[Display(Name = "Date recognition given")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime recognizationDate
{
get { return DateTime.Now; }
}
[Required]
[Display(Name = "Person giving the recognition")]
public Guid EmployeeGivingRecog { get; set; }
[ForeignKey("EmployeeGivingRecog")]
public virtual UserDetails Giver { get; set; }
[Display(Name = "Comments")]
public string RecognitionComments { get; set; }
[Display(Name = "Employee Being Recognized")]
public Guid ID { get; set; }
[ForeignKey("ID")]
public virtual UserDetails UserDetail { get; set; }
//public ICollection<EmployeeRecognition> EmployeeRecognitions { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class Hasten : Spell
{
//string m_key = "AAAEA";
// Use this for initialization
void Start()
{
base.Start();
m_type = SpellType.Effect;
}
// Update is called once per frame
void Update()
{
base.Update();
}
public override string Name
{
get { return "Hasten"; }
}
public override Note[] Key
{
get { return new Note[] { Note.A, Note.B, Note.A, Note.E, Note.A, Note.A, Note.B, Note.A }; }
}
public override SpellType Type
{
get{ return SpellType.Effect; }
}
}
|
using AlgorithmProblems.Arrays.ArraysHelper;
using AlgorithmProblems.Sorting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Arrays
{
/// <summary>
/// Given an array, find all the elements which sum up to a particular sum
/// </summary>
public class SumOfTwoNumbersInArray
{
/// <summary>
/// We will sort the array
/// Have a startPointer and endPointer.
/// if(arr[startPointer]+arr[endPointer])>sum, decrement endPointer
/// if(arr[startPointer]+arr[endPointer])<sum, increment startPointer
/// if(arr[startPointer]+arr[endPointer])==sum, add this in list and decrement endPtr and increment startPtr
///
/// Running time = O(nlogn) for sorting
/// Space = O(1)
/// </summary>
/// <param name="arr">array from which the sum needs to be calculated</param>
/// <param name="sum">sum value</param>
/// <returns></returns>
public static List<ArrayPair> GetIndiciesWhenSumIsFoundAlgo1(int[] arr, int sum)
{
List<ArrayPair> ret = new List<ArrayPair>();
// Sort the array
HeapSort<int> hs = new HeapSort<int>(arr);
arr = hs.HeapArray;
int startPointer = 0;
int endPointer = arr.Length-1;
while(startPointer<endPointer)
{
if(arr[startPointer]+arr[endPointer]>sum)
{
endPointer--;
}
else if (arr[startPointer]+arr[endPointer]<sum)
{
startPointer++;
}
else
{
//arr[startPointer]+arr[endPointer]==sum
ret.Add(new ArrayPair(arr[startPointer], arr[endPointer]));
startPointer++;
endPointer--;
}
}
return ret;
}
/// <summary>
/// We can use a dictionary to keep track of all the sum - arr[i]
/// and do a O(1) lookup to check whether that value is present.
///
/// This makes the algo run at O(n)
/// The space complexity is O(n)
///
/// </summary>
/// <param name="arr">array from which the sum needs to be calculated</param>
/// <param name="sum">sum value</param>
/// <returns>list of array value pairs, where addition of each pair yields sum</returns>
public static List<ArrayPair> GetIndiciesWhenSumIsFoundAlgo2(int[] arr, int sum)
{
List<ArrayPair> ret = new List<ArrayPair>();
Dictionary<int,bool> dict = new Dictionary<int,bool>();
for (int i = 0; i < arr.Length;i++ )
{
if(dict.ContainsKey(sum - arr[i]))
{
ret.Add(new ArrayPair(sum - arr[i], arr[i]));
}
else
{
dict[arr[i]] = true;
}
}
return ret;
}
/// <summary>
/// Instead of using a dictionary(as shown in algo2), we can use an int[] if we know the range of numbers in the arr.
/// each bit in the int[] will tell us whether this number was present in the array or not.
/// So the space requirement will drastically reduce to Range/32 ints in the array, since each int can have 32 bits.
///
/// This will get us the run time of O(n) and almost constant space requirement
/// </summary>
/// <param name="arr">array from which the sum needs to be calculated</param>
/// <param name="sum">sum value</param>
/// <returns>list of array value pairs, where addition of each pair yields sum</returns>
public static List<ArrayPair> GetIndiciesWhenSumIsFoundAlgo3(int[] arr, int sum)
{
List<ArrayPair> ret = new List<ArrayPair>();
// We need to find the Range. to do that we need to find the max and min
int minVal = int.MaxValue;
int maxVal = int.MinValue;
for (int i = 0; i < arr.Length; i++ )
{
if(arr[i]>maxVal)
{
// get the max value
maxVal = arr[i];
}
if (arr[i] < minVal)
{
// get the min Value
minVal = arr[i];
}
}
//So the number of bits needed are equal to Range
int Range = maxVal - minVal + 1;//overflow can happen here
int[] bitDictionary = new int[(int)Math.Ceiling((double)Range / (sizeof(int)*8))];
for (int i = 0; i < arr.Length; i++)
{
if (IsValuePresent(bitDictionary, sum - arr[i]))
{
ret.Add(new ArrayPair(sum - arr[i], arr[i]));
}
else
{
SetABit(bitDictionary,arr[i]);
}
}
return ret;
}
/// <summary>
/// This method will find the bit corresponding to value and return whether the bit is set or not
/// </summary>
/// <param name="bitDictionary"></param>
/// <param name="value"></param>
/// <returns></returns>
private static bool IsValuePresent(int[] bitDictionary, int value)
{
int arrayIndex = value / (sizeof(int) * 8);
int bitIndex = value % (sizeof(int) * 8);
int flag = bitDictionary[arrayIndex] & (1 << bitIndex);
return !(flag == 0);
}
/// <summary>
/// This method sets the bit corresponding to value as 1 in the bitDictionary
/// </summary>
/// <param name="bitDictionary"></param>
/// <param name="value"></param>
/// <returns></returns>
private static void SetABit(int[] bitDictionary, int value)
{
int arrayIndex = value / (sizeof(int) * 8);
int bitIndex = value % (sizeof(int) * 8);
bitDictionary[arrayIndex] |= (1 << bitIndex);
}
public static void TestSumOfTwoNumbersInArray()
{
int[] arr = new int[]{2,5,2,6,3,5,6,2,5,1,0,9,3};
Console.WriteLine("The input array is as shown below");
ArrayHelper.PrintArray(arr);
List<ArrayPair> list = GetIndiciesWhenSumIsFoundAlgo1(arr, 5);
Console.WriteLine("Algo1: The array value pairs which sum upto 5 are as shown below");
PrintArrayValuePairs(list);
list = GetIndiciesWhenSumIsFoundAlgo2(arr, 5);
Console.WriteLine("Algo2: The array value pairs which sum upto 5 are as shown below");
PrintArrayValuePairs(list);
list = GetIndiciesWhenSumIsFoundAlgo3(arr, 5);
Console.WriteLine("Algo3: The array value pairs which sum upto 5 are as shown below");
PrintArrayValuePairs(list);
list = GetIndiciesWhenSumIsFoundAlgo1(arr, 3);
Console.WriteLine("Algo1: The array value pairs which sum upto 3 are as shown below");
PrintArrayValuePairs(list);
list = GetIndiciesWhenSumIsFoundAlgo2(arr, 3);
Console.WriteLine("Algo2: The array value pairs which sum upto 3 are as shown below");
PrintArrayValuePairs(list);
list = GetIndiciesWhenSumIsFoundAlgo3(arr, 3);
Console.WriteLine("Algo3: The array value pairs which sum upto 3 are as shown below");
PrintArrayValuePairs(list);
}
private static void PrintArrayValuePairs(List<ArrayPair> list)
{
foreach(ArrayPair arrIndexPair in list)
{
Console.WriteLine(arrIndexPair.ToString());
}
}
}
/// <summary>
/// this class object will be used to represent a pair of 2 element in the array
/// </summary>
public class ArrayPair
{
public ArrayPair (int element1, int element2)
{
Element1 = element1;
Element2 = element2;
}
public int Element1 { get; set; }
public int Element2 { get; set; }
public override string ToString()
{
return string.Format("{0},{1}",Element1,Element2);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class QueryString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string uname = txtUname.Text;
string pwd = txtPwd.Text;
Response.Redirect("QueryStringDestination.aspx?uid="+uname+"&pwd="+pwd);
}
} |
namespace Vapotage.Models
{
public class Accumulateur
{
public int Id { get; set; }
public string Marque { get; set; }
public int? DechargeMax { get; set; }
public int Capacite { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp33
{
class Forvet:Futbolcu
{
public int Bitiricilik { get; set; }
public int IlkDokunus { get; set; }
public int Kafa { get; set; }
public int OzelYetenek { get; set; }
public int SogukKanlilik { get; set; }
public Forvet(string AdSoyad,int FormaNo):base(AdSoyad,FormaNo)
{
Bitiricilik = RastgeleSayiUret.Uret(70, 100);
IlkDokunus = RastgeleSayiUret.Uret(70, 100);
Kafa = RastgeleSayiUret.Uret(70, 100);
OzelYetenek = RastgeleSayiUret.Uret(70, 100);
SogukKanlilik = RastgeleSayiUret.Uret(70, 100);
}
public override bool PasVer()
{
double PasSkor;
PasSkor = Pas * 0.3 + Yetenek * 0.2 + OzelYetenek * 0.2 + Dayaniklik * 0.1 + DogalForm * 0.1 + Sans * 0.1;
if (PasSkor > 60)
return true;
else
return false;
}
public override bool GolVurusu()
{
double GolSkor;
GolSkor = Yetenek * 0.2 + OzelYetenek * 0.2 + Sut * 0.1 + Kafa * 0.1 + IlkDokunus * 0.1 + Bitiricilik * 0.1 + SogukKanlilik * 0.1 + Kararlilik * 0.1 + DogalForm * 0.1 + Sans * 0.1;
if (GolSkor > 70)
return true;
else
return false;
}
}
}
|
using LibraryCoder.Numerics;
using Windows.UI.Xaml.Controls;
/*
* Verify that the LibraryNumerics LibNum.TruncateFloatingPoint() method overloads are working correctly..
*/
namespace SampleUWP.ConsoleCodeSamples
{
internal partial class Samples
{
internal static void Sample08_Test_Truncate_Methods(TextBlock outputBlock)
{
outputBlock.Text = "\nSample08_Test_Truncate_Methods:\n";
outputBlock.Text += "\nVerify that the LibraryNumerics LibNum.TruncateFloatingPoint() method overloads are working correctly.\n";
outputBlock.Text += "\nDecimal Overload Test: *************************************************************************\n";
decimal valDecimal = 359.99999999999999999999999969m;
int digits = 6;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
digits = 0;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = -359.999999995m;
digits = 10;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
digits = 9;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
digits = 8;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = 3.5999999999999999999999999997m;
digits = 6;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = -3.5999999999999999999999999997m; ;
digits = 8;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = 0.0249999999999999999999996133m; ;
digits = 8;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = -0.0249999999999999999999996133m;
digits = 6;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = 0.1499999999999999999999999978m;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = -0.1499999999999999999999999978m;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = 123456.5m;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]";
valDecimal = -123456.5m;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDecimal + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDecimal, digits) + "]\n";
outputBlock.Text += "\nDouble Overload Test: *************************************************************************\n";
double valDouble = 359.99999999969d;
digits = 6;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
digits = 0;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = -359.999999995d;
digits = 10;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
digits = 9;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
digits = 8;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = 3.5999999999997d;
digits = 6;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = -3.5999999999997d; ;
digits = 8;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = 0.024999999996133d; ;
digits = 8;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = -0.024999999996133d;
digits = 6;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = 0.14999999999978d;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = -0.14999999999978d;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = 123456.5d;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]";
valDouble = -123456.5d;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valDouble + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valDouble, digits) + "]\n";
outputBlock.Text += "\nFloat Overload Test: *************************************************************************\n";
float valFloat = 359.9969f;
digits = 3;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
digits = 0;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = -359.9969f;
digits = 10;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
digits = 3;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = 3.599997f;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = -3.599997f; ;
digits = 3;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = 0.02499613f; ;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = -0.02499613f;
digits = 6;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = 0.1499978f;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = -0.1499978f;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = 123456.5f;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]";
valFloat = -123456.5f;
digits = 4;
outputBlock.Text += "\n TruncateFloatingPoint(" + valFloat + ", " + digits + ") = [" + LibNum.TruncateFloatingPoint(valFloat, digits) + "]\n";
}
}
}
|
using System;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("NUnitTestStack")]
namespace Stack
{
internal class Item<T> : IDisposable
{
private int _Index { get; set; }
public int Index
{
get
{
return _Index;
}
set
{
if (Prev != null) _Index = Prev.Index + 1;
else _Index = 0;
}
}
public T Object { get; set; }
internal bool IsFilled;
public Item<T> Prev { get; set; }
internal Item(Item<T> head)
{
Object = default;
Prev = head;
IsFilled = false;
Index = 0;
}
internal Item(Item<T> head, T obj)
{
Object = obj;
Prev = head;
IsFilled = true;
Index = 0;
}
public void Dispose()
{
Object = default;
Prev = null;
IsFilled = default;
_Index = default;
}
}
}
|
namespace EFTeste.Entidades.Entidades
{
public class ProfessorClasse : Pessoa
{
public ProfessorClasse()
{
//Alunos = new List<Aluno>();
Idade = 0;
Sexo = Sexo.Masculino;
}
public int Id { get; set; }
public int TurmaId { get; set; }
public virtual Turma Turma { get; set; }
public int CoordenadorId { get; set; }
public virtual Coordenador Coordenador { get; set; }
//public virtual ICollection<Aluno> Alunos { get; set; }
}
}
|
using Xamarin.Forms;
namespace RRExpress.Views {
public partial class EditMyInfoView : ContentPage {
public EditMyInfoView() {
InitializeComponent();
}
}
}
|
namespace DataLightning.Core.Tests.Unit.Operators
{
public class TestEntityC
{
public int KeyC { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CardController : MonoBehaviour
{
public static CardController instance = null;
[SerializeField]
private GameObject CardPrefab;
[SerializeField]
private Transform CardInstantiatePos;
[SerializeField]
private Transform CardParent;
[SerializeField]GameObject[] card;
public int CardCount;
private int upgradeCard;
[SerializeField]
Sprite[] cardSprites;
[SerializeField]
Sprite[] cardUpSprites;
void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
Destroy(gameObject);
card = new GameObject[10];
}
private void Start()
{
//StartCoroutine(DrawCardCoroutine());
}
private IEnumerator DrawCardCoroutine()
{
while (!GameManager.Instance.isGameInPlay)
yield return null;
while(GameManager.Instance.isGameInPlay)
{
DrawCard();
yield return new WaitForSeconds(2.0f);
}
}
public void DrawCard()
{
if (CardCount < 10)
{
card[CardCount] = Instantiate(CardPrefab, CardInstantiatePos.position, Quaternion.Euler(new Vector3(0, 180, 0)), CardParent);
card[CardCount].GetComponent<Card>().CardMoving(CardCount);
int random = Random.Range(0, 100);
int ranType = 0;
if (random < 19)
ranType = 0;
else if (random < 29)
ranType = 1;
else if (random < 48)
ranType = 2;
else if (random < 67)
ranType = 3;
else if (random < 72)
ranType = 4;
else if (random < 91)
ranType = 5;
else
ranType = 6;
card[CardCount].GetComponent<Card>().cardType = ranType;
card[CardCount].GetComponent<Image>().sprite = cardSprites[card[CardCount].GetComponent<Card>().cardType];
CardCount++;
if (CardCount >= 2)
{
for (int i = 2; i < CardCount; i++)
{
if (card[i-2].GetComponent<Card>().isUpgrade) continue;
if ((card[i].GetComponent<Card>().cardType == card[i - 1].GetComponent<Card>().cardType && card[i].GetComponent<Card>().cardType == card[i - 2].GetComponent<Card>().cardType))
{
upgradeCard = i;
StartCoroutine(CardUpgrade());
}
}
}
}
}
public void DeleteCard(int cardNum)
{
for (int i = cardNum; i < CardCount - 1; i++)
{
card[i] = card[i + 1];
card[i].GetComponent<Card>().CardMoving(i);
}
CardCount--;
if (CardCount >= 2)
{
for (int i = 2; i < CardCount; i++)
{
if (card[i].GetComponent<Card>().cardType == card[i - 1].GetComponent<Card>().cardType && card[i].GetComponent<Card>().cardType == card[i - 2].GetComponent<Card>().cardType)
{
upgradeCard = i;
StartCoroutine(CardUpgrade());
break;
}
}
}
}
IEnumerator CardUpgrade()
{
card[upgradeCard].GetComponent<Card>().CardUpgrade(card[upgradeCard - 2]);
card[upgradeCard-1].GetComponent<Card>().CardUpgrade(card[upgradeCard - 2]);
card[upgradeCard-2].GetComponent<Card>().isUpgrade = true;
SoundManager.Instance.PlaySound("Card_Upgrade");
yield return new WaitForSeconds(.3f);
for (int i = upgradeCard - 1; i < CardCount - 2; i++)
{
card[i] = card[i + 2];
card[i].GetComponent<Card>().CardMoving(i);
}
card[upgradeCard - 2].GetComponent<Image>().sprite = cardUpSprites[card[upgradeCard - 2].GetComponent<Card>().cardType];
CardCount -= 2;
}
}
|
using UnityEngine;
public interface IInputService
{
bool IsHolding();
Vector3 HoldingPosition();
bool IsStartedHolding();
float HoldingTime();
bool IsReleased();
void Update(float delta);
} |
namespace ProjetctTiGr13.Domain.FicheComponent
{
public class PersonalityAndBackground
{
public string TraitDePersonnalite { get; set; }
public string Ideaux { get; set; }
public string Liens { get; set; }
public string Defauts { get; set; }
public int Alignement { get; set; }
public string Historique { get; set; }
public int Age { get; set; }
public string Apparence { get; set; }
public string AllieEtOrganisation { get; set; }
public string Background { get; set; }
public PersonalityAndBackground()
{
TraitDePersonnalite = "";
Ideaux = "";
Liens = "";
Defauts = "";
Historique = "";
Age = 0;
Apparence = "";
AllieEtOrganisation = "";
Background = "";
Alignement = 5;
}
}
} |
using System;
using System.Collections.Generic;
using Uintra.Core.Activity.Entities;
namespace Uintra.Features.Social
{
public interface ISocialBase : IIntranetActivity
{
int? UmbracoCreatorId { get; set; }
Guid CreatorId { get; set; }
IEnumerable<int> MediaIds { get; set; }
DateTime PublishDate { get; set; }
}
}
|
using Puppeteer.Core;
public class AIEnoughMushroomsSensor : PuppeteerExecutableSensor
{
public override void Initialise(PuppeteerAgent _owner)
{
m_Agent = _owner;
MushroomManager.Instance.OnMushroomCountChanged += SetHasEnoughMushrooms;
var sensorDesc = PuppeteerManager.Instance.GetSensorDescription(DescriptionGUID);
m_ManagedWorldState = sensorDesc.ManagedWorldState;
}
private void SetHasEnoughMushrooms(int _desiredCount, int _hasCount)
{
m_Agent.AddOrUpdateWorkingMemory(m_ManagedWorldState, _hasCount >= _desiredCount);
m_Agent.AddOrUpdateWorkingMemory(m_NeedForMushroomKey, 1.0f - (float)_hasCount / _desiredCount);
}
private const string m_NeedForMushroomKey = "NeedForMushrooms";
private PuppeteerAgent m_Agent;
private string m_ManagedWorldState;
} |
using System;
using System.Collections.Generic;
using System.Linq;
using WritingPlatformCore.Interfaces;
namespace WritingPlatformCore.Entities.CabinetAggregate
{
public class Cabinet: BaseEntity, IAggregateRoot
{
public string OwnerId { get; private set; }
private readonly List<CabinetItem> _items = new List<CabinetItem>();
public IReadOnlyCollection<CabinetItem> Items => _items.AsReadOnly();
public Cabinet(string ownerId)
{
OwnerId = ownerId;
}
public void AddItem(int catalogItemId, bool modify=false)
{
if (!modify && !Items.Any(q => q.CatalogItemId == catalogItemId))
{
_items.Add(new CabinetItem(catalogItemId));
return;
}
var existingItem = Items.FirstOrDefault(q => q.CatalogItemId == catalogItemId);
existingItem.SetIsModify();
}
public void SetNewOwnerId(string ownerId)
{
OwnerId = ownerId;
}
public void RemoveEmptyItems()
{
_items.RemoveAll(i => i.DateTimeCreate == i.DateTimeModify);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OE.Service.Commands.Publish
{
public class RollBackAppCommand : ICommand
{
/// <summary>
/// App version
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public override int Execute(string[] args)
{
if (args == null || args.Count() != 3)
{
Msg = "为三个参数!";
return -1;
}
string appname = args[1];
string toappversion = args[2];
string appdir = Configrations.Config.GetAppDir(appname, "");
string appbackupdir = Configrations.Config.GetAppBackup(appname, Configrations.Config.GetAppDefaultBackupDir(appname));
if (string.IsNullOrEmpty(appdir))
{
Msg = "应用不存在!";
return -1;
}
if (!System.IO.Directory.Exists(appbackupdir))
{
Msg = "备份文件不存在!";
return -1;
}
string toversiondir = "";
if (toappversion == "-1")
{
//回退到上一个备份版本
toversiondir = GetAppAllBackupTag(appbackupdir, appname).LastOrDefault();
}
else
{
//回退到特定版本 需要有版本号
var v_vs = GetAppAllBackupVersion(appbackupdir, appname).Where(x => x.Item1 == toappversion).ToList().OrderBy(x => x.Item2).FirstOrDefault();
if (v_vs != null)
{
toversiondir = v_vs.Item3;
}
}
if (string.IsNullOrEmpty(toversiondir))
{
Msg = "回退版本不存在!";
return -1;
}
int copyfiles = Utils.Utils.CopyDir(toversiondir, appdir);
string versionfilename = System.IO.Path.Combine(toversiondir, Configrations.ConfigConst.AppVersionFileName);
string newtoversion = "";
if (System.IO.File.Exists(versionfilename))
{
newtoversion = System.IO.File.ReadAllText(versionfilename);
}
Msg = "回退成功,回退到备份" + toversiondir +";版本号:"+newtoversion+ ";复制文件数:" + copyfiles;
return 1;
}
private List<string> GetAppAllBackupTag(string backupdir, string appname)
{
List<string> vs = new List<string>();
System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(backupdir);
if (dirinfo.Exists)
{
foreach (var a in dirinfo.GetDirectories(appname + "_*"))
{
vs.Add(a.FullName);
}
}
vs.Sort();
return vs;
}
private List<Tuple<string, string, string>> GetAppAllBackupVersion(string backupdir, string appname)
{
List<Tuple<string, string, string>> vs = new List<Tuple<string, string, string>>();
System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(backupdir);
if (dirinfo.Exists)
{
foreach (var a in dirinfo.GetDirectories(appname + "_*"))
{
string versionfile = a.FullName.TrimEnd('\\') + "\\" + Configrations.ConfigConst.AppVersionFileName;
if (!System.IO.File.Exists(versionfile))
continue;
string version = System.IO.File.ReadAllText(a.FullName.TrimEnd('\\') + "\\" + Configrations.ConfigConst.AppVersionFileName, Encoding.UTF8);
if (string.IsNullOrEmpty(version))
continue;
vs.Add(new Tuple<string, string, string>(version, a.Name.Replace(appname + "_", ""), a.FullName));
}
}
return vs;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace RcSimulator
{
class Serial
{
static private Serial _singleton;
private string lastPort;
private SerialPort mySerialPort;
MemoryStream readAllBytes = new MemoryStream(Form1.CONFIG_RESPONSE_SIZE);
static public Serial Instance
{
get {
if (_singleton == null)
{
_singleton = new Serial();
}
return _singleton;
}
}
public bool IsConnected {
get
{
return (mySerialPort != null);
}
}
public void ReadStream(MemoryStream readAllBytes, int v)
{
readAllBytes.SetLength(0);
for (int i = 0; i < v; i++)
{
readAllBytes.WriteByte((byte)mySerialPort.ReadByte());
}
}
private void MySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//AppendTextBox(mySerialPort.ReadExisting());
//ExecResponse();
}
public byte[] SendStream(MemoryStream ms, int responseSize)
{
if (mySerialPort == null)
return null;
try
{
for (int i = 0; i < 3; i++)
{
byte[] buffer = ms.GetBuffer();
mySerialPort.Write(buffer, 0, (int)ms.Length);
byte[] response = new byte[responseSize];
try
{
mySerialPort.Read(response, 0, responseSize);
return response;
}
catch(TimeoutException timeout)
{
//
}
}
}
catch (IOException ec)
{
Disconnect();
if (lastPort != null)
Connect(lastPort);
}
return null;
}
internal void ReadConfig()
{
MemoryStream ms = new MemoryStream();
ms.WriteByte((byte)'!');
ms.WriteByte((byte)'2'); // 2- read settings
ms.WriteByte((byte)'>');
RCSettingsHelper.ReadFromBuffer(SendStream(ms, Form1.CONFIG_RESPONSE_SIZE));
}
internal void RawMoveServo(RCSinkMode sink, byte value)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte((byte)'!');
ms.WriteByte((byte)'1');
ms.WriteByte((byte)sink); // servo #id
ms.WriteByte((byte)value); // value
ms.WriteByte((byte)'>');
Serial.Instance.SendStream(ms, 0);
}
public void Connect(string portName)
{
try
{
lastPort = portName;
SerialPort lSerialPort = new SerialPort();
lSerialPort.DataReceived += DataReceived;
lSerialPort.PortName = portName;
lSerialPort.BaudRate = 115200;
lSerialPort.ReadTimeout = 1500;
lSerialPort.Open();
mySerialPort = lSerialPort;
lSerialPort.ReadExisting();
}
catch (Exception ex)
{
}
}
private void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
}
public void Disconnect()
{
SerialPort lSerialPort = mySerialPort;
mySerialPort = null;
if (lSerialPort != null)
{
lSerialPort.Close();
}
}
internal void WriteConfig(RCSoftwareSettings instance)
{
MemoryStream ms = new MemoryStream();
ms.WriteByte((byte)'!');
ms.WriteByte((byte)'3'); // 3- write settings
RCSettingsHelper.WriteToBuffer(ms, instance);
ms.WriteByte((byte)'>');
byte[] rsp = SendStream(ms, 3);
}
}
}
|
using System;
using System.Windows.Forms;
namespace UNO__ {
public partial class ColorLIst : Form {
public ColorLIst() {
InitializeComponent();
}
public delegate void ReturnColorDelegate(string ret);
public event ReturnColorDelegate ReturnColorEvent;
private void button1_Click(object sender, EventArgs e) {
if (radioButton1.Checked) ReturnColorEvent("red");
if (radioButton2.Checked) ReturnColorEvent("yellow");
if (radioButton3.Checked) ReturnColorEvent("blue");
if (radioButton4.Checked) ReturnColorEvent("green");
this.Close();
}
private void ColorLIst_FormClosing(object sender, FormClosingEventArgs e) {
if (!radioButton1.Checked && !radioButton2.Checked
&& !radioButton3.Checked && !radioButton4.Checked) {
MessageBox.Show("请选择一种颜色", "提示");
e.Cancel = true;
}
}
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
namespace ProyectoSCA_Navigation.Clases
{
public class Afiliado : Persona
{
String telefonoEmpresa_;
public String TelefonoEmpresa
{
get { return telefonoEmpresa_; }
set { telefonoEmpresa_ = value; }
}
String nombreEmpresa_;
public String NombreEmpresa
{
get { return nombreEmpresa_; }
set { nombreEmpresa_ = value; }
}
String direccionEmpresa_;
public String DireccionEmpresa
{
get { return direccionEmpresa_; }
set { direccionEmpresa_ = value; }
}
String departamentoEmpresa_;
public String DepartamentoEmpresa
{
get { return departamentoEmpresa_; }
set { departamentoEmpresa_ = value; }
}
String tiempoLaboracionEmpresa_;
public String TiempoLaboracionEmpresa
{
get { return tiempoLaboracionEmpresa_; }
set { tiempoLaboracionEmpresa_ = value; }
}
int IDAfiliado_;
public int IDAfiliado
{
get { return this.IDAfiliado_; }
set { this.IDAfiliado_ = value; }
}
String lugarDeNacimiento_;
public String lugarDeNacimiento
{
get { return this.lugarDeNacimiento_; }
set { this.lugarDeNacimiento_ = value; }
}
String fechaIngresoCooperativa_;
public String fechaIngresoCooperativa
{
get { return this.fechaIngresoCooperativa_; }
set { this.fechaIngresoCooperativa_ = value; }
}
String estadoAfiliado_;
public String EstadoAfiliado
{
get { return this.estadoAfiliado_;}
set { this.estadoAfiliado_ = value; }
}
Usuario usuario_ = new Usuario();
public String Password
{
get { return this.usuario_.Password; }
set { this.usuario_.Password = value; }
}
public String CorreoElectronico
{
get { return usuario_.correoElectronico; }
set { this.usuario_.correoElectronico = value; }
}
Cuenta c = new Cuenta();
public int certificadoCuenta
{
get { return this.c.num_certificado; }
set { this.c.num_certificado = value; }
}
public void retirar(float monto)
{
c.retirarDeCuenta(monto);
}
public void depositar(float monto)
{
c.depositarEnCuenta(monto);
}
public float consultarMontoDeCuenta()
{
return c.saldo;
}
Ocupacion ocupacion_ = new Ocupacion();
public String Ocupacion
{
get { return ocupacion_.ocupacion; }
set { ocupacion_.ocupacion = value; }
}
List<BeneficiarioNormal> beneficiariosNormales_;
public List<BeneficiarioNormal> bensNormales
{
get { return beneficiariosNormales_; }
set { beneficiariosNormales_ = value; }
}
Beneficiario beneficiarioCont_ = new BeneficiarioContingencia();
public Beneficiario BeneficiarioCont
{
get { return beneficiarioCont_; }
set { beneficiarioCont_ = value; }
}
public void verAportacionesObligatorias()
{
//en este metodo el afiliado puede ver que aportaciones ha pagado
//y cuales le quedan por pagar
}
}
}
|
using BLL.DLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Controls_Records_RecordSearch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Access.IsAdmin() && !Access.UserSearchInRecords(Library.GetActiveLibrary()))
Page.Response.Redirect("~/login.aspx");
}
protected void Search()
{
Page.Response.Redirect("RecordsList.aspx?Keyword=" + TXT_Keyword.Text);
}
protected void BTN_Search_Click(object sender, EventArgs e)
{
Search();
}
protected void TXT_Keyword_TextChanged(object sender, EventArgs e)
{
Search();
}
} |
using OrdersViewer.Model;
using OrdersViewer.Service;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
namespace OrdersViewer.ViewModel
{
/// <summary>
/// Модель представления сотрудника
/// </summary>
public class EmployeeWindowViewModel : INotifyPropertyChanged
{
/// <summary>
/// Сотрудник
/// </summary>
private Employee employeeTmp;
/// <summary>
/// Идентификатор сотрудника
/// </summary>
private int id;
/// <summary>
/// Обработчик сохранения сотрудника
/// </summary>
private void SaveEmployee()
{
employeeTmp.Id = id;
employeeTmp.Name = Name;
employeeTmp.Surname = Surname;
employeeTmp.Middlename = MiddleName;
employeeTmp.DateOfBirth = DateOfBirth;
employeeTmp.SexId = SelectedSex.Id;
employeeTmp.SubdivisionId = SelecedSubdivision.Id;
OnPropertyChanged("CanClose");
}
/// <summary>
/// Имя
/// </summary>
public string Name { get; set; }
/// <summary>
/// Фамилия
/// </summary>
public string Surname { get; set; }
/// <summary>
/// Отчество
/// </summary>
public string MiddleName { get; set; }
/// <summary>
/// Дата рождения
/// </summary>
public DateTime DateOfBirth { get; set; }
/// <summary>
/// Коллекция подразделений
/// </summary>
public ObservableCollection<Subdivision> Subdivisions { get; set; }
/// <summary>
/// Половая принадлежность
/// </summary>
public ObservableCollection<Sex> Sexes { get; set; }
/// <summary>
/// Выбранное подразделение
/// </summary>
public Subdivision SelecedSubdivision { get; set; }
/// <summary>
/// Выбранный пол
/// </summary>
public Sex SelectedSex { get; set; }
/// <summary>
/// Возвращает сотрудника
/// </summary>
/// <returns></returns>
public Employee GetEmployee()
{
return employeeTmp;
}
/// <summary>
/// Команда сохранения сотрудника
/// </summary>
public ICommand SaveEmployeeCommand
{
get { return new DelegateCommand(SaveEmployee); }
}
public EmployeeWindowViewModel(Employee employee)
{
employeeTmp = new Employee();
id = employee.Id;
Name = employee.Name;
Surname = employee.Surname;
MiddleName = employee.Middlename;
DateOfBirth = employee.DateOfBirth;
}
// реализация обработчиков INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
|
namespace CustomerApp.Dtos
{
using System.Runtime.Serialization;
[DataContract(Name="CustomerDetail")]
public class CustomerDetailDto
{
[DataMember]
public int Id { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Status { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Created { get; set; }
[DataMember(EmitDefaultValue = false)]
public string LastName { get; set; }
[DataMember(EmitDefaultValue = false)]
public string FirstName { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Email { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Address { get; set; }
}
} |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace GradConnect.Models
{
public class Article : Post
{
public Article()
{
Comments = new List<Comment>();
}
public string Link { get; set; }
//Navigational props
public IEnumerable<Comment> Comments { get; set; }
}
} |
// The MIT License (MIT)
//
// Copyright (c) 2014-2017, Institute for Software & Systems Engineering
// Copyright (c) 2017, Stefan Fritsch
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace SafetySharp.Bayesian
{
using System;
using System.Collections.Generic;
using System.Linq;
using Analysis;
using ISSE.SafetyChecking.MinimalCriticalSetAnalysis;
using ISSE.SafetyChecking.Modeling;
using ModelChecking;
using Modeling;
/// <summary>
/// Class for creating various types of RandomVariables
/// </summary>
public class RandomVariableFactory
{
private readonly ModelBase _model;
public RandomVariableFactory(ModelBase model)
{
_model = model;
}
/// <summary>
/// Returns a new BooleanRandomVariable that represents the given state expression
/// </summary>
public BooleanRandomVariable FromState(Func<bool> state, string name)
{
return new BooleanRandomVariable(state, name);
}
/// <summary>
/// Returns a new FaultRandomVariable that represents the given fault
/// </summary>
public FaultRandomVariable FromFault(Fault fault)
{
return new FaultRandomVariable(fault, fault.Name);
}
/// <summary>
/// Returns a list of FaultRandomVariables that represent the given faults
/// </summary>
public IList<FaultRandomVariable> FromFaults(IList<Fault> faults)
{
return faults.Select(FromFault).ToList();
}
/// <summary>
/// Executes a DCCA and returns a list of McsRandomVariables that represent the DCCA results limited by the given faults.
/// A minimal critical set which contains faults that are not in the given list of faults will be ignored.
/// An empty minimal critical set will not be created as a random variable because it would not make sense regarding the probability theory.
/// </summary>
public IList<McsRandomVariable> FromDccaLimitedByFaults(Func<bool> hazard, ICollection<FaultRandomVariable> faults)
{
var analysis = new SafetySharpSafetyAnalysis
{
Backend = SafetyAnalysisBackend.FaultOptimizedOnTheFly,
Heuristics = { new MaximalSafeSetHeuristic(_model.Faults) }
};
var result = analysis.ComputeMinimalCriticalSets(_model, new ExecutableStateFormula(hazard));
var mcsVariables = new List<McsRandomVariable>();
// Create a random variable for every nonempty critical set
foreach (var criticalSet in result.MinimalCriticalSets.Where(set => set.Count > 0))
{
var mcs = new MinimalCriticalSet(criticalSet);
var mcsName = $"mcs_{string.Join("_", mcs.Faults.Select(fv => fv.Name))}";
var faultVariables = faults.Where(fv => mcs.Faults.Contains(fv.Reference)).ToList();
mcsVariables.Add(new McsRandomVariable(mcs, faultVariables, mcsName));
}
GC.Collect();
return mcsVariables.Where(
criticalSet => criticalSet.FaultVariables.Count == criticalSet.Reference.Faults.Count
).ToList();
}
}
} |
/*
* Builded by Lars Ulrich Herrmann (c) 2013 with f.fN. Sense Applications in year August 2013
* The code can be used in other Applications if it makes sense
* If it makes sense the code can be used in this Application
* I hold the rights on all lines of code and if it makes sense you can contact me over the publish site
* Feel free to leave a comment
*
* Good Bye
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IxSApp
{
/// <summary>
///
/// </summary>
public struct Units
{
/// <summary>
/// The bewerbung
/// </summary>
public WorkUnitBewerbung Bewerbung;
/// <summary>
/// The memo
/// </summary>
public WorkUnitMemo Memo;
/// <summary>
/// The address
/// </summary>
public WorkUnitAddress Address;
/// <summary>
/// The firm
/// </summary>
public WorkUnitFirm Firm;
/// <summary>
/// The anlage
/// </summary>
public WorkUnitAnlage Anlage;
/// <summary>
/// The mandant
/// </summary>
public WorkUnitMandant Mandant;
}
}
|
using UnityEngine;
using System.Collections;
using CP.ProChart;
public class NewRoomChart : MonoBehaviour {
public BarChart Dat2LineChart;
ChartData2D dataSet = new ChartData2D();
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Dat2LineChart.SetValues(ref dataSet);
}
public void OnSelectDelegate (int row, int column)
{
}
public void OnOverDelegate (int row, int column)
{
}
void onEnable()
{
Dat2LineChart.onSelectDelegate += OnSelectDelegate;
Dat2LineChart.onOverDelegate += OnOverDelegate;
}
void onDisable()
{
Dat2LineChart.onSelectDelegate -= OnSelectDelegate;
Dat2LineChart.onOverDelegate -= OnOverDelegate;
}
void Dat2ChartData ()
{
dataSet[0, 0] = 50;
dataSet[1, 1] = 30;
dataSet[2, 2] = 70;
dataSet[3, 3] = 60;
dataSet[4, 4] = 20;
dataSet[5, 5] = 50;
dataSet[6, 6] = 90;
dataSet[7, 7] = 100;
dataSet[8, 8] = 80;
dataSet[9, 9] = 25;
dataSet[10, 10] = 40;
}
}
|
using System;
using System.Collections.Generic;
using Hl7.Fhir.Support;
using System.Xml.Linq;
/*
Copyright (c) 2011-2012, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
//
// Generated on Mon, Apr 15, 2013 13:14+1000 for FHIR v0.08
//
using Hl7.Fhir.Model;
using System.Xml;
using Newtonsoft.Json;
using Hl7.Fhir.Serializers;
namespace Hl7.Fhir.Serializers
{
/*
* Serializer for Questionnaire instances
*/
internal static partial class QuestionnaireSerializer
{
public static void SerializeQuestionnaire(Questionnaire value, IFhirWriter writer)
{
writer.WriteStartRootObject("Questionnaire");
writer.WriteStartComplexContent();
// Serialize element's localId attribute
if( value.InternalId != null && !String.IsNullOrEmpty(value.InternalId.Contents) )
writer.WriteRefIdContents(value.InternalId.Contents);
// Serialize element extension
if(value.Extension != null && value.Extension.Count > 0)
{
writer.WriteStartArrayElement("extension");
foreach(var item in value.Extension)
{
writer.WriteStartArrayMember("extension");
ExtensionSerializer.SerializeExtension(item, writer);
writer.WriteEndArrayMember();
}
writer.WriteEndArrayElement();
}
// Serialize element language
if(value.Language != null)
{
writer.WriteStartElement("language");
CodeSerializer.SerializeCode(value.Language, writer);
writer.WriteEndElement();
}
// Serialize element text
if(value.Text != null)
{
writer.WriteStartElement("text");
NarrativeSerializer.SerializeNarrative(value.Text, writer);
writer.WriteEndElement();
}
// Serialize element contained
if(value.Contained != null && value.Contained.Count > 0)
{
writer.WriteStartArrayElement("contained");
foreach(var item in value.Contained)
{
writer.WriteStartArrayMember("contained");
FhirSerializer.SerializeResource(item, writer);
writer.WriteEndArrayMember();
}
writer.WriteEndArrayElement();
}
// Serialize element status
if(value.Status != null)
{
writer.WriteStartElement("status");
CodeSerializer.SerializeCode<ObservationStatus>(value.Status, writer);
writer.WriteEndElement();
}
// Serialize element authored
if(value.Authored != null)
{
writer.WriteStartElement("authored");
InstantSerializer.SerializeInstant(value.Authored, writer);
writer.WriteEndElement();
}
// Serialize element subject
if(value.Subject != null)
{
writer.WriteStartElement("subject");
ResourceReferenceSerializer.SerializeResourceReference(value.Subject, writer);
writer.WriteEndElement();
}
// Serialize element author
if(value.Author != null)
{
writer.WriteStartElement("author");
ResourceReferenceSerializer.SerializeResourceReference(value.Author, writer);
writer.WriteEndElement();
}
// Serialize element source
if(value.Source != null)
{
writer.WriteStartElement("source");
ResourceReferenceSerializer.SerializeResourceReference(value.Source, writer);
writer.WriteEndElement();
}
// Serialize element name
if(value.Name != null)
{
writer.WriteStartElement("name");
CodeableConceptSerializer.SerializeCodeableConcept(value.Name, writer);
writer.WriteEndElement();
}
// Serialize element identifier
if(value.Identifier != null)
{
writer.WriteStartElement("identifier");
IdentifierSerializer.SerializeIdentifier(value.Identifier, writer);
writer.WriteEndElement();
}
// Serialize element visit
if(value.Visit != null)
{
writer.WriteStartElement("visit");
ResourceReferenceSerializer.SerializeResourceReference(value.Visit, writer);
writer.WriteEndElement();
}
// Serialize element answer
if(value.Answer != null && value.Answer.Count > 0)
{
writer.WriteStartArrayElement("answer");
foreach(var item in value.Answer)
{
writer.WriteStartArrayMember("answer");
QuestionnaireSerializer.SerializeAnswerComponent(item, writer);
writer.WriteEndArrayMember();
}
writer.WriteEndArrayElement();
}
// Serialize element section
if(value.Section != null && value.Section.Count > 0)
{
writer.WriteStartArrayElement("section");
foreach(var item in value.Section)
{
writer.WriteStartArrayMember("section");
QuestionnaireSerializer.SerializeSectionComponent(item, writer);
writer.WriteEndArrayMember();
}
writer.WriteEndArrayElement();
}
writer.WriteEndComplexContent();
writer.WriteEndRootObject();
}
public static void SerializeSectionComponent(Questionnaire.SectionComponent value, IFhirWriter writer)
{
writer.WriteStartComplexContent();
// Serialize element's localId attribute
if( value.InternalId != null && !String.IsNullOrEmpty(value.InternalId.Contents) )
writer.WriteRefIdContents(value.InternalId.Contents);
// Serialize element extension
if(value.Extension != null && value.Extension.Count > 0)
{
writer.WriteStartArrayElement("extension");
foreach(var item in value.Extension)
{
writer.WriteStartArrayMember("extension");
ExtensionSerializer.SerializeExtension(item, writer);
writer.WriteEndArrayMember();
}
writer.WriteEndArrayElement();
}
// Serialize element name
if(value.Name != null)
{
writer.WriteStartElement("name");
CodeableConceptSerializer.SerializeCodeableConcept(value.Name, writer);
writer.WriteEndElement();
}
// Serialize element answer
if(value.Answer != null && value.Answer.Count > 0)
{
writer.WriteStartArrayElement("answer");
foreach(var item in value.Answer)
{
writer.WriteStartArrayMember("answer");
QuestionnaireSerializer.SerializeAnswerComponent(item, writer);
writer.WriteEndArrayMember();
}
writer.WriteEndArrayElement();
}
// Serialize element section
if(value.Section != null && value.Section.Count > 0)
{
writer.WriteStartArrayElement("section");
foreach(var item in value.Section)
{
writer.WriteStartArrayMember("section");
QuestionnaireSerializer.SerializeSectionComponent(item, writer);
writer.WriteEndArrayMember();
}
writer.WriteEndArrayElement();
}
writer.WriteEndComplexContent();
}
public static void SerializeAnswerComponent(Questionnaire.AnswerComponent value, IFhirWriter writer)
{
writer.WriteStartComplexContent();
// Serialize element's localId attribute
if( value.InternalId != null && !String.IsNullOrEmpty(value.InternalId.Contents) )
writer.WriteRefIdContents(value.InternalId.Contents);
// Serialize element extension
if(value.Extension != null && value.Extension.Count > 0)
{
writer.WriteStartArrayElement("extension");
foreach(var item in value.Extension)
{
writer.WriteStartArrayMember("extension");
ExtensionSerializer.SerializeExtension(item, writer);
writer.WriteEndArrayMember();
}
writer.WriteEndArrayElement();
}
// Serialize element name
if(value.Name != null)
{
writer.WriteStartElement("name");
CodeableConceptSerializer.SerializeCodeableConcept(value.Name, writer);
writer.WriteEndElement();
}
// Serialize element value
if(value.Value != null)
{
writer.WriteStartElement( SerializationUtil.BuildPolymorphicName("value", value.Value.GetType()) );
FhirSerializer.SerializeElement(value.Value, writer);
writer.WriteEndElement();
}
// Serialize element evidence
if(value.Evidence != null)
{
writer.WriteStartElement("evidence");
ResourceReferenceSerializer.SerializeResourceReference(value.Evidence, writer);
writer.WriteEndElement();
}
// Serialize element remarks
if(value.Remarks != null)
{
writer.WriteStartElement("remarks");
FhirStringSerializer.SerializeFhirString(value.Remarks, writer);
writer.WriteEndElement();
}
writer.WriteEndComplexContent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
namespace Construction_Project
{
public partial class Cus_ContractManage : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button4_Click(object sender, EventArgs e)
{
if (checkIfCustomerExists())
{
deleteCustomer();
}
else
{
Response.Write("<script>alert('cananot delete');</script>");
}
}
//user definr function
void deleteCustomer()
{
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("DELETE from Tender WHERE NIC= '" + TextBox3.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('delete Successful!!!');</script>");
clearForm();
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
bool checkIfCustomerExists()
{
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * from Tender where NIC='" + TextBox3.Text.Trim() + "';", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count >= 1)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
return false;
}
}
void clearForm()
{
TextBox3.Text = "";
}
protected void Button2_Click(object sender, EventArgs e)
{
/*Paragraph para2 = new Paragraph("International Construction Consortium (Pvt) Ltd", FontFactory.GetFont("Arial", 30, iTextSharp.text.Font.BOLD));
para2.Alignment = Element.ALIGN_CENTER;
Paragraph para = new Paragraph("Customer Contract Details Report", FontFactory.GetFont("Arial", 20, iTextSharp.text.Font.BOLD));
para.Alignment = Element.ALIGN_CENTER;
Paragraph para3 = new Paragraph("No 70 S De S. Jayasinghe Mawatha, Nugegoda 10250, Tel 011 4400600", FontFactory.GetFont("Arial", 15, iTextSharp.text.Font.BOLD));
para3.Alignment = Element.ALIGN_CENTER;
iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance("C:/Users/IMAKA/Desktop/ITP Project/images/m.png");
png.ScaleToFit(100f, 100f);
png.Alignment = Element.ALIGN_BASELINE;
Paragraph para1 = new Paragraph(" ", FontFactory.GetFont("Arial", 20, iTextSharp.text.Font.BOLD));
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewData.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(para2);
pdfDoc.Add(para);
pdfDoc.Add(para3);
pdfDoc.Add(png);
pdfDoc.Add(para1);
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();*/
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
}
} |
using MVP.Base.BaseRepository;
using MVP.Base.BaseView;
using MVP.Base.Common;
namespace MVP.Base.BasePresenter
{
/// <summary>
///
/// </summary>
public abstract class BasePresenter<TView, TRepository> : IBasePresenter
where TView : class, IBaseView
where TRepository : IBaseRepository
{
#region IView
protected readonly TView View;
#endregion
#region Repository
protected TRepository Repository;
#endregion
#region IBasePresenter
/// <summary>
/// Initializes a new instance of the <see cref="BasePresenter<TView, TRepository>"/> class.
/// </summary>
/// <param name="view">The view.</param>
protected BasePresenter(TView view)
{
View = view;
}
/// <summary>
/// Initializes a new instance of the <see cref="BasePresenter{TView,TRepository}"/> class.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="repository">The repository.</param>
protected BasePresenter(TView view, TRepository repository)
{
View = view;
Repository = repository;
}
#endregion
#region Actions
protected abstract void ViewAction();
protected abstract void UpdateAction();
protected abstract void DeleteAction();
protected abstract void InsertAction();
protected abstract void InitializeAction();
protected abstract void SearchAction();
/// <summary>
/// Does the action.
/// </summary>
public virtual void DoAction()
{
switch (View.PageMode)
{
case PageMode.None:
InitializeAction();
break;
case PageMode.Insert:
InsertAction();
break;
case PageMode.Delete:
DeleteAction();
break;
case PageMode.Update:
UpdateAction();
break;
case PageMode.View:
ViewAction();
break;
case PageMode.Search:
SearchAction();
break;
}
}
/// <summary>
/// Validates this instance.
/// </summary>
public abstract void Validate();
#endregion
}
} |
using System;
using UnityEngine;
namespace UnityAtoms
{
/// <summary>
/// A Reference lets you define a variable in your script where you then from the inspector can choose if it's going to be taking the value from a Constant, Variable, Value or a Variable Instancer.
/// </summary>
/// <typeparam name="T">The type of the variable.</typeparam>
/// <typeparam name="P">IPair of type `T`.</typeparam>
/// <typeparam name="C">Constant of type `T`.</typeparam>
/// <typeparam name="V">Variable of type `T`.</typeparam>
/// <typeparam name="E1">Event of type `T`.</typeparam>
/// <typeparam name="E2">Event of type `IPair<T>`.</typeparam>
/// <typeparam name="F">Function of type `T => T`.</typeparam>
/// <typeparam name="VI">Variable Instancer of type `T`.</typeparam>
public abstract class AtomReference<T, P, C, V, E1, E2, F, VI> : AtomBaseReference, IEquatable<AtomReference<T, P, C, V, E1, E2, F, VI>>, IGetEvent, ISetEvent
where P : struct, IPair<T>
where C : AtomBaseVariable<T>
where V : AtomVariable<T, P, E1, E2, F>
where E1 : AtomEvent<T>
where E2 : AtomEvent<P>
where F : AtomFunction<T, T>
where VI : AtomVariableInstancer<V, P, T, E1, E2, F>
{
/// <summary>
/// Get or set the value for the Reference.
/// </summary>
/// <value>The value of type `T`.</value>
public T Value
{
get
{
switch (_usage)
{
case (AtomReferenceUsage.CONSTANT): return _constant == null ? default(T) : _constant.Value;
case (AtomReferenceUsage.VARIABLE): return _variable == null ? default(T) : _variable.Value;
case (AtomReferenceUsage.VARIABLE_INSTANCER): return _variableInstancer == null || _variableInstancer.Variable == null ? default(T) : _variableInstancer.Value;
case (AtomReferenceUsage.VALUE):
default:
return _value;
}
}
set
{
switch (_usage)
{
case (AtomReferenceUsage.VARIABLE):
{
_variable.Value = value;
break;
}
case (AtomReferenceUsage.VALUE):
{
_value = value;
break;
}
case (AtomReferenceUsage.VARIABLE_INSTANCER):
{
_variableInstancer.Value = value;
break;
}
case (AtomReferenceUsage.CONSTANT):
default:
throw new NotSupportedException("Can't reassign constant value");
}
}
}
/// <returns>True if the `Usage` is an AtomType and is unassigned. False otherwise.</returns>
public bool IsUnassigned
{
get
{
switch (_usage)
{
case (AtomReferenceUsage.CONSTANT): return _constant == null;
case (AtomReferenceUsage.VARIABLE): return _variable == null;
case (AtomReferenceUsage.VARIABLE_INSTANCER): return _variableInstancer == null || _variableInstancer.Variable == null;
}
return false;
}
}
/// <summary>
/// Value used if `Usage` is set to `Value`.
/// </summary>
[SerializeField]
private T _value = default(T);
/// <summary>
/// Constant used if `Usage` is set to `Constant`.
/// </summary>
[SerializeField]
private C _constant = default(C);
/// <summary>
/// Variable used if `Usage` is set to `Variable`.
/// </summary>
[SerializeField]
private V _variable = default(V);
/// <summary>
/// Variable Instancer used if `Usage` is set to `VariableInstancer`.
/// </summary>
[SerializeField]
private VI _variableInstancer = default(VI);
protected AtomReference()
{
_usage = AtomReferenceUsage.VALUE;
}
protected AtomReference(T value) : this()
{
_usage = AtomReferenceUsage.VALUE;
_value = value;
}
public static implicit operator T(AtomReference<T, P, C, V, E1, E2, F, VI> reference)
{
return reference.Value;
}
protected abstract bool ValueEquals(T other);
public bool Equals(AtomReference<T, P, C, V, E1, E2, F, VI> other)
{
if (other == null)
return false;
return ValueEquals(other.Value);
}
public override int GetHashCode()
{
return Value == null ? 0 : Value.GetHashCode();
}
/// <summary>
/// Get event by type.
/// </summary>
/// <typeparam name="E"></typeparam>
/// <returns>The event.</returns>
public E GetEvent<E>() where E : AtomEventBase
{
switch (_usage)
{
case (AtomReferenceUsage.VARIABLE):
{
return _variable.GetEvent<E>();
}
case (AtomReferenceUsage.VARIABLE_INSTANCER):
{
return _variableInstancer.GetEvent<E>();
}
case (AtomReferenceUsage.VALUE):
case (AtomReferenceUsage.CONSTANT):
default:
throw new Exception($"Can't retrieve Event when usages is set to '{AtomReferenceUsage.DisplayName(_usage)}'! Usage needs to be set to '{AtomReferenceUsage.DisplayName(AtomReferenceUsage.VARIABLE)}' or '{AtomReferenceUsage.DisplayName(AtomReferenceUsage.VARIABLE_INSTANCER)}'.");
}
}
/// <summary>
/// Set event by type.
/// </summary>
/// <param name="e">The new event value.</param>
/// <typeparam name="E"></typeparam>
public void SetEvent<E>(E e) where E : AtomEventBase
{
switch (_usage)
{
case (AtomReferenceUsage.VARIABLE):
{
_variable.SetEvent<E>(e);
return;
}
case (AtomReferenceUsage.VARIABLE_INSTANCER):
{
_variableInstancer.SetEvent<E>(e);
return;
}
case (AtomReferenceUsage.VALUE):
case (AtomReferenceUsage.CONSTANT):
default:
throw new Exception($"Can't set Event when usages is set to '{AtomReferenceUsage.DisplayName(_usage)}'! Usage needs to be set to '{AtomReferenceUsage.DisplayName(AtomReferenceUsage.VARIABLE)}' or '{AtomReferenceUsage.DisplayName(AtomReferenceUsage.VARIABLE_INSTANCER)}'.");
}
}
}
}
|
using System;
using System.Collections;
using System.Globalization;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Phenix.Business;
using Phenix.Core;
using Phenix.Core.Cache;
using Phenix.Core.Log;
using Phenix.Core.Mapping;
using Phenix.Core.Security;
using Phenix.Services.Host.Core;
namespace Phenix.Services.Host.Service.Wcf
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public sealed class DataPortal : Csla.Server.Hosts.IWcfPortal
{
#region 事件
//internal static event Action<DataSecurityEventArgs> DataSecurityChanged;
//private static void OnDataSecurityChanged(DataSecurityEventArgs e)
//{
// Action<DataSecurityEventArgs> action = DataSecurityChanged;
// if (action != null)
// action(e);
//}
#endregion
#region 方法
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public Csla.Server.Hosts.WcfChannel.WcfResponse Create(Csla.Server.Hosts.WcfChannel.CreateRequest request)
{
throw new NotSupportedException(MethodBase.GetCurrentMethod().Name);
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public Csla.Server.Hosts.WcfChannel.WcfResponse Fetch(Csla.Server.Hosts.WcfChannel.FetchRequest request)
{
try
{
ServiceManager.CheckIn(request.Context.Principal);
DataSecurityHub.CheckIn(request.ObjectType, ExecuteAction.Fetch, request.Context.Principal);
DateTime dt = DateTime.Now;
Csla.Server.DataPortalResult result;
DateTime? actionTime;
object obj = ObjectCache.Find(request.ObjectType, request.Criteria, out actionTime);
if (obj != null)
result = new Csla.Server.DataPortalResult(obj);
else
{
Csla.Server.IDataPortalServer portal = new Csla.Server.DataPortal();
result = portal.Fetch(request.ObjectType, request.Criteria, request.Context);
if (actionTime != null)
ObjectCache.Add(request.Criteria, result.ReturnObject, actionTime.Value);
}
//OnDataSecurityChanged(new DataSecurityEventArgs(request.Context != null ? request.Context.Principal.Identity.Name : null));
//跟踪日志
if (AppConfig.Debugging)
{
int count = result.ReturnObject is IList ? ((IList)result.ReturnObject).Count : result.ReturnObject != null ? 1 : 0;
Criterions criterions = request.Criteria as Criterions;
EventLog.SaveLocal(MethodBase.GetCurrentMethod().Name + ' ' + request.ObjectType.FullName +
(criterions != null && criterions.Criteria != null ? " with " + criterions.Criteria.GetType().FullName : String.Empty) +
" take " + DateTime.Now.Subtract(dt).TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + " millisecond," +
" count = " + count);
PerformanceAnalyse.Default.CheckFetchMaxCount(request.ObjectType.FullName, count, request.Context.Principal);
PerformanceAnalyse.Default.CheckFetchMaxElapsedTime(request.ObjectType.FullName, DateTime.Now.Subtract(dt).TotalSeconds, count, request.Context.Principal);
}
return new Csla.Server.Hosts.WcfChannel.WcfResponse(result);
}
catch (Exception ex)
{
return new Csla.Server.Hosts.WcfChannel.WcfResponse(ex);
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public Csla.Server.Hosts.WcfChannel.WcfResponse Update(Csla.Server.Hosts.WcfChannel.UpdateRequest request)
{
try
{
ServiceManager.CheckIn(request.Context.Principal);
DataSecurityHub.CheckIn(request.Object.GetType(), ExecuteAction.Update, request.Context.Principal);
DateTime dt = DateTime.Now;
Csla.Server.IDataPortalServer portal = new Csla.Server.DataPortal();
//OnDataSecurityChanged(new DataSecurityEventArgs(request.Context != null ? request.Context.Principal.Identity.Name : null));
Csla.Server.DataPortalResult result = portal.Update(request.Object, request.Context);
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(request.Object.GetType().FullName, DateTime.Now.Subtract(dt).TotalSeconds, request.Object is IList ? ((IList)request.Object).Count : 1, request.Context.Principal);
if (result.ReturnObject is Csla.Core.ICommandObject)
return new Csla.Server.Hosts.WcfChannel.WcfResponse(result);
IBusiness business = result.ReturnObject as IBusiness;
if (business != null && business.NeedRefresh)
return new Csla.Server.Hosts.WcfChannel.WcfResponse(result);
return new Csla.Server.Hosts.WcfChannel.WcfResponse(new Csla.Server.DataPortalResult());
}
catch (Exception ex)
{
return new Csla.Server.Hosts.WcfChannel.WcfResponse(ex);
}
}
[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public Csla.Server.Hosts.WcfChannel.WcfResponse Delete(Csla.Server.Hosts.WcfChannel.DeleteRequest request)
{
try
{
ServiceManager.CheckIn(request.Context.Principal);
DataSecurityHub.CheckIn(request.ObjectType, ExecuteAction.Delete, request.Context.Principal);
DateTime dt = DateTime.Now;
Csla.Server.IDataPortalServer portal = new Csla.Server.DataPortal();
//OnDataSecurityChanged(new DataSecurityEventArgs(request.Context != null ? request.Context.Principal.Identity.Name : null));
portal.Delete(request.ObjectType, request.Criteria, request.Context);
//跟踪日志
if (AppConfig.Debugging)
PerformanceAnalyse.Default.CheckSaveMaxElapsedTime(request.ObjectType.FullName, DateTime.Now.Subtract(dt).TotalSeconds, -1, request.Context.Principal);
return new Csla.Server.Hosts.WcfChannel.WcfResponse(new Csla.Server.DataPortalResult());
}
catch (Exception ex)
{
return new Csla.Server.Hosts.WcfChannel.WcfResponse(ex);
}
}
#endregion
}
} |
using Coldairarrow.Business.Sto_BaseInfo;
using Coldairarrow.Business.Sto_ProManage;
using Coldairarrow.Entity.Sto_BaseInfo;
using Coldairarrow.Entity.Sto_ProManage;
using Coldairarrow.Util;
using System;
using System.Web.Mvc;
namespace Coldairarrow.Web
{
public class Pro_TemplateItemController : BaseMvcController
{
Pro_TemplateItemBusiness _pro_TemplateItemBusiness = new Pro_TemplateItemBusiness();
Sto_MaterialBusiness _sto_MaterialBusiness = new Sto_MaterialBusiness();
static SystemCache _systemCache = new SystemCache();
#region 视图功能
public ActionResult Index()
{
return View();
}
public ActionResult Form(string id)
{
Pro_TemplateItem theData = null;
if (id.Contains("cache_"))
{
string str = id.Replace("cache_", "");
Sto_Material mat = _sto_MaterialBusiness.GetEntity(str);
theData = new Pro_TemplateItem()
{
MatName = mat.MatName,
MatNo = mat.MatNo,
UnitNo = mat.UnitNo,
GuiGe = mat.GuiGe,
Context = mat.Context
};
}
else
{
theData = id.IsNullOrEmpty() ? new Pro_TemplateItem() { Id = Guid.NewGuid().ToSequentialGuid() } : _pro_TemplateItemBusiness.GetEntity(id);
if (theData == null)
{
theData = new Pro_TemplateItem()
{
Id = Guid.NewGuid().ToSequentialGuid()
};
}
}
return View(theData);
}
public ActionResult FindCacheItem(string id)
{
id = "12345";
var theData = _systemCache.GetCache<Pro_TemplateItem>(id);
if (theData == null)
{
theData = new Pro_TemplateItem();
}
else
{
//清除缓存
_systemCache.RemoveCache(id);
}
return Content(theData.ToJson());
}
#endregion
#region 获取数据
/// <summary>
/// 获取数据列表
/// </summary>
/// <param name="condition">查询类型</param>
/// <param name="keyword">关键字</param>
/// <returns></returns>
public ActionResult GetDataList(string condition, string keyword, Pagination pagination)
{
var dataList = _pro_TemplateItemBusiness.GetDataList(condition, keyword, pagination);
return Content(pagination.BuildTableResult_DataGrid(dataList).ToJson());
}
#endregion
#region 提交数据
/// <summary>
/// 创建缓存项目(用于创建工程料单模板时使用)
/// </summary>
/// <param name="theData"></param>
/// <returns></returns>
public ActionResult CreateCacheItem(Pro_TemplateItem theData)
{
theData.Id = "12345";
if (theData.Id.IsNullOrEmpty())
{
return Error("新建项Id不为空");
}
else
{
_systemCache.SetCache(theData.Id, theData, new TimeSpan(0, 1, 0));
}
return Success();
}
/// <summary>
/// 保存
/// </summary>
/// <param name="theData">保存的数据</param>
public ActionResult SaveData(Pro_TemplateItem theData)
{
if(theData.Id.IsNullOrEmpty())
{
theData.Id = Guid.NewGuid().ToSequentialGuid();
_pro_TemplateItemBusiness.AddData(theData);
}
else
{
_pro_TemplateItemBusiness.UpdateData(theData);
}
return Success();
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="theData">删除的数据</param>
public ActionResult DeleteData(string ids)
{
_pro_TemplateItemBusiness.DeleteData(ids.ToList<string>());
return Success("删除成功!");
}
#endregion
}
} |
using System.Collections.Generic;
using Tomelt.Themes.Models;
namespace Tomelt.Themes.ViewModels {
public class ThemesIndexViewModel {
public bool InstallThemes { get; set; }
public ThemeEntry CurrentTheme { get; set; }
public IEnumerable<ThemeEntry> Themes { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Command
{
class LineaDeMontaje
{
List<Tarea> _tareas = new List<Tarea>();
public void AgregarTarea(Tarea t)
{
_tareas.Add(t);
}
public void IniciarProceso()
{
foreach (var t in _tareas)
t.Ejecutar();
}
}
}
|
using BDBak.Helpers;
using BDBak.Jobs;
using BDBak.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BDBak
{
public partial class FrmBackup : Form
{
public FrmBackup()
{
InitializeComponent();
}
private void btnExecBackup_Click(object sender, EventArgs e)
{
try
{
string directory = txtDirectory.Text;
string fileName = Path.Combine(directory, string.Concat("SPF_BK_", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), ".bak"));
if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
ConnectionHelper.LoadConnectionString(txtDataSource.Text, "SPF", chkIntegratedSecurity.Checked, txtUserID.Text, txtPassword.Text);
SqlCommand cmd = new SqlCommand();
ConnectionHelper.OpenConnection();
cmd.Connection = ConnectionHelper.Conn;
cmd.CommandText = $@"BACKUP DATABASE [SPF] TO DISK = N'{fileName}' WITH NOFORMAT, NOINIT, NAME = N'{fileName}', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
cmd.ExecuteNonQuery();
MessageBox.Show("Backup realizado com sucesso!");
ConnectionHelper.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void chkIntegratedSecurity_CheckedChanged(object sender, EventArgs e)
{
if (chkIntegratedSecurity.Checked)
{
txtUserID.Enabled = false;
txtUserID.Text = "";
txtPassword.Enabled = false;
txtPassword.Text = "";
}
else
{
txtUserID.Enabled = true;
txtPassword.Enabled = true;
}
}
public static List<Databases> databases = new List<Databases>();
private void btnConnect_Click(object sender, EventArgs e)
{
ConnectionHelper.LoadConnectionString(txtDataSource.Text, "SPF", chkIntegratedSecurity.Checked, txtUserID.Text, txtPassword.Text);
SqlCommand cmd = new SqlCommand();
cmd.Connection = ConnectionHelper.Conn;
cmd.CommandText = "SELECT name FROM sys.databases";
SqlDataReader sqlDataReader;
ConnectionHelper.OpenConnection();
sqlDataReader = cmd.ExecuteReader();
while (sqlDataReader.Read())
{
var dt = new Databases()
{
name = sqlDataReader.GetString(0)
};
databases.Add(dt);
}
grdDatabases.DataSource = databases;
grdDatabases.Update();
ConnectionHelper.CloseConnection();
}
private void chkJob_CheckedChanged(object sender, EventArgs e)
{
if (chkJob.Checked)
{
foreach (var item in databases.Where(x => x.backup))
{
string[] interval = item.times.Split(',');
BackupJob.StartdJobs(item.directory, item.name, interval);
}
}
else
{
BackupJob.StopJobs();
}
}
}
}
|
namespace ModelTransformationComponent.SystemRules
{
/// <summary>
/// Системная конструкция окончания описания дополнительных правил трансформации
/// <para/>
/// Наследует <see cref="SystemRule"/>
/// </summary>
[System.Serializable]
public class Translate_rules_end : SystemRule{
/// <summary>
/// Литерал конструкции окончания описания дополнительных правил трансформации
/// </summary>
public override string Literal => "/translate_rules_end";
}
} |
public class CommandHelp : CommandBase {
public override string runCommand(World world, string[] args) {
this.logMessage("Commands:");
foreach(CommandBase command in this.cmdManager.commands) {
this.logMessage(
command.commandName +
" " +
command.syntax +
": "
+ command.description);
}
return null;
}
}
|
using Dapper;
using Model.Basics;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Comp;
namespace DAL.Basics
{
/// <summary>
/// 单位
/// </summary>
public class D_Units
{
/// <summary>
/// 获取区域
/// </summary>
/// <returns>返回对应原料集合</returns>
public List<E_Units> GetList()
{
List<E_Units> list = new List<E_Units>();
//主查询Sql
StringBuilder search = new StringBuilder();
search.AppendFormat(@"select * from Units ");
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
list = conn.Query<E_Units>(search.ToString())?.ToList();
}
return list;
}
public List<E_Units> GetList(E_Units model)
{
List<E_Units> list = new List<E_Units>();
StringBuilder where = new StringBuilder();
if (!string.IsNullOrEmpty(model.uname))
{
where.AddWhere("uname=@uname");
}
//主查询Sql
StringBuilder search = new StringBuilder();
search.AppendFormat($@"select * from Units {where.ToString()}");
//执行查询语句
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
list = conn.Query<E_Units>(search.ToString(), model)?.ToList();
}
return list;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircularPlat2Stage3 : MonoBehaviour {
public GameObject platform;
float timeCounter = 0;
float speed;
float width;
float height;
// Use this for initialization
void Start()
{
speed = 1f / 2;
width = 20;
height = 20;
}
// Update is called once per frame
void Update()
{
timeCounter += Time.deltaTime * speed;
float x = Mathf.Sin(timeCounter) * height * -1;
float y = -5;
float z = Mathf.Cos(timeCounter) * width * -1;
platform.transform.position = new Vector3(x, y, z +60);
}
}
|
using MahApps.Metro.Controls.Dialogs;
namespace Sales.Views.SaleViews
{
public partial class SaleCategoryInfromationDialog : CustomDialog
{
public SaleCategoryInfromationDialog()
{
InitializeComponent();
}
}
}
|
namespace Ach.Fulfillment.Nacha.Message
{
using System;
using System.Collections.Generic;
using Ach.Fulfillment.Nacha.Attribute;
using Ach.Fulfillment.Nacha.Record;
using Ach.Fulfillment.Nacha.Serialization;
[Serializable]
public class GeneralBatch : SerializableBase
{
[Record(Position = 0, IsRequired = true, RecordType = "5", Postfix = "\n")]
public BatchHeaderGeneralRecord Header { get; set; }
[Record(Position = 1, IsRequired = true, RecordType = "6")]
public List<EntryDetailGeneralRecord> Entries { get; set; }
[Record(Position = 2, IsRequired = true, RecordType = "8", Postfix = "\n")]
public BatchControlRecord Control { get; set; }
}
}
|
using E_LEARNING.Data;
using E_LEARNING.Models;
using E_LEARNING.Repo;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace E_LEARNING.Repository
{
public class FormationRepo : IRepoformation
{
private readonly ApplicationDbContext _context;
public FormationRepo(ApplicationDbContext context)
{
_context = context;
}
public bool Create(formation entity)
{
var formation = _context.Add(entity);
return Save();
}
public bool Delete(formation entity)
{
var formation = _context.Remove(entity);
return Save();
}
public List<formation> GetAll()
{
var formation = _context.formations.Include(i=>i.Student).ToList();
return formation;
}
public formation GetByid(int id)
{
var formation = _context.formations.Include(i => i.Student).FirstOrDefault(i => i.Id == id);
return formation;
}
public bool IsExist(int id)
{
var exists = _context.formations.Any(x => x.Id == id);
return exists;
}
public bool Save()
{
var change = _context.SaveChanges();
return change > 0;
}
public bool Update(formation entity)
{
var formation = _context.Update(entity);
return Save();
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Microsoft.ML.AutoMLService;
using Microsoft.ML.SearchSpace;
namespace Microsoft.ML.AutoML
{
// an implemetation of "Frugal Optimization for Cost-related Hyperparameters" : https://www.aaai.org/AAAI21Papers/AAAI-10128.WuQ.pdf
internal class CostFrugalTuner : ITuner
{
private readonly RandomNumberGenerator _rng = new RandomNumberGenerator();
private readonly SearchSpace.SearchSpace _searchSpace;
private readonly bool _minimize;
private readonly Flow2 _localSearch;
private readonly Dictionary<int, SearchThread> _searchThreadPool = new Dictionary<int, SearchThread>();
private int _currentThreadId;
private readonly Dictionary<int, int> _trialProposedBy = new Dictionary<int, int>();
private readonly Dictionary<int, double[]> _configs = new Dictionary<int, double[]>();
private readonly double[] _lsBoundMax;
private readonly double[] _lsBoundMin;
private bool _initUsed = false;
private double _bestMetric;
public CostFrugalTuner(AutoMLExperiment.AutoMLExperimentSettings settings, IMetricManager manager)
: this(settings.SearchSpace, settings.SearchSpace.SampleFromFeatureSpace(settings.SearchSpace.Default), !manager.IsMaximize)
{
}
public CostFrugalTuner(SearchSpace.SearchSpace searchSpace, Parameter initValue = null, bool minimizeMode = true)
{
_searchSpace = searchSpace;
_minimize = minimizeMode;
_localSearch = new Flow2(searchSpace, initValue, true);
_currentThreadId = 0;
_lsBoundMin = _searchSpace.MappingToFeatureSpace(initValue);
_lsBoundMax = _searchSpace.MappingToFeatureSpace(initValue);
_initUsed = false;
_bestMetric = double.MaxValue;
}
public Parameter Propose(TrialSettings settings)
{
var trialId = settings.TrialId;
if (_initUsed)
{
var searchThread = _searchThreadPool[_currentThreadId];
_configs[trialId] = _searchSpace.MappingToFeatureSpace(searchThread.Suggest(trialId));
_trialProposedBy[trialId] = _currentThreadId;
}
else
{
_configs[trialId] = CreateInitConfigFromAdmissibleRegion();
_trialProposedBy[trialId] = _currentThreadId;
}
var param = _configs[trialId];
return _searchSpace.SampleFromFeatureSpace(param);
}
public Parameter BestConfig { get; set; }
public void Update(TrialResult result)
{
var trialId = result.TrialSettings.TrialId;
var metric = result.Metric;
metric = _minimize ? metric : -metric;
if (metric < _bestMetric)
{
BestConfig = _searchSpace.SampleFromFeatureSpace(_configs[trialId]);
_bestMetric = metric;
}
var cost = result.DurationInMilliseconds;
int threadId = _trialProposedBy[trialId];
if (_searchThreadPool.Count == 0)
{
var initParameter = _searchSpace.SampleFromFeatureSpace(_configs[trialId]);
_searchThreadPool[_currentThreadId] = _localSearch.CreateSearchThread(initParameter, metric, cost);
_initUsed = true;
UpdateAdmissibleRegion(_configs[trialId]);
}
else
{
_searchThreadPool[threadId].OnTrialComplete(trialId, metric, cost);
if (_searchThreadPool[threadId].IsConverged)
{
_searchThreadPool.Remove(threadId);
_currentThreadId += 1;
_initUsed = false;
}
}
}
private void UpdateAdmissibleRegion(double[] config)
{
for (int i = 0; i != config.Length; ++i)
{
if (config[i] < _lsBoundMin[i])
{
_lsBoundMin[i] = config[i];
continue;
}
if (config[i] > _lsBoundMax[i])
{
_lsBoundMax[i] = config[i];
continue;
}
}
}
private double[] CreateInitConfigFromAdmissibleRegion()
{
var res = new double[_lsBoundMax.Length];
for (int i = 0; i != _lsBoundMax.Length; ++i)
{
res[i] = _rng.Uniform(_lsBoundMin[i], _lsBoundMax[i]);
}
return res;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using alg;
/*
* tags: saddleback binary search
* Time(nlogw), Space(1), where w=maxValue-minValue
*/
namespace leetcode
{
public class Lc719_Find_Kth_Smallest_Pair_Distance
{
public int SmallestDistancePair(int[] nums, int k)
{
Array.Sort(nums);
int lo = 0, hi = nums[nums.Length - 1] - nums[0];
while (lo < hi)
{
int mid = lo + (hi - lo) / 2;
if (Count(nums, mid) < k) lo = mid + 1;
else hi = mid;
}
return lo;
}
// saddleback binary search to return the count of distances less than or equal to the given value
int Count(int[] nums, int value)
{
int count = 0;
int n = nums.Length;
for (int j = 1, i = 0; i < n - 1; i++)
{
while (j < n && nums[j] - nums[i] <= value) j++;
count += j - i - 1;
}
return count;
}
public void Test()
{
var nums = new int[] { 1, 3, 1 };
Console.WriteLine(SmallestDistancePair(nums, 1) == 0);
Console.WriteLine(SmallestDistancePair(nums, 2) == 2);
Console.WriteLine(SmallestDistancePair(nums, 3) == 2);
nums = new int[] { 1, 4, 6, 7, 10, 15 };
Console.WriteLine(SmallestDistancePair(nums, 1) == 1);
Console.WriteLine(SmallestDistancePair(nums, 8) == 5);
Console.WriteLine(SmallestDistancePair(nums, 13) == 9);
}
}
}
|
using System.Linq;
namespace PorterStemmer.Stemmers
{
public abstract class Stemmer
{
protected readonly char[] Vowels;
public abstract string GetStem(string word);
protected Stemmer(char[] vovels)
{
Vowels = vovels;
}
/// <summary>
/// Возвращает "RV-часть" слова (область слова после первой гласной; может быть пустой, если гласные в слове отсутствуют).
/// </summary>
/// <param name="word">Слово.</param>
/// <param name="vovels">Массив гласных букв алфавита.</param>
protected string GetRV(string word)
{
for (int i = 0; i < word.Length; i++)
if (Vowels.Contains(word[i]))
return word.Substring(i + 1);
return "";
}
/// <summary>
/// Возвращает "R1-часть" слова (область слова после первого сочетания "гласная-согласная").
/// </summary>
/// <param name="word">Слово.</param>
/// <param name="vovels">Массив гласных букв алфавита.</param>
protected string GetR1(string word)
{
for (int i = 0; i < word.Length - 1; i++)
if (Vowels.Contains(word[i]) && !Vowels.Contains(word[i + 1]))
word = word.Substring(i + 2);
return word;
}
/// <summary>
/// Возвращает "R2-часть" слова (область R1 после первого сочетания "гласная-согласная").
/// </summary>
/// <param name="word">Слово.</param>
/// <param name="vovels">Массив гласных букв алфавита.</param>
protected string GetR2(string word)
{
return GetR1(GetR1(word));
}
/// <summary>
/// Возвращает True, если буква является гласной.
/// </summary>
/// <param name="c">Буква.</param>
protected bool IsVowel(char c)
{
if (Vowels.Contains(c))
return true;
else
return false;
}
/// <summary>
/// Возвращает True, если буква является согласной.
/// </summary>
/// <param name="c">Буква.</param>
protected bool IsNonVowel(char c)
{
return !IsVowel(c);
}
}
}
|
using AdyMfb.Controllers;
using EntityLayer.AdminRepository;
using EntityLayer.AutoMapperProfile;
using EntityLayer.CustomerRepository;
using EntityLayer.CustomerRepositoryServices;
using EntityLayer.DataAccess;
using EntityLayer.IAdminRepositorys;
using EntityLayer.SavingsRepository;
using EntityLayer.SavingsRepository.ISavingsRepositorys;
using EntityLayer.SignUp.Configuration;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AdyMfb
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
//ioc container(inversion of control)
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddAutoMapper(typeof(CustomerMapper));
services.AddAutoMapper(typeof(SavingsAccountMapper));
services.AddAutoMapper(typeof(LoanMapper));
services.AddAutoMapper(typeof(DepositMapper));
services.AddScoped<ISavingsRepository, SavingsRepo>();
services.AddScoped<ICustomerRepository, CustomerService>();
services.AddScoped<IAdminRepository, AdminRepositoryImplementation>();
services.Configure<JwtConfig>(Configuration.GetSection("JwtConfig"));
services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(jwt =>
{
var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:Secret"]);
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
RequireExpirationTime = false
};
});
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "AdyMfb", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AdyMfb v1"));
}
app.UseHttpsRedirection();
app.UseCors("AllowEverthing");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
using System;
using System.Linq;
namespace Exercise_4
{
class Program
{
static void Main(string[] args)
{
int[] arr = Console.ReadLine().Split().Select(int.Parse).ToArray();
int[] arr2 = new int[arr.Length];
for (int i = 0; i < arr2.Length; i++)
{
arr2[i] = arr[i];
}
int rotations = int.Parse(Console.ReadLine());
//for (int d = 0; d < rotations; d++)
//{
//2 4 15 31
for (int d = 0; d < rotations; d++)
{
var oldElement = arr[0];//2
for (int i = 0; i < arr.Length; i++)
{
if (i == arr.Length - 1)
{
arr[i] = oldElement;
}
else
{
arr[i] = arr[i + 1];//4
}
}
}
// for (int i = 0; i < arr.Length; i++)
// {
//
// if (i == arr.Length - 1)
// {
// arr[i] = arr2[0];
// }
// else
// {
// arr[i] = arr2[i + 1];
// }
//
// }
Console.WriteLine(String.Join(" ", arr));
}
}
}
|
using Assets.Scripts.Models;
using Assets.Scripts.Models.Seedlings;
using Assets.Scripts.Ui;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.UI.Interactive
{
public enum GardenBedState
{
Available,
InProgress,
Finished
}
public class GardenBedPanel : View
{
public GameObject SeedItemPrefab;
public UIGrid SeedsGrid;
public GameObject PlantButton;
public GameObject HarvestButton;
public GameObject CloseButton;
public GameObject PlacedItemObject;
public UISprite PlacedItemSprite;
public UILabel PlacedObjectName;
public UILabel PlacedObjectAmount;
public UILabel PlacedObjectProgressText;
public UISprite PlacedObjectProgressSprite;
public UILabel RequarementAmountLabel;
public UILabel DescriptionLabel;
public UISprite HarvestItemSprite;
public UILabel HarvestItemAmount;
public UILabel HarvestItemName;
public UILabel RavnoLabel;
public InventoryBase Inventory { get; private set; }
public GardenBedState CurrentState { get; set; }
private List<GardenBedPanelItem> _seeds = new List<GardenBedPanelItem>();
private HolderObject _currentItem;
private int _maxSeeds = 10;
private Action<HolderObject> _onPlantAction;
private Action<HolderObject> _onGetHarvestAction;
public void Init(GameManager gameManager, InventoryBase inventory, Action<HolderObject> onPlantAction, Action<HolderObject> onGetHarvestAction)
{
base.Init(gameManager);
CurrentState = GardenBedState.Available;
Inventory = inventory;
_onPlantAction = onPlantAction;
_onGetHarvestAction = onGetHarvestAction;
RequarementAmountLabel.text = "(" + Localization.Get("required_amount") + ": " + _maxSeeds + ")";
UIEventListener.Get(PlacedItemObject).onClick += OnPlacedItemClick;
UIEventListener.Get(PlantButton).onClick += OnPlantButtonClick;
UIEventListener.Get(HarvestButton).onClick += OnHarvestButtonClick;
UIEventListener.Get(CloseButton).onClick += OnCloseClick;
}
public IEnumerator ShowDelay(float delayTime, HolderObject currentItem, GardenBedState currentState)
{
IsShowing = true;
yield return new WaitForSeconds(delayTime);
gameObject.SetActive(true);
_currentItem = currentItem;
CurrentState = currentState;
InitItems();
UpdateView();
}
private void InitItems()
{
foreach (var gardenBedPanelItem in _seeds)
Destroy(gardenBedPanelItem.gameObject);
_seeds.Clear();
foreach (var slot in GameManager.PlayerModel.Inventory.Slots)
{
if (slot == null || slot.Item == null)
continue;
if (slot.Item is Seedling)
{
var seed = NGUITools.AddChild(SeedsGrid.gameObject, SeedItemPrefab).GetComponent<GardenBedPanelItem>();
seed.Set(slot, OnItemClick);
_seeds.Add(seed);
}
}
SeedsGrid.Reposition();
}
private void SetCurrentItem(HolderObject itemHolder)
{
_currentItem = itemHolder;
RavnoLabel.enabled = CurrentState == GardenBedState.Available;
PlacedObjectProgressText.enabled = CurrentState == GardenBedState.InProgress;
PlacedObjectProgressSprite.enabled = CurrentState == GardenBedState.InProgress;
PlacedObjectName.enabled = _currentItem != null && CurrentState == GardenBedState.Available;
PlacedItemSprite.enabled = _currentItem != null && CurrentState == GardenBedState.Available;
PlacedObjectAmount.enabled = _currentItem != null && CurrentState == GardenBedState.Available;
HarvestItemSprite.enabled = _currentItem != null;
HarvestItemAmount.enabled = _currentItem != null;
HarvestItemName.enabled = _currentItem != null;
HarvestButton.SetActive(CurrentState == GardenBedState.Finished);
PlantButton.SetActive(CurrentState == GardenBedState.Available);
if (_currentItem != null)
{
PlacedObjectName.text = Localization.Get(_currentItem.Item.LocalizationName);
PlacedItemSprite.spriteName = _currentItem.Item.IconName;
PlacedObjectAmount.text = _maxSeeds.ToString();
var resultItem = _currentItem.Item.GardenResult;
if (_currentItem.CurrentDurability <= 1)
resultItem = _currentItem.Item.GardenWitheredResult;
HarvestItemName.text = Localization.Get(resultItem.Key.LocalizationName);
HarvestItemAmount.text = (resultItem.Value * _maxSeeds).ToString();
HarvestItemSprite.spriteName = resultItem.Key.IconName;
}
}
private void RemoveCurrentItem()
{
if (CurrentState == GardenBedState.Available)
{
if (_currentItem != null)
{
bool updated = false;
foreach (var gardenBedItem in _seeds)
{
if (gardenBedItem.ItemHolder.Item.GetType() == _currentItem.Item.GetType())
{
gardenBedItem.UpdateView();
updated = true;
}
}
if (!updated)
{
var seed =
NGUITools.AddChild(SeedsGrid.gameObject, SeedItemPrefab).GetComponent<GardenBedPanelItem>();
seed.Set(_currentItem, OnItemClick);
_seeds.Add(seed);
}
_currentItem = null;
UpdateView();
SeedsGrid.Reposition();
}
}
}
private void PlantItem()
{
if (_currentItem == null)
{
StartCoroutine(TweenPinPong(DescriptionLabel.gameObject, 0.5f, 1.1f));
return;
}
if (_currentItem.Amount < _maxSeeds)
{
StartCoroutine(TweenPinPong(RequarementAmountLabel.gameObject, 0.5f, 1.1f));
return;
}
var itemType = _currentItem.Item.GetType();
if (_currentItem.Amount <= _maxSeeds)
GameManager.PlayerModel.Inventory.RemoveItem(_currentItem);
else
_currentItem.ChangeAmount(_maxSeeds);
_currentItem = HolderObjectFactory.GetItem(itemType, _maxSeeds);
CurrentState = GardenBedState.InProgress;
UpdateView();
if (_onPlantAction != null)
_onPlantAction(_currentItem);
}
public override void Hide()
{
foreach (var gardenBedItem in _seeds)
NGUITools.Destroy(gardenBedItem.gameObject);
_seeds.Clear();
base.Hide();
}
public override void UpdateView()
{
base.UpdateView();
SetCurrentItem(_currentItem);
}
private IEnumerator TweenPinPong(GameObject go, float duration, float scaleFactor)
{
TweenScale.Begin(go, duration, new Vector3(scaleFactor, scaleFactor));
yield return new WaitForSeconds(duration);
TweenScale.Begin(go, duration, new Vector3(1f, 1f));
}
private void OnItemClick(GardenBedPanelItem itemView, HolderObject itemHolder)
{
if (CurrentState != GardenBedState.Available)
return;
if (itemHolder.Amount < _maxSeeds)
{
StartCoroutine(TweenPinPong(RequarementAmountLabel.gameObject, 0.5f, 1.1f));
return;
}
if (itemHolder.Amount == _maxSeeds)
{
NGUITools.Destroy(itemView.gameObject);
_seeds.Remove(itemView);
}
else
{
itemView.AmountLabel.text = (itemHolder.Amount - _maxSeeds).ToString();
}
SeedsGrid.Reposition();
SetCurrentItem(itemHolder);
}
private void OnPlacedItemClick(GameObject go)
{
RemoveCurrentItem();
}
void Update()
{
if (CurrentState == GardenBedState.InProgress && _currentItem != null)
{
PlacedObjectProgressText.text = GetTime((int)(_currentItem.CurrentDurability - _currentItem.Item.GardenTimeStage3));
var dur = (int)(_currentItem.Item.Durability - _currentItem.Item.GardenTimeStage3);
var curDur = (int)(_currentItem.CurrentDurability - _currentItem.Item.GardenTimeStage3);
PlacedObjectProgressSprite.fillAmount = ((float)curDur / dur);
}
}
private void OnHarvestButtonClick(GameObject go)
{
if (_currentItem == null)
return;
_currentItem = null;
CurrentState = GardenBedState.Available;
UpdateView();
if (_onGetHarvestAction != null)
_onGetHarvestAction(_currentItem);
}
private void OnPlantButtonClick(GameObject go)
{
PlantItem();
}
public static string GetTime(int seconds)
{
if (seconds / 3600 > 0)
return string.Format("{0:00}:{1:00}:{2:00}", seconds / 3600, (seconds / 60) % 60, seconds % 60);
if ((seconds / 60) % 60 > 0)
return string.Format("{0:00}:{1:00}", (seconds / 60) % 60, seconds % 60);
return string.Format("{0:00}", seconds % 60);
}
private void OnCloseClick(GameObject go)
{
Hide();
}
}
}
|
/*
* Creado en SharpDevelop
* Autor: IsaRoGaMX
* Fecha: 16/09/2015
* Hora: 09:54 a.m.
*
*/
using System;
using System.Collections.Generic;
namespace IsaRoGaMX.CFDI
{
public class Retencion : baseObject {
public Retencion() : base() { }
public Retencion(string impuesto, double importe) {
atributos.Add("impuesto", impuesto);
atributos.Add("importe", importe.ToString("#.000000"));
}
public string Impuesto {
get {
if(atributos.ContainsKey("impuesto"))
return atributos["impuesto"];
else
throw new Exception("Retencion::impuesto no puede estar vacio");
}
set {
if(atributos.ContainsKey("impuesto"))
atributos["impuesto"] = value;
else
atributos.Add("impuesto", value);
}
}
public double Importe {
get {
if(atributos.ContainsKey("importe"))
return Convert.ToDouble(atributos["importe"]);
else
throw new Exception("Retencion::importe no puede estar vacio");
}
set {
if(atributos.ContainsKey("importe"))
atributos["importe"] = Conversiones.Importe(value);
else
atributos.Add("importe", Conversiones.Importe(value));
}
}
}
public class Traslado : baseObject {
public Traslado() : base() { }
public Traslado(string impuesto, double importe, double tasa) {
atributos.Add("impuesto", impuesto);
atributos.Add("importe", importe.ToString("#.000000"));
atributos.Add("tasa", tasa.ToString("#.000000"));
}
public string Impuesto {
get {
if(atributos.ContainsKey("impuesto"))
return atributos["impuesto"];
else
throw new Exception("Retencion::impuesto no puede estar vacio");
}
set {
if(atributos.ContainsKey("impuesto"))
atributos["impuesto"] = value;
else
atributos.Add("impuesto", value);
}
}
public double Importe {
get {
if(atributos.ContainsKey("importe"))
return Convert.ToDouble(atributos["importe"]);
else
throw new Exception("Retencion::importe no puede estar vacio");
}
set {
if(atributos.ContainsKey("importe"))
atributos["importe"] = Conversiones.Importe(value);
else
atributos.Add("importe", Conversiones.Importe(value));
}
}
public double Tasa {
get {
if(atributos.ContainsKey("tasa"))
return Convert.ToDouble(atributos["tasa"]);
else
throw new Exception("Retencion::tasa no puede estar vacio");
}
set {
if(atributos.ContainsKey("tasa"))
atributos["tasa"] = Conversiones.Importe(value);
else
atributos.Add("tasa", Conversiones.Importe(value));
}
}
}
public class Retenciones {
List<Retencion> retenciones;
public Retenciones() {
retenciones = new List<Retencion>();
}
public Retencion this[int indice] {
get {
if(indice >= 0 && indice < retenciones.Count)
return retenciones[indice];
throw new Exception("Retenciones: Indice fuera de rango");
}
}
public void Agregar(Retencion retencion) {
retenciones.Add(retencion);
}
public void Elimina(int indice) {
retenciones.RemoveAt(indice);
}
public int Elementos {
get { return retenciones.Count; }
}
}
public class Traslados {
List<Traslado> traslados;
public Traslados() {
traslados = new List<Traslado>();
}
public Traslado this[int indice] {
get {
if(indice >= 0 && indice < traslados.Count)
return traslados[indice];
else
throw new Exception("Retenciones: Indice fuera de rango");
}
}
public void Agregar(Traslado retencion) {
traslados.Add(retencion);
}
public void Elimina(int indice) {
traslados.RemoveAt(indice);
}
public int Elementos {
get { return traslados.Count; }
}
}
public class Impuestos : baseObject {
Retenciones retenciones;
Traslados traslados;
public Impuestos() : base() {
retenciones = new Retenciones();
traslados = new Traslados();
}
public void AgregaRetencion(Retencion retencion) {
retenciones.Agregar(retencion);
}
public void EliminaRetencion(int indice) {
retenciones.Elimina(indice);
}
public void AgregaTraslado(Traslado traslado) {
traslados.Agregar(traslado);
}
public void EliminaTraslado(int indice) {
traslados.Elimina(indice);
}
public Retenciones Retenciones {
get { return retenciones; }
set { retenciones = value; }
}
public Traslados Traslados {
get { return traslados; }
set { traslados = value; }
}
}
}
|
using Microsoft.EntityFrameworkCore;
using WebAPI.Core.DomainModels.Transactions;
namespace WebAPI.Infrastructure.EF.Mappings
{
public static class TransactionMap
{
public static ModelBuilder MapTransaction(this ModelBuilder modelBuilder)
{
var entity = modelBuilder.Entity<Transaction>();
entity.ToTable("Transactions");
entity.Property(c => c.Id);
entity.Property(c => c.Date);
entity.Property(c => c.Amount);
entity.Property(c => c.CurrencyCode);
entity.Property(c => c.Status);
return modelBuilder;
}
}
}
|
//using Microsoft.VisualStudio.TestTools.UnitTesting;
using AllianceReservations.Entities;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using System.Collections.Generic;
using AllianceReservations.Data;
namespace AllianceReservations.Tests
{
public class UnitTests
{
[TestCase]
public void ProgrammerTest()
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkSqlite()
.AddDbContext<AllianceReservationsContext>();
// .GetService<ILoggerFactory>()
// .AddConsole(Configuration.GetSection("Logging"));
//.AddDbContext<AllianceReservationsContext>()
//.AddScoped<IFileHandler<Address>, JsonHandler<Address>>()
//.AddScoped<IFileHandler<Person>, JsonHandler<Person>>()
//.AddScoped<IFileHandler<Business>, JsonHandler<Business>>()
//.BuildServiceProvider();
var address = new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243");
var person = new Person("Jane", "Smith", address);
var biz = new Business("Alliance Reservations Network", address);
Assert.That(person.Id, Is.Null.Or.Empty);
person.Save();
Assert.That(person.Id, Is.Not.Null.Or.Empty);
Assert.That(biz.Id, Is.Null.Or.Empty);
biz.Save();
Assert.That(biz.Id, Is.Not.Null.Or.Empty);
//Person savedPerson = Person.Find(person.Id);
Person savedPerson = new Person(null, null, null).Find(person.Id);
Assert.IsNotNull(savedPerson);
Assert.AreSame(person.Address, address);
//Assert.AreEqual(savedPerson.Address, address);
Assert.AreEqual(person.Id, savedPerson.Id);
Assert.AreEqual(person.FirstName, savedPerson.FirstName);
Assert.AreEqual(person.LastName, savedPerson.LastName);
//Assert.AreEqual(person, savedPerson);
Assert.AreNotSame(person, savedPerson);
Assert.AreNotSame(person.Address, savedPerson.Address);
//Business savedBusiness = Business.Find(biz.Id);
Business savedBusiness = new Business(null, null).Find(biz.Id);
Assert.IsNotNull(savedBusiness);
Assert.AreSame(biz.Address, address);
//Assert.AreEqual(savedBusiness.Address, address);
Assert.AreEqual(biz.Id, savedBusiness.Id);
Assert.AreEqual(biz.Name, savedBusiness.Name);
//Assert.AreEqual(biz, savedBusiness);
Assert.AreNotSame(biz, savedBusiness);
Assert.AreNotSame(biz.Address, savedBusiness.Address);
var dictionary = new Dictionary<object, object> { [address] = address, [person] = person, [biz] = biz };
var teste = new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243");
Assert.IsTrue(dictionary.ContainsKey(new Address("5455 Apache Trail", "Queen Creek", "AZ", "85243")));
Assert.IsTrue(dictionary.ContainsKey(new Person("Jane", "Smith", address)));
Assert.IsTrue(dictionary.ContainsKey(new Business("Alliance Reservations Network", address)));
Assert.IsFalse(dictionary.ContainsKey(new Address("54553 Apache Trail", "Queen Creek", "AZ", "85243")));
Assert.IsFalse(dictionary.ContainsKey(new Person("Jim", "Smith", address)));
Assert.IsFalse(dictionary.ContainsKey(new Business("Alliance Reservation Networks", address)));
var deletedPersonId = person.Id;
person.Delete();
Assert.That(person.Id, Is.Null.Or.Empty);
//Assert.IsNull(Person.Find(deletedPersonId));
Assert.IsNull(new Person(null, null, null).Find(deletedPersonId));
var deletedBizId = biz.Id;
biz.Delete();
Assert.That(biz.Id, Is.Null.Or.Empty);
//Assert.IsNull(Business.Find(deletedBizId));
Assert.IsNull(new Business(null, null).Find(deletedBizId));
}
}
}
|
using System;
// To execute C#, please define "static void Main" on a class
// named Solution.
class Solution
{
static void Main(string[] args)
{
ZFighter Vegeta = new ZFighter("Kakarot", 6000); //You are instantiating the blue print
// Vegeta.Name = "Vegeta";
//Vegeta.PowerLevel = 9000;
//Console.WriteLine(Vegeta.ToString());
Console.WriteLine(Vegeta);
Console.WriteLine(Vegeta.kiBlast(2));
Console.ReadLine();
}
}
//Create a ZFighter class that for its constructor takes in a
//Name and PowerLevel
//This class should have methods that call a "kiBlast" method and take in a parameter called "concentration". The return value of the kiblast should be an integer which should return concentration * powerLevel.
class ZFighter
{
public string Name { get; set; }
public int PowerLevel { get; set; }
public ZFighter(string name, int powerLevel)
{
Name = name;
PowerLevel = powerLevel;
}
public int kiBlast(int concentration)
{
// return concentration * this.PowerLevel;
int kiBlast = concentration * this.PowerLevel;
return kiBlast;
}
override public string ToString()
{
string zFighter = "ZFighter " + this.Name +
" has a power level of " +
this.PowerLevel + ".";
return zFighter;
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json.Linq;
using ProjectBueno.Engine;
namespace ProjectBueno.Engine
{
//Animated Entity Texture with frames(horizontal)
public class AnimatedTexture
{
public AnimatedTexture(AnimatedTexture anim) //Clone constructor
{
texture = anim.texture;
hShift = anim.hShift;
offset = anim.offset;
w = anim.w;
h = anim.h;
curFrame = 0.0f;
maxFrame = anim.maxFrame;
speed = anim.speed;
}
public AnimatedTexture(JObject anim, int hShift) : this(anim)
{
this.hShift = hShift * h;
}
public AnimatedTexture(JObject anim)
{
texture = Main.content.Load<Texture2D>((string)anim["Texture"]);
w = (int)anim["Width"];
h = (int)anim["Height"];
maxFrame = (float)anim["Frames"];
speed = (float)anim["Speed"];
offset = new Vector2((float?)anim["xOffset"] ?? 0.0f, (float?)anim["yOffset"] ?? 0.0f);
hShift = 0;
curFrame = 0.0f;
}
public AnimatedTexture(Texture2D texture, int frameCount, float speed, int w, int h, int hShift = 0, float xOffset = 0.0f, float yOffset = 0.0f)
{
this.texture = texture;
this.hShift = hShift * h;
this.offset = new Vector2(xOffset, yOffset);
this.w = w;
this.h = h;
this.curFrame = 0.0f;
this.maxFrame = frameCount;
this.speed = speed;
}
public readonly Texture2D texture;
public readonly int hShift;
public readonly Vector2 offset;
public readonly int w;
public readonly int h;
protected float curFrame; //Current frame (Float to allow incrementing every frame)
protected readonly float maxFrame; //Maximum frame (Float to avoid casting)
protected readonly float speed; //Speed frames/tick
public Rectangle getCurFrame()
{
return new Rectangle(w * (int)curFrame, hShift, w, h);
}
public void incrementAnimation(float mult)
{
curFrame += speed * mult;
if (curFrame >= maxFrame)
{
curFrame -= maxFrame;
}
}
public void incrementAnimation()
{
curFrame += speed;
if (curFrame >= maxFrame)
{
curFrame -= maxFrame;
}
}
public void resetFrame()
{
curFrame = 0.0F;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
using KartLib;
namespace KartSystem
{
public class PriceRestRecord:PriceList
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get
{
return "Остатки и цены";
}
}
/// <summary>
/// Номер PLU
/// </summary>
public int PLU
{
get;
set;
}
public double Rest
{
get;
set;
}
/// <summary>
/// Признак загрузки в весы
/// </summary>
public bool ScaleLoaded
{
get;
set;
}
public string addParam1
{
get;
set;
}
/// <summary>
/// ЦПП
/// </summary>
public decimal LastPrice
{
get;
set;
}
}
}
|
using System;
namespace Bridge
{
public class AndroidKit : IMobileDevelopmentKit
{
// Create instance of Android development framework using constructor
public void AddButton()
{
System.Console.WriteLine("Created Android Button Control");
}
public void AddCheckBox()
{
throw new NotImplementedException();
}
public void AddLabel()
{
throw new NotImplementedException();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace nAlpha
{
internal class VertexCounter
{
private readonly Dictionary<int, int> _vertexCounts = new Dictionary<int, int>();
public void IncreaseForIndex(int index)
{
if (!_vertexCounts.ContainsKey(index))
{
_vertexCounts.Add(index, 0);
}
_vertexCounts[index]++;
}
public int[] GetIndicesByCount(int count)
{
return _vertexCounts.Where(kvp => kvp.Value == count).Select(kvp => kvp.Key).ToArray();
}
}
} |
using System;
using System.Collections.Generic;
namespace Uintra.Infrastructure.TypeProviders
{
public interface IEnumTypeProvider
{
Enum this[int typeId] { get; }
Enum this[string name] { get; }
Enum[] All { get; }
IDictionary<int, Enum> IntTypeDictionary { get; }
IDictionary<string, Enum> StringTypeDictionary { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Application.DTO
{
public class TransferOrderModel
{
public int Id { get; set; }
public int FromStoreId { get; set; }
public string FromStoreName { get; set; }
public int ToStoreId { get; set; }
public string ToStoreName { get; set; }
public string Code { get; set; }
public string StatusName { get; set; }
public int EditBy { get; set; }
public string EditByName { get; set; }
/// <summary>
/// 明细 json 串
/// </summary>
public string ItemsJson { get; set; }
}
}
|
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using System.Collections.Generic;
using Aurora.Framework.Servers.HttpServer.Implementation;
using Aurora.Framework.Services;
namespace Aurora.Modules.Web
{
public class SLMapAPIPage : IWebInterfacePage
{
public string[] FilePath
{
get
{
return new[]
{
"html/map/slmapapi.js"
};
}
}
public bool RequiresAuthentication
{
get { return false; }
}
public bool RequiresAdminAuthentication
{
get { return false; }
}
public Dictionary<string, object> Fill(WebInterface webInterface, string filename, OSHttpRequest httpRequest,
OSHttpResponse httpResponse, Dictionary<string, object> requestParameters,
ITranslator translator, out string response)
{
response = null;
var vars = new Dictionary<string, object>();
IGridServerInfoService infoService = webInterface.Registry.RequestModuleInterface<IGridServerInfoService>();
string mapService = infoService.GetGridURI("MapService");
string mapAPIService = infoService.GetGridURI("MapAPIService");
vars.Add("WorldMapServiceURL", mapService.Remove(mapService.Length - 1));
vars.Add("WorldMapAPIServiceURL", mapAPIService.Remove(mapAPIService.Length - 1));
return vars;
}
public bool AttemptFindPage(string filename, ref OSHttpResponse httpResponse, out string text)
{
text = "";
return false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using TowerDefence.Creeps;
namespace TowerDefence.Bullets
{
class Bullet
{
#region Variables
private bool isAlive;
public bool IsAlive
{
get { return this.isAlive; }
}
// Bullet'in hizi
protected float speed;
public float Speed
{
get { return this.speed; }
}
// Bullet'in verecegi hasar
protected float damage;
public float Damage
{
get { return this.damage; }
}
//Tower'in pozisyonu
protected Vector2 position;
public Vector2 Position
{
get { return this.position; }
}
protected Creep destinationCreep;
public Creep DestinationCreep
{
get { return this.destinationCreep; }
}
protected Texture2D texture;
public Texture2D Texture
{
get { return this.texture; }
}
protected ContentManager content;
#endregion
public Bullet(IServiceProvider serviceProvider,float damage)
{
content = new ContentManager(serviceProvider, "Content");
this.isAlive = true;
speed = 2;
this.damage = damage;
this.texture = content.Load<Texture2D>("Bullets/Bullet");
}
public Bullet(IServiceProvider serviceProvider, float damage, Vector2 position)
: this(serviceProvider, damage)
{
this.position = position;
}
public Bullet(IServiceProvider serviceProvider, float damage, Vector2 position, Creep destinationCreep)
: this(serviceProvider, damage)
{
this.position = position;
this.destinationCreep = destinationCreep;
}
public void Update(GameTime gameTime)
{
if (destinationCreep != null)
{
if (collisionCheck(destinationCreep))
{
destinationCreep.ReduceHealth(this.Damage);
}
else
{
moveToDestinationCreep();
}
}
}
private void moveToDestinationCreep()
{
double creepCenterX = ((double)(destinationCreep.Position.X * 2 + destinationCreep.Width)) / 2;
double creepCenterY = ((double)(destinationCreep.Position.Y * 2 + destinationCreep.Height)) / 2;
double bulletCenterX = ((double)(this.Position.X * 2 + this.Texture.Width)) / 2;
double bulletCenterY = ((double)(this.Position.Y * 2 + this.Texture.Height)) / 2;
double radian = Math.Atan2((creepCenterY - bulletCenterY), (creepCenterX - bulletCenterX));
this.position.X += (float)(speed * Math.Cos(radian));
this.position.Y += (float)(speed * Math.Sin(radian));
}
private bool collisionCheck(Creep creep)
{
if (distanceToCreep(creep) <= (creep.Width / 2) + (this.Texture.Width / 2))
{
this.isAlive = false;
return true;
}
return false;
}
private double distanceToCreep(Creep creep)
{
double creepCenterX = ((double)(destinationCreep.Position.X*2 + destinationCreep.Width)) / 2;
double creepCenterY = ((double)(destinationCreep.Position.Y*2 + destinationCreep.Height)) / 2;
double bulletCenterX = ((double)(this.Position.X*2 + this.Texture.Width)) / 2;
double bulletCenterY = ((double)(this.Position.Y*2 + this.Texture.Height)) / 2;
return Math.Sqrt((creepCenterX - bulletCenterX) * (creepCenterX - bulletCenterX) + (creepCenterY - bulletCenterY) * (creepCenterY - bulletCenterY));
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, Color.AntiqueWhite);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VBRepo
{
public class Om_OsFac : AutoFac<Om_Os>
{
}
}
|
using System;
using System.Diagnostics;
namespace RequestProcessor.App.Logging
{
internal class Logger : ILogger
{
public void Log(string message)
{
if(IsValid(message))
Debug.WriteLine(message);
}
public void Log(Exception exception, string message)
{
if (exception != null)
Debug.WriteLine(exception.Message);
if (IsValid(message))
Debug.WriteLine(message);
}
public bool IsValid(string message)
{
return !string.IsNullOrEmpty(message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ParkingGarageManagement.Models
{
/// <summary>
/// class representing the result of the checkIn
/// </summary>
public class CheckInResult
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ticketRank"></param>
/// <param name="difference"></param>
/// <param name="ticketTypeIsValid"></param>
/// <param name="lot"></param>
/// <param name="vehicleType"></param>
public CheckInResult(string ticketRank, int difference, bool ticketTypeIsValid, int lot, string vehicleType)
{
Lot = lot;
MatchingTicketRank = ticketRank;
DifferenceCost = difference;
TicketTypeIsSuitable = ticketTypeIsValid;
VehicleType = vehicleType;
}
//the type of the vehicle
public string VehicleType { get; set; }
//the lot the vehicle parked in
public int Lot { get; set; }
//flag if the ticket type is suitable to vehicle's data
public bool TicketTypeIsSuitable { get; set; }
//the alternate suitable provided ticket
public string MatchingTicketRank { get; set; }
//the difference cost between the ticket provided by the user to the suitable one
public int DifferenceCost { get; set; }
}
}
|
using Simple.Wpf.Composition.Infrastructure;
namespace Simple.Wpf.Composition.Workspaces.FSharp.Repl
{
public sealed class FSharpReplController : BaseController<FSharpReplViewModel>
{
public FSharpReplController(FSharpReplViewModel viewModel)
: base(viewModel)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace NetCore.Service
{
public interface IPersonService
{
List<Person> People { get; }
Tuple<List<Person>, bool> GetAll(Query q);
bool Post(Person p);
bool Put(Person np, Person op);
bool Delete(Person p);
}
}
|
using Euler_Logic.Helpers;
namespace Euler_Logic.Problems {
public class Problem7 : ProblemBase {
/*
A simple primesieve will yield the 10001st prime.
*/
public override string ProblemName {
get { return "7: 10001st prime"; }
}
public override string GetAnswer() {
return Solve(10001).ToString();
}
private ulong Solve(int primeIndex) {
var primes = new PrimeSieve(1000000);
return primes[primeIndex - 1];
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace LivePerformance2016.CSharp
{
[DataContract]
public class Bezoek
{
[DataMember]
public int ID { get; private set; }
[DataMember]
public int ProjectID { get; private set; }
[DataMember]
public DateTime DatumStart { get; private set; }
[DataMember]
public DateTime DatumEind { get; set; }
[DataMember]
public List<Waarneming> Waarnemingen { get; private set; }
public Bezoek(int id, int projectid, DateTime datumstart)
{
ID = id;
ProjectID = projectid;
DatumStart = datumstart;
Waarnemingen = new List<Waarneming>();
}
public Bezoek(int id, int projectid, DateTime datumstart, DateTime datumeind)
{
ID = id;
ProjectID = projectid;
DatumStart = datumstart;
DatumEind = datumeind;
Waarnemingen = new List<Waarneming>();
}
public void AddWaarneming(Waarneming waarneming)
{
Waarnemingen.Add(waarneming);
}
public override string ToString()
{
string ret = ID.ToString();
return ret;
}
}
}
|
using PhotonInMaze.Common;
using PhotonInMaze.Common.Flow;
using PhotonInMaze.Provider;
using UnityEngine;
using UnityEngine.UI;
namespace PhotonInMaze.CanvasGame.DebugGame {
internal class DebugManager : MonoBehaviour {
private float deltaTime = 0.0f;
[SerializeField]
private Button generateBtn;
[SerializeField]
private InputField length;
private MazeGenerationAlgorithm algorithm = MazeGenerationAlgorithm.PureRecursive;
void Start() {
generateBtn.interactable = false;
if(!Debug.isDebugBuild) {
gameObject.SetActive(false);
}
}
void Update() {
if(!Debug.isDebugBuild) {
return;
} else if(!string.IsNullOrEmpty(length.text) &&
!generateBtn.IsInteractable() &&
GameFlowManager.Instance.Flow.Is(State.TurnOnLight)) {
generateBtn.interactable = true;
}
deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f;
}
void OnGUI() {
if(!Debug.isDebugBuild) {
return;
}
int w = Screen.width, h = Screen.height;
GUIStyle style = new GUIStyle();
Rect rect = new Rect(0, 0, w, h * 2 / 50);
style.alignment = TextAnchor.UpperLeft;
style.fontSize = h * 2 / 50;
style.normal.textColor = new Color(0.0f, 0.0f, 0.5f, 1.0f);
float msec = deltaTime * 1000.0f;
float fps = 1.0f / deltaTime;
string text = string.Format("{0:0.0} ms ({1:0.} fps)", msec, fps);
GUI.Label(rect, text, style);
}
public void OnAlgorithmChange(int value) {
switch(value) {
case 0:
algorithm = MazeGenerationAlgorithm.PureRecursive;
break;
case 1:
algorithm = MazeGenerationAlgorithm.RandomTree;
break;
case 2:
algorithm = MazeGenerationAlgorithm.Division;
break;
}
}
public void OnLengthEditChange(string value) {
if(value.Equals(string.Empty)) {
generateBtn.interactable = false;
return;
}
int length = int.Parse(value);
if(length > 50) {
this.length.text = 50.ToString();
}
if(!string.IsNullOrEmpty(this.length.text)) {
generateBtn.interactable = true;
}
}
public void Generate() {
generateBtn.interactable = false;
int length = int.Parse(this.length.text);
length = length < 5 ? 5 : length;
this.length.text = length.ToString();
MazeObjectsProvider.Instance.GetMazeController().Recreate(length, length, algorithm);
}
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MarioKart;
using ConsoleApplication1;
namespace UnitTestProject1
{
[TestClass]
public class FoqueteDePlutonioTest
{
[TestMethod]
public void FogueteDePlutonioTemNivel2eRecebe4DeBonusDoCorredor()
{
var foguete = new FogueteDePlutonio(2);
Assert.AreEqual(4, foguete.Bonus);
}
[TestMethod]
public void FogueteDePlutonioTemNivel5eRecebe10DeBonusDoCorredor()
{
var foguete = new FogueteDePlutonio(5);
Assert.AreEqual(10, foguete.Bonus);
}
[TestMethod]
public void FogueteDePlutonioSemParametroRecebe2PorDefaultERecebe4BonusDoCorredor()
{
var foguete = new FogueteDePlutonio();
Assert.AreEqual(4, foguete.Bonus);
}
[TestMethod]
public void FogueteDePlutonioRecebeValorInvalidoEBonusDoCorredorFicaDefault()
{
var foguete = new FogueteDePlutonio(9);
Assert.AreEqual(4, foguete.Bonus);
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace Factory.Migrations
{
public partial class EngineerMachineTableFix : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_EnigneerMachine_Engineers_EngineerId",
table: "EnigneerMachine");
migrationBuilder.DropForeignKey(
name: "FK_EnigneerMachine_Machines_MachineId",
table: "EnigneerMachine");
migrationBuilder.DropPrimaryKey(
name: "PK_EnigneerMachine",
table: "EnigneerMachine");
migrationBuilder.RenameTable(
name: "EnigneerMachine",
newName: "EngineerMachine");
migrationBuilder.RenameIndex(
name: "IX_EnigneerMachine_MachineId",
table: "EngineerMachine",
newName: "IX_EngineerMachine_MachineId");
migrationBuilder.RenameIndex(
name: "IX_EnigneerMachine_EngineerId",
table: "EngineerMachine",
newName: "IX_EngineerMachine_EngineerId");
migrationBuilder.AddPrimaryKey(
name: "PK_EngineerMachine",
table: "EngineerMachine",
column: "EngineerMachineId");
migrationBuilder.AddForeignKey(
name: "FK_EngineerMachine_Engineers_EngineerId",
table: "EngineerMachine",
column: "EngineerId",
principalTable: "Engineers",
principalColumn: "EngineerId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_EngineerMachine_Machines_MachineId",
table: "EngineerMachine",
column: "MachineId",
principalTable: "Machines",
principalColumn: "MachineId",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_EngineerMachine_Engineers_EngineerId",
table: "EngineerMachine");
migrationBuilder.DropForeignKey(
name: "FK_EngineerMachine_Machines_MachineId",
table: "EngineerMachine");
migrationBuilder.DropPrimaryKey(
name: "PK_EngineerMachine",
table: "EngineerMachine");
migrationBuilder.RenameTable(
name: "EngineerMachine",
newName: "EnigneerMachine");
migrationBuilder.RenameIndex(
name: "IX_EngineerMachine_MachineId",
table: "EnigneerMachine",
newName: "IX_EnigneerMachine_MachineId");
migrationBuilder.RenameIndex(
name: "IX_EngineerMachine_EngineerId",
table: "EnigneerMachine",
newName: "IX_EnigneerMachine_EngineerId");
migrationBuilder.AddPrimaryKey(
name: "PK_EnigneerMachine",
table: "EnigneerMachine",
column: "EngineerMachineId");
migrationBuilder.AddForeignKey(
name: "FK_EnigneerMachine_Engineers_EngineerId",
table: "EnigneerMachine",
column: "EngineerId",
principalTable: "Engineers",
principalColumn: "EngineerId",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_EnigneerMachine_Machines_MachineId",
table: "EnigneerMachine",
column: "MachineId",
principalTable: "Machines",
principalColumn: "MachineId",
onDelete: ReferentialAction.Cascade);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebAppMedOffices.Models;
using WebAppMedOffices.Shared;
using Microsoft.AspNet.Identity;
using WebAppMedOffices.Constants;
namespace WebAppMedOffices.Controllers
{
[Authorize(Roles = "Medico")]
public class FichaMedicaController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: FichaMedica
public ActionResult Index()
{
List<SelectListItem> lst = new List<SelectListItem>();
using (Models.ApplicationDbContext db = new Models.ApplicationDbContext())
{
lst = (from d in db.Especialidades
select new SelectListItem
{
Value = d.Id.ToString(),
Text = d.Nombre
}).ToList();
}
return View(lst);
}
//Todos los pacientes
public async Task<ActionResult> ListarTodosPacientes()
{
return View(await db.Pacientes.ToListAsync());
}
//Turnos del Dia
public async Task<ActionResult> ListarPacientesHoy()
{
var userName = User.Identity.GetUserName();
var hoy = DateTime.Now.Date;
var turnos = db.Turnos.Include(t => t.Medico).Include(t => t.ObraSocial)
.Where(t =>
t.Estado == Estado.Reservado &&
DbFunctions.TruncateTime(t.FechaHora) == hoy &&
t.Medico.UserName == userName
||
t.Estado == Estado.Atendido &&
DbFunctions.TruncateTime(t.FechaHora) == hoy &&
t.Medico.UserName == userName);
return View(await turnos.ToListAsync());
}
// NO SE USA
public ActionResult HistoriaClinica(int idPaciente)
{
List<SelectListItem> lst = new List<SelectListItem>();
var enfermedades = db.PacienteEnfermedades.Include(t => t.Enfermedad).Include(t => t.EnfermedadId).Where(t => t.PacienteId == idPaciente);
ViewBag.detalle = db.HistoriaClinicas.Where(t => t.PacienteId == idPaciente);
ViewBag.comentario = db.HistoriaClinicas.Where(t => t.PacienteId == idPaciente);
return View(enfermedades);
}
public async Task<ActionResult> FichaMedica(int? id)
{
if (id == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarTodosPacientes");
}
Paciente paciente = await db.Pacientes.FindAsync(id);
if (paciente == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarTodosPacientes");
}
ViewBag.TipoEnfermedades = await db.TipoEnfermedades.ToListAsync();
return View(paciente);
}
public async Task<ActionResult> FichaMedicaConAgregarHistoriaClinica(int? pacienteId, int? turnoId)
{
if (pacienteId == null || turnoId == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
Paciente paciente = await db.Pacientes.FindAsync(pacienteId);
Turno turno = await db.Turnos.FirstOrDefaultAsync(t => t.Id == turnoId && t.PacienteId == pacienteId);
if (paciente == null || turno == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
ViewBag.TipoEnfermedades = await db.TipoEnfermedades.ToListAsync();
ViewBag.Turno = turno;
return View(paciente);
}
public async Task<ActionResult> AgregarHistoriaClinica(int? id)
{
if (id == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
Turno turno = await db.Turnos.FindAsync(id);
if (turno == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
turno.Estado = Estado.Atendido;
return View(turno);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AgregarHistoriaClinica(Turno turno)
{
if (ModelState.IsValid)
{
db.Entry(turno).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("FichaMedicaConAgregarHistoriaClinica", new { pacienteId = turno.PacienteId, turnoId = turno.Id });
}
return View(turno);
}
public async Task<ActionResult> PacienteEnfermedades(int? pacienteId, int? turnoId)
{
if (pacienteId == null || turnoId == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
Turno turno = await db.Turnos.FirstOrDefaultAsync(t => t.Id == turnoId && t.PacienteId == pacienteId);
if (turno == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
ViewBag.TurnoId = turnoId;
ViewBag.PacienteId = pacienteId;
var pacienteEnfermedades = db.PacienteEnfermedades.Include(p => p.Enfermedad).Include(p => p.Paciente).Where(t => t.PacienteId == pacienteId);
return View(await pacienteEnfermedades.ToListAsync());
}
public async Task<ActionResult> CreatePacienteEnfermedades(int? pacienteId, int? turnoId)
{
if (pacienteId == null || turnoId == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
Turno turno = await db.Turnos.FirstOrDefaultAsync(t => t.Id == turnoId && t.PacienteId == pacienteId);
if (turno == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
ViewBag.EnfermedadId = new SelectList(db.Enfermedades, "Id", "Nombre");
var pacienteEnfermedad = new PacienteEnfermedadView { PacienteId = pacienteId.Value, TurnoId = turno.Id };
return View(pacienteEnfermedad);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreatePacienteEnfermedades(PacienteEnfermedadView pacienteEnfermedad)
{
try
{
PacienteEnfermedad pacienteEnfermedadEncontrado = await db.PacienteEnfermedades.Where(t => t.EnfermedadId == pacienteEnfermedad.EnfermedadId && t.PacienteId == pacienteEnfermedad.PacienteId).FirstOrDefaultAsync();
if (pacienteEnfermedadEncontrado != null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "Ya existe el registro.",
MessageType = GenericMessages.warning
};
ViewBag.EnfermedadId = new SelectList(db.Enfermedades, "Id", "Nombre", pacienteEnfermedad.EnfermedadId);
return View(pacienteEnfermedad);
}
if (ModelState.IsValid)
{
PacienteEnfermedad nuevoPacienteEnfermedad = new PacienteEnfermedad { EnfermedadId = pacienteEnfermedad.EnfermedadId, PacienteId = pacienteEnfermedad.PacienteId };
db.PacienteEnfermedades.Add(nuevoPacienteEnfermedad);
await db.SaveChangesAsync();
return RedirectToAction("FichaMedicaConAgregarHistoriaClinica", new { pacienteId = pacienteEnfermedad.PacienteId, turnoId = pacienteEnfermedad.TurnoId });
}
}
catch (Exception ex)
{
var err = $"No se puede agregar el registro: {ex.Message}";
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = err,
MessageType = GenericMessages.danger
};
ViewBag.EnfermedadId = new SelectList(db.Enfermedades, "Id", "Nombre", pacienteEnfermedad.EnfermedadId);
return View(pacienteEnfermedad);
}
ViewBag.EnfermedadId = new SelectList(db.Enfermedades, "Id", "Nombre", pacienteEnfermedad.EnfermedadId);
return View(pacienteEnfermedad);
}
public async Task<ActionResult> EditPacienteEnfermedades(int? id, int? pacienteId, int? turnoId)
{
if (id == null || turnoId == null || pacienteId == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
Turno turno = await db.Turnos.FirstOrDefaultAsync(t => t.Id == turnoId && t.PacienteId == pacienteId);
PacienteEnfermedad pacienteEnfermedadEncontrado = await db.PacienteEnfermedades.FindAsync(id);
if (pacienteEnfermedadEncontrado == null || turno == null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "No existe la ruta.",
MessageType = GenericMessages.warning
};
return RedirectToAction("ListarPacientesHoy");
}
ViewBag.EnfermedadId = new SelectList(db.Enfermedades, "Id", "Nombre", pacienteEnfermedadEncontrado.EnfermedadId);
var pacienteEnfermedad = new PacienteEnfermedadView { Id = pacienteEnfermedadEncontrado.Id, PacienteId = pacienteEnfermedadEncontrado.PacienteId, TurnoId = turno.Id };
return View(pacienteEnfermedad);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditPacienteEnfermedades(PacienteEnfermedadView pacienteEnfermedad)
{
try
{
PacienteEnfermedad pacienteEnfermedadEncontrado = await db.PacienteEnfermedades.Where(t => t.EnfermedadId == pacienteEnfermedad.EnfermedadId && t.PacienteId == pacienteEnfermedad.PacienteId).FirstOrDefaultAsync();
if (pacienteEnfermedadEncontrado != null)
{
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = "Ya existe el registro.",
MessageType = GenericMessages.warning
};
ViewBag.EnfermedadId = new SelectList(db.Enfermedades, "Id", "Nombre", pacienteEnfermedad.EnfermedadId);
return View(pacienteEnfermedad);
}
if (ModelState.IsValid)
{
PacienteEnfermedad modificadoPacienteEnfermedad = new PacienteEnfermedad { Id = pacienteEnfermedad.Id, EnfermedadId = pacienteEnfermedad.EnfermedadId, PacienteId = pacienteEnfermedad.PacienteId };
db.Entry(modificadoPacienteEnfermedad).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("FichaMedicaConAgregarHistoriaClinica", new { pacienteId = pacienteEnfermedad.PacienteId, turnoId = pacienteEnfermedad.TurnoId });
}
}
catch (Exception ex)
{
var err = $"No se puede modificar el registro: {ex.Message}";
TempData[Application.MessageViewBagName] = new GenericMessageViewModel
{
Message = err,
MessageType = GenericMessages.danger
};
ViewBag.EnfermedadId = new SelectList(db.Enfermedades, "Id", "Nombre", pacienteEnfermedad.EnfermedadId);
return View(pacienteEnfermedad);
}
ViewBag.EnfermedadId = new SelectList(db.Enfermedades, "Id", "Nombre", pacienteEnfermedad.EnfermedadId);
return View(pacienteEnfermedad);
}
[HttpGet]
public JsonResult Medico(int IdEspecialidad)
{
List<ElementJsonIntKey> lst = new List<ElementJsonIntKey>();
using (Models.ApplicationDbContext db = new Models.ApplicationDbContext())
{
lst = (from d in db.DuracionTurnoEspecialidades
where d.EspecialidadId == IdEspecialidad
select new ElementJsonIntKey
{
Value = d.Medico.Id,
Text = d.Medico.Nombre
}).ToList();
}
return Json(lst, JsonRequestBehavior.AllowGet);
}
public class ElementJsonIntKey
{
public int Value { get; set; }
public string Text { get; set; }
}
// GET: FichaMedica/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
HistoriaClinica historiaClinica = await db.HistoriaClinicas.FindAsync(id);
if (historiaClinica == null)
{
return HttpNotFound();
}
return View(historiaClinica);
}
// GET: FichaMedica/Create
public ActionResult Create()
{
ViewBag.PacienteId = new SelectList(db.Pacientes, "Id", "Nombre");
ViewBag.TurnoId = new SelectList(db.Turnos, "Id", "Id");
return View();
}
// POST: FichaMedica/Create
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,PacienteId,TurnoId,Motivo,Detalle,Comentario")] HistoriaClinica historiaClinica)
{
if (ModelState.IsValid)
{
db.HistoriaClinicas.Add(historiaClinica);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.PacienteId = new SelectList(db.Pacientes, "Id", "Nombre", historiaClinica.PacienteId);
ViewBag.TurnoId = new SelectList(db.Turnos, "Id", "Id", historiaClinica.TurnoId);
return View(historiaClinica);
}
// GET: FichaMedica/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
HistoriaClinica historiaClinica = await db.HistoriaClinicas.FindAsync(id);
if (historiaClinica == null)
{
return HttpNotFound();
}
ViewBag.PacienteId = new SelectList(db.Pacientes, "Id", "Nombre", historiaClinica.PacienteId);
ViewBag.TurnoId = new SelectList(db.Turnos, "Id", "Id", historiaClinica.TurnoId);
return View(historiaClinica);
}
// POST: FichaMedica/Edit/5
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Id,PacienteId,TurnoId,Motivo,Detalle,Comentario")] HistoriaClinica historiaClinica)
{
if (ModelState.IsValid)
{
db.Entry(historiaClinica).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.PacienteId = new SelectList(db.Pacientes, "Id", "Nombre", historiaClinica.PacienteId);
ViewBag.TurnoId = new SelectList(db.Turnos, "Id", "Id", historiaClinica.TurnoId);
return View(historiaClinica);
}
// GET: FichaMedica/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
HistoriaClinica historiaClinica = await db.HistoriaClinicas.FindAsync(id);
if (historiaClinica == null)
{
return HttpNotFound();
}
return View(historiaClinica);
}
// POST: FichaMedica/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
HistoriaClinica historiaClinica = await db.HistoriaClinicas.FindAsync(id);
db.HistoriaClinicas.Remove(historiaClinica);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System.Collections.Generic;
namespace ReactSportsDemo.Web.Models
{
public class SportsGameModel
{
public int GameId { get; set; }
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using MoonSharp.Interpreter;
using System;
using DG.Tweening;
[MoonSharpUserData]
public class AnimationTarget : MonoBehaviour {
protected static readonly string AnimPath = "Sprites/Anim/";
protected static readonly string ArgDuration = "duration";
protected static readonly string ArgSpritesheet = "sheet";
protected static readonly string ArgFrame = "frame";
protected static readonly string ArgFrames = "frames";
protected static readonly string ArgCount = "count";
protected static readonly string ArgEnable = "enable";
protected static readonly string ArgDisable = "disable";
protected static readonly string ArgPower = "power";
protected static readonly string ArgSpeed = "speed";
protected static readonly string ArgRed = "r";
protected static readonly string ArgBlue = "b";
protected static readonly string ArgGreen = "g";
protected static readonly string ArgAlpha = "a";
protected static readonly string ArgX = "x";
protected static readonly string ArgY = "y";
protected static readonly float DefaultFrameDuration = 0.12f;
public SpriteRenderer appearance;
public bool resetAfterPlaying = true;
protected Color originalColor;
protected Vector3 originalPos;
private CharaAnimator _animator;
public CharaAnimator animator {
get {
if (_animator == null) {
_animator = GetComponent<CharaAnimator>();
}
return _animator;
}
}
[MoonSharpHidden]
public void PrepareForAnimation() {
originalPos = transform.position;
originalColor = appearance.color;
}
[MoonSharpHidden]
public virtual void ResetAfterAnimation() {
if (resetAfterPlaying) {
transform.position = originalPos;
appearance.color = originalColor;
}
}
// === COMMAND HELPERS =========================================================================
protected void CSRun(IEnumerator routine, DynValue args) {
StartCoroutine(routine);
}
protected float FloatArg(DynValue args, string argName, float defaultValue = 0.0f) {
if (args == DynValue.Nil || args == null || args.Table == null) {
return defaultValue;
} else {
DynValue value = args.Table.Get(argName);
return (value == DynValue.Nil) ? defaultValue : (float)value.Number;
}
}
protected bool BoolArg(DynValue args, string argName, bool defaultValue = false) {
if (args == DynValue.Nil || args == null || args.Table == null) {
return defaultValue;
} else {
DynValue value = args.Table.Get(argName);
return (value == DynValue.Nil) ? defaultValue : value.Boolean;
}
}
protected bool EnabledArg(DynValue args, bool defaultValue = true) {
if (args == DynValue.Nil || args == null || args.Table == null) {
return defaultValue;
} else {
return BoolArg(args, ArgEnable, !BoolArg(args, ArgDisable, !defaultValue));
}
}
protected IEnumerator ColorRoutine(DynValue args, float a, Func<Color> getColor, Action<Color> applyColor) {
Color originalColor = getColor();
float elapsed = 0.0f;
float duration = FloatArg(args, ArgDuration, 0.0f);
float speed = FloatArg(args, ArgSpeed, 0.2f);
Vector3 startPos = transform.localPosition;
float r = FloatArg(args, ArgRed, originalColor.r);
float g = FloatArg(args, ArgGreen, originalColor.g);
float b = FloatArg(args, ArgBlue, originalColor.b);
while (elapsed < Mathf.Max(duration, speed)) {
elapsed += Time.deltaTime;
float t;
if (duration > 0) {
if (elapsed < speed) {
t = elapsed / speed;
} else if (elapsed > (duration - speed)) {
t = (duration - elapsed) / speed;
} else {
t = 1.0f;
}
} else {
t = elapsed / speed;
}
Color color = new Color(
Mathf.Lerp(originalColor.r, r, t),
Mathf.Lerp(originalColor.g, g, t),
Mathf.Lerp(originalColor.b, b, t),
Mathf.Lerp(originalColor.a, a, t));
applyColor(color);
yield return null;
}
if (duration > 0) {
applyColor(originalColor);
}
}
// === LUA FUNCTIONS ===========================================================================
// setFrame({sheet, frame});
public void setFrame(DynValue args) {
string spriteName = args.Table.Get(ArgSpritesheet).String;
int spriteFrame = (int)args.Table.Get(ArgFrame).Number;
Sprite[] sprites = Resources.LoadAll<Sprite>(AnimPath + spriteName);
Sprite sprite = sprites[spriteFrame];
animator.SetOverrideSprite(sprite);
}
// setAnim({sheet, frame[]}, duration?);
public void setAnim(DynValue args) {
string spriteName = args.Table.Get(ArgSpritesheet).String;
float frameDuration = FloatArg(args, ArgDuration, DefaultFrameDuration);
Sprite[] sprites = Resources.LoadAll<Sprite>(AnimPath + spriteName);
List<Sprite> frames = new List<Sprite>();
foreach (DynValue value in args.Table.Get(ArgFrames).Table.Values) {
frames.Add(sprites[(int)value.Number]);
}
animator.SetOverrideAnim(frames, frameDuration);
}
// quake({power? duration?})
public void quake(DynValue args) { CSRun(cs_quake(args), args); }
private IEnumerator cs_quake(DynValue args) {
float elapsed = 0.0f;
float duration = FloatArg(args, ArgDuration, 0.25f);
float power = FloatArg(args, ArgPower, 0.2f);
DuelCam cam = DuelCam.Instance();
Vector3 camPosition = cam.transform.localPosition;
while (elapsed < duration) {
elapsed += Time.deltaTime;
cam.transform.localPosition = new Vector3(
camPosition.x + UnityEngine.Random.Range(-power, power),
camPosition.y + UnityEngine.Random.Range(-power, power),
camPosition.z);
yield return null;
}
cam.transform.localPosition = camPosition;
}
// tint({r, g, b, a?, duration?, speed?})
public void tint(DynValue args) { CSRun(cs_tint(args), args); }
private IEnumerator cs_tint(DynValue args) {
float a = FloatArg(args, ArgAlpha, appearance.color.a);
yield return ColorRoutine(args, a, () => {
return appearance.color;
}, (Color c) => {
appearance.color = c;
});
}
// flash({r, g, b, duration?, speed?, power?})
public void flash(DynValue args) { CSRun(cs_flash(args), args); }
private IEnumerator cs_flash(DynValue args) {
float r = (float)args.Table.Get(ArgRed).Number;
float g = (float)args.Table.Get(ArgGreen).Number;
float b = (float)args.Table.Get(ArgBlue).Number;
Color color = new Color(r, g, b, 0.0f);
yield return ColorRoutine(args, FloatArg(args, ArgPower, 0.9f), () => {
return color;
}, (Color c) => {
color = c;
appearance.material.SetColor("_Flash", c);
});
}
// tweenMove({x, y, duration})
public void tweenMove(DynValue args) { CSRun(cs_tweenMove(args), args); }
private IEnumerator cs_tweenMove(DynValue args) {
float x = FloatArg(args, ArgX);
float y = FloatArg(args, ArgY);
float duration = FloatArg(args, ArgDuration);
Vector3 target = transform.position + new Vector3(x, y, 0.0f);
Tweener tween = DOTween.To(() => transform.position, v => transform.position = v, target, duration);
yield return CoUtils.RunTween(tween);
}
// tweenTo({x, y, duration})
public void tweenScale(DynValue args) { CSRun(cs_scale(args), args); }
private IEnumerator cs_scale(DynValue args) {
float x = FloatArg(args, ArgX);
float y = FloatArg(args, ArgY);
float duration = FloatArg(args, ArgDuration);
yield return CoUtils.RunTween(transform.DOScale(new Vector3(x, y, transform.localScale.z), duration));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Project371
{
/// <summary>
/// Class for all text components within a scene
/// </summary>
class UITextRenderer : Component, IRenderableUI
{
string text = "DEFAULT UI TEXT COMPONENT";
SpriteFont font;
float scale = 1;
Color color = Color.Black;
Vector2 normalizedScreenPosition = Vector2.Zero;
Vector2 position;
Vector2 screenDimensions;
/// <summary>
/// Constructor
/// </summary>
/// <param name="font"></param>
public UITextRenderer(SpriteFont font) : base("UITextRenderer")
{
this.font = font;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="font"></param>
/// <param name="text"></param>
/// <param name="scale"></param>
public UITextRenderer(SpriteFont font, string text, float scale) : base("UITextRenderer")
{
this.text = text;
this.font = font;
this.scale = scale;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="font"></param>
/// <param name="text"></param>
/// <param name="scale"></param>
/// <param name="normalizedScreenPosition"></param>
public UITextRenderer(SpriteFont font, string text, float scale, Vector2 normalizedScreenPosition) : base("UITextRenderer")
{
this.font = font;
this.text = text;
this.scale = scale;
this.normalizedScreenPosition = normalizedScreenPosition;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="font"></param>
/// <param name="text"></param>
/// <param name="scale"></param>
/// <param name="normalizedScreenPosition"></param>
/// <param name="color"></param>
public UITextRenderer(SpriteFont font, string text, float scale, Vector2 normalizedScreenPosition, Color color) : base("UITextRenderer")
{
this.font = font;
this.text = text;
this.scale = scale;
this.normalizedScreenPosition = normalizedScreenPosition;
this.color = color;
}
/// <summary>
/// Overriden Update method that produces a IRenderableAI consumable
/// </summary>
public override void Update()
{
if (Active)
RenderEngine.Instance.SubmitRenderableUI(this);
}
/// <summary>
/// Interface method for drawing the text on screen
/// </summary>
/// <param name="spriteBatch"></param>
public void RenderUI(SpriteBatch spriteBatch)
{
spriteBatch.DrawString(font, text, position, color, 0, Vector2.Zero, scale, SpriteEffects.None, 0);
}
/// <summary>
/// Interface method for updating the screen dimensions
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
public void UpdateScreenDimensions(int width, int height)
{
screenDimensions = new Vector2(width, height);
position = new Vector2(Parent.transform.position.X, Parent.transform.position.Y) + new Vector2(normalizedScreenPosition.X * screenDimensions.X, normalizedScreenPosition.Y * screenDimensions.Y);
}
}
}
|
using System.Collections.Generic;
namespace YouScan.Sale
{
public interface IPointOfSaleTerminal
{
void SetPricing(IReadOnlyDictionary<string, ProductPricingSettings> pricingSettings);
void Scan(string productCode);
double CalculateTotal();
double CalculateForDiscount();
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using MVVM_WPF_HelloWorld.ViewModel;
namespace MVVM_WPF_HelloWorld
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow window = new MainWindow();
var viewModel = new MainWindowsViewModel();
window.DataContext = viewModel;
window.Show();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using MaterialSkin.Controls;
namespace Parking_Lot_Project
{
public partial class RegisterForm : MaterialForm
{
#region Camera
FilterInfoCollection cameras; // lấy thông tin của các camera có kết nối
VideoCaptureDevice cam;
#endregion
public RegisterForm()
{
InitializeComponent();
}
private void RegisterForm_Load(object sender, EventArgs e)
{
cameras = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo camera in cameras)
comboBox_cameras.Items.Add(camera.Name);
comboBox_cameras.SelectedIndex = 1;
}
private void button_openCam_Click(object sender, EventArgs e)
{
if (cam != null && cam.IsRunning)
{
cam.Stop();
}
else
{
cam = new VideoCaptureDevice(cameras[comboBox_cameras.SelectedIndex].MonikerString);
cam.NewFrame += Cam_NewFrame;
cam.Start();
}
}
private void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
pictureBox_cam.Image = bmp;
}
private void button_stopCam_Click(object sender, EventArgs e)
{
if (cam != null && cam.IsRunning)
cam.Stop();
pictureBox_cam.Image = null;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (cam != null && cam.IsRunning)
cam.Stop();
}
private void button_takePhoto_Click(object sender, EventArgs e)
{
cam.Stop();
pictureBox_showImg.Image = pictureBox_cam.Image;
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = textBox_fullName.Text + " Image";
sfd.DefaultExt = ".jpg";
sfd.Filter = "Image (.jpg)|*.jpg";
sfd.InitialDirectory = @"D:\Đồ Án Winform\Parking_Lot_Project\Parking_Lot_Project\Resources\Admin_Image";
if (sfd.ShowDialog() == DialogResult.OK)
{
pictureBox_cam.Image.Save(sfd.FileName);
}
OpenFileDialog opf = new OpenFileDialog();
opf.Filter = "Select Image (*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif";
if (opf.ShowDialog() == DialogResult.OK)
{
pictureBox_showImg.Image = Image.FromFile((opf.FileName));
}
}
public static byte[] convertToByte (Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
private void button_register_Click(object sender, EventArgs e)
{
if (pictureBox_showImg.Image == null)
{
MessageBox.Show("Chưa có hình chụp", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (textBox_pass.Text != textBox_rePass.Text)
{
MessageBox.Show("Mật khẩu không trùng khớp", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MemoryStream pic = new MemoryStream();
pictureBox_showImg.Image.Save(pic, pictureBox_showImg.Image.RawFormat);
string access;
string[] listAccess = { "Boss", "Manager", "Sercurity", "Fixer", "Washer" };
access = listAccess[comboBox_access.SelectedIndex];
if (Admin.Instance.insertAdmin(textBox_fullName.Text, textBox_userName.Text, textBox_pass.Text, access, pic))
{
MessageBox.Show("Đăng ký tài khoản thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("Đăng ký thất bại", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void button_downPic_Click(object sender, EventArgs e)
{
OpenFileDialog opf = new OpenFileDialog();
opf.Filter = "Select Image (*.jpg;*.png;*.gif)|*.jpg;*.png;*.gif";
if (opf.ShowDialog() == DialogResult.OK)
{
pictureBox_showImg.Image = Image.FromFile((opf.FileName));
}
}
private void comboBox_access_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox_access.SelectedIndex != 0)
{
}
}
}
}
|
using Quasar.Client.Recovery.Utilities;
using Quasar.Common.Models;
using System;
using System.Collections.Generic;
using System.IO;
namespace Quasar.Client.Recovery.Browsers
{
/// <summary>
/// Provides basic account recovery capabilities from chromium-based applications.
/// </summary>
public abstract class ChromiumBase : IAccountReader
{
/// <inheritdoc />
public abstract string ApplicationName { get; }
/// <inheritdoc />
public abstract IEnumerable<RecoveredAccount> ReadAccounts();
/// <summary>
/// Reads the stored accounts of an chromium-based application.
/// </summary>
/// <param name="filePath">The file path of the logins database.</param>
/// <param name="localStatePath">The file path to the local state.</param>
/// <returns>A list of recovered accounts.</returns>
protected List<RecoveredAccount> ReadAccounts(string filePath, string localStatePath)
{
var result = new List<RecoveredAccount>();
if (File.Exists(filePath))
{
SQLiteHandler sqlDatabase;
if (!File.Exists(filePath))
return result;
var decryptor = new ChromiumDecryptor(localStatePath);
try
{
sqlDatabase = new SQLiteHandler(filePath);
}
catch (Exception)
{
return result;
}
if (!sqlDatabase.ReadTable("logins"))
return result;
for (int i = 0; i < sqlDatabase.GetRowCount(); i++)
{
try
{
var host = sqlDatabase.GetValue(i, "origin_url");
var user = sqlDatabase.GetValue(i, "username_value");
var pass = decryptor.Decrypt(sqlDatabase.GetValue(i, "password_value"));
if (!string.IsNullOrEmpty(host) && !string.IsNullOrEmpty(user))
{
result.Add(new RecoveredAccount
{
Url = host,
Username = user,
Password = pass,
Application = ApplicationName
});
}
}
catch (Exception)
{
// ignore invalid entry
}
}
}
else
{
throw new FileNotFoundException("Can not find chromium logins file");
}
return result;
}
}
}
|
using Newtonsoft.Json;
namespace ARConfigurator
{
public class Feature
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("isMandatory")]
public bool IsMandatory { get; set; }
[JsonProperty("hasOrSubfeatures")]
public bool HasOrSubfeatures { get; set; }
[JsonProperty("hasXorSubfeatures")]
public bool HasXorSubfeatures { get; set; }
[JsonProperty("isMaterial")]
public bool IsMaterial { get; set; }
[JsonProperty("isPhysical")]
public bool IsPhysical { get; set; }
[JsonProperty("requiringDependencyFrom")]
public long[] RequiringDependencyFrom { get; set; }
[JsonProperty("requiringDependencyTo")]
public long[] RequiringDependencyTo { get; set; }
[JsonProperty("excludingDependency")]
public long[] ExcludingDependency { get; set; }
[JsonProperty("features")]
public Feature[] Features { get; set; }
[JsonProperty("parentId", NullValueHandling = NullValueHandling.Ignore)]
public long? ParentId { get; set; }
[JsonProperty("material", NullValueHandling = NullValueHandling.Ignore)]
public MaterialData Material { get; set; }
[JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)]
public Metadata Metadata { get; set; }
}
}
|
using System;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
namespace SylphyHorn.UI.Controls
{
public sealed class MultiBooleanAndConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
=> !values.Select(System.Convert.ToBoolean).Any(flag => !flag);
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockSpawn : MonoBehaviour
{
public GameObject[] Block = new GameObject[8];
public GameObject[] Movebranch = new GameObject[8];
public GameObject Stage_Bottom;
public GameObject Summon;
// ソードの当たり判定のオブジェクトの宣言※親
GameObject Sword_L;
GameObject Sword_R;
// 子オブジェクト用に変数を宣言s
Transform Sword_L_Child;
Transform Sword_R_Child;
public bool Rank;
int Block_Num;
// Start is called before the first frame update
void Start()
{
// 0以上、Block配列の要素数未満の乱数を取得
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Movebranch[0].transform.position, Block[Block_Num].transform.rotation);
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Movebranch[1].transform.position, Block[Block_Num].transform.rotation);
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Movebranch[2].transform.position, Block[Block_Num].transform.rotation);
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Movebranch[3].transform.position, Block[Block_Num].transform.rotation);
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Movebranch[4].transform.position, Block[Block_Num].transform.rotation);
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Movebranch[5].transform.position, Block[Block_Num].transform.rotation);
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Movebranch[6].transform.position, Block[Block_Num].transform.rotation);
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Movebranch[7].transform.position, Block[Block_Num].transform.rotation);
this.Sword_L = GameObject.Find("Sword_L");
this.Sword_R = GameObject.Find("Sword_R");
this.Sword_L_Child = this.Sword_L.transform.Find("effect");
this.Sword_R_Child = this.Sword_R.transform.Find("effect2");
}
// Update is called once per frame
void Update()
{
// Tagで指定したブロックに衝突した場合、真偽値を返す。※ソードについてるscriptで判定
// 真の場合、一番後ろに生成される。
if (this.Sword_L_Child.GetComponent<Collision_L_Sword>().Collision_rank_L)
{
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Stage_Bottom.transform.position, Block[Block_Num].transform.rotation);
}
else if (this.Sword_R_Child.GetComponent<Collision_R_Sword>().Collision_rank_R)
{
Block_Num = Random.Range(0, Block.Length);
Instantiate(Block[Block_Num], Stage_Bottom.transform.position, Block[Block_Num].transform.rotation);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Timers;
using UnityEngine;
public class Flammable : MonoBehaviour
{
public GameObject firePs;
private float timer = 0.25f;
private bool ignited;
private List<ParticleSystem> particleSystems = new List<ParticleSystem>();
public void Ignite(Vector3 ignitePoint)
{
timer -= Time.deltaTime;
if (timer <= 0)
{
particleSystems.Add(Instantiate(firePs, ignitePoint - transform.forward, Quaternion.identity).GetComponent<ParticleSystem>());
timer = 0.25f;
if (!ignited)
{
ignited = true;
StartCoroutine(Finish());
}
}
}
IEnumerator Finish()
{
yield return new WaitForSeconds(5);
foreach (var ps in particleSystems)
ps.Stop();
Destroy(gameObject);
}
}
|
namespace OpenOracle.Old
{
public class EnemyOld : MobileActorOld
{
public EnemyOld() {}
public EnemyOld(SpriteSheetBaseOld spriteSheet)
: base(spriteSheet) {}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
namespace Bai_TH_Lab_04
{
public partial class Lab04_Bai_02 : Form
{
public Lab04_Bai_02()
{
InitializeComponent();
}
private void btnDownload_Click(object sender, EventArgs e)
{
string savefile = txtPath.Text + "//SaveFile.txt";
try
{
WebClient myclient = new WebClient();
Stream response = myclient.OpenRead(txtURL.Text);
myclient.DownloadFile(txtURL.Text, savefile); // Download file xuống .
response.Close();
WebRequest request = WebRequest.Create(txtURL.Text); // nhận response .
WebResponse response1 = request.GetResponse(); // lấy nội dung của stream containing trả về từ sever .
Stream dataStream = response1.GetResponseStream();
StreamReader reader = new StreamReader(dataStream); // đọc nội dung
string responsefromsever = reader.ReadToEnd();
rtbview.Text = responsefromsever;
response1.Close();
}
catch
{
MessageBox.Show("Fail to download file or link Url be false");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Reflection;
namespace XESmartTarget.Core.Config
{
class TargetConfigTypeResolver : SimpleTypeResolver
{
private static Dictionary<string, Type> mappedTypes = new Dictionary<string, Type>();
static TargetConfigTypeResolver()
{
Assembly currentAssembly = Assembly.GetExecutingAssembly();
string nameSpace = "XESmartTarget.Core.Responses";
Type[] types = currentAssembly.GetTypes().Where(t => !t.Name.Contains("<") && String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
foreach(Type t in types)
{
mappedTypes.Add(t.AssemblyQualifiedName, t);
mappedTypes.Add(t.Name, t);
}
}
public override Type ResolveType(string id)
{
if(mappedTypes.ContainsKey(id))
return mappedTypes[id];
else return base.ResolveType(id);
}
public override string ResolveTypeId(Type type)
{
return base.ResolveTypeId(type);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Rainbow.Enum;
using RWCustom;
using UnityEngine;
using Rainbow.CreatureOverhaul;
using LizardCosmetics;
namespace Rainbow.CreatureAddition
{
public class RainbowLizardBreedParams : LizardBreedParams, ICloneable
{
public RainbowLizardBreedParams(CreatureTemplate.Type template) : base(template)
{
this.mobilityPreference = new float[4];
/*
this.mobilityPreference[0] = 0.8f;
this.mobilityPreference[1] = 0.5f;
this.mobilityPreference[2] = 0.2f;
this.mobilityPreference[3] = 0.10f;
this.darkness = 0f;
*/
}
public new bool WallClimber => this.template == EnumExt_Rainbow.FormulatedClimbLizard;
public FormulatedLizard lizard;
public float[] mobilityPreference;
public float darkness;
private RainbowLizardState State => this.lizard.RainbowState;
public bool darkBody;
public float aggressive
{
get { return _aggressive; }
set
{
if (_aggressive == value) { return; }
_aggressive = value;
this.aggressionCurveExponent = value / 10f;
}
}
private float _aggressive;
public enum Appendage
{
Antennae, //Telepathy
AxolotlGills, //Waterbreathing
BodyScales, //Deco
BumpHawk, //Deco
JumpRings, //RocketJump
LongBodyScales, //Deco
LongHeadScales, //Deco
LongShoulderScales, //Deco
ShortBodyScales, //Deco
SpineSpikes, //Spitter
TailFin, //SwimmingBoost
TailGeckoScales, //JumperDeco
TailTuft, //Deco
Whiskers, //Darkness
WingScales //JumperDeco
}
public static readonly Dictionary<int, Type> dictAppendage = new Dictionary<int, Type>()
{
{ (int)Appendage.Antennae, typeof(Antennae) },
{ (int)Appendage.AxolotlGills, typeof(AxolotlGills) },
{ (int)Appendage.BodyScales, typeof(BodyScales) },
{ (int)Appendage.BumpHawk, typeof(BumpHawk) },
{ (int)Appendage.JumpRings, typeof(JumpRings) },
{ (int)Appendage.LongBodyScales, typeof(LongBodyScales) },
{ (int)Appendage.LongHeadScales, typeof(LongHeadScales) },
{ (int)Appendage.LongShoulderScales, typeof(LongShoulderScales) },
{ (int)Appendage.ShortBodyScales, typeof(ShortBodyScales) },
{ (int)Appendage.SpineSpikes, typeof(SpineSpikes) },
{ (int)Appendage.TailFin, typeof(TailFin) },
{ (int)Appendage.TailGeckoScales, typeof(TailGeckoScales) },
{ (int)Appendage.TailTuft, typeof(TailTuft) },
{ (int)Appendage.Whiskers, typeof(Whiskers) },
{ (int)Appendage.WingScales, typeof(WingScales) }
};
/// <summary>
/// For RainbowLizardState.FromString
/// </summary>
public static readonly Dictionary<string, Appendage> dictAppName = new Dictionary<string, Appendage>()
{
{ "Antennae", Appendage.Antennae },
{ "AxolotlGills", Appendage.AxolotlGills },
{ "BodyScales", Appendage.BodyScales },
{ "BumpHawk", Appendage.BumpHawk },
{ "JumpRings", Appendage.JumpRings },
{ "LongBodyScales", Appendage.LongBodyScales },
{ "LongHeadScales", Appendage.LongHeadScales },
{ "LongShoulderScales", Appendage.LongShoulderScales },
{ "ShortBodyScales", Appendage.ShortBodyScales },
{ "SpineSpikes", Appendage.SpineSpikes },
{ "TailFin", Appendage.TailFin },
{ "TailGeckoScales", Appendage.TailGeckoScales },
{ "TailTuft", Appendage.TailTuft },
{ "Whiskers", Appendage.Whiskers },
{ "WingScales", Appendage.WingScales }
};
public void BalanceFix()
{
float s = this.mobilityPreference[0] + this.mobilityPreference[1] + this.mobilityPreference[2] + this.mobilityPreference[3];
if (s > 2.4f)
{
s = 2.4f / s;
this.mobilityPreference[0] *= s;
this.mobilityPreference[1] *= s;
this.mobilityPreference[2] *= s;
}
s = (this.mobilityPreference[0] + this.mobilityPreference[1] + this.mobilityPreference[2]) / 3f + this.mobilityPreference[3];
if (s > 1.5f)
{
s = 1.5f / s;
this.mobilityPreference[3] *= s;
}
s = Mathf.Max(this.mobilityPreference);
if (s < 0.8f)
{
s = 0.8f / s;
this.mobilityPreference[0] *= s;
this.mobilityPreference[1] *= s;
this.mobilityPreference[2] *= s;
this.mobilityPreference[3] *= s;
}
this.mobilityPreference[0] = Mathf.Clamp01(this.mobilityPreference[0]);
this.mobilityPreference[1] = Mathf.Clamp01(this.mobilityPreference[1]);
this.mobilityPreference[2] = Mathf.Clamp01(this.mobilityPreference[2]);
this.mobilityPreference[3] = Mathf.Clamp01(this.mobilityPreference[3]);
s = Mathf.Max(this.mobilityPreference[0], this.mobilityPreference[1], this.mobilityPreference[2]);
if (s > this.mobilityPreference[3])
{
this.mobilityPreference[3] = Mathf.Max(this.mobilityPreference[3] - 0.6f, this.mobilityPreference[3] * 0.3f);
this.standardColor = new Color(this.mobilityPreference[0], this.mobilityPreference[1], this.mobilityPreference[2]);
}
else
{
this.mobilityPreference[0] *= 0.8f;
this.mobilityPreference[1] *= 0.8f;
this.mobilityPreference[2] *= 0.8f;
this.standardColor = new Color(this.mobilityPreference[3], this.mobilityPreference[1], this.mobilityPreference[2]);
}
RXColorHSL c = RXColor.HSLFromColor(this.standardColor);
c.s = Mathf.Clamp01(c.s - Mathf.Pow(Mathf.Abs(this.aggressive) / 10f, 2f));
c.l = Mathf.Clamp01(c.l + Mathf.Pow(this.aggressive / 10f, 2f) / 4f);
this.standardColor = RXColor.ColorFromHSL(c);
}
/// <summary>
/// Run for lizard loaded from world file(completely new)
/// </summary>
public void Randomize()
{
float r = RainbowMod.config.LizardRandomizer; bool arena = this.lizard.room?.game.IsArenaSession == true;
Debug.Log(string.Concat("Before Randomized: ", this.mobilityPreference[0], "; ", this.mobilityPreference[1], "; ", this.mobilityPreference[2], "; ",
this.mobilityPreference[3], "; ", " (drk: ", this.darkness, "; agg: ", this.aggressive, ")"));
///this.BalanceFix();
RXColorHSL hslMobility = RXColor.HSLFromColor(
new Color(Mathf.Clamp01(this.mobilityPreference[0]), Mathf.Clamp01(this.mobilityPreference[1]), Mathf.Clamp01(this.mobilityPreference[2])));
hslMobility.h = Custom.WrappedRandomVariation(hslMobility.h, r, 0.5f);
hslMobility.s = 1f;
hslMobility.l = Custom.ClampedRandomVariation(hslMobility.l, r, 0.1f);
Color c = RXColor.ColorFromHSL(hslMobility);
this.mobilityPreference[0] = c.r;
this.mobilityPreference[1] = c.g;
this.mobilityPreference[2] = c.b;
this.mobilityPreference[3] = Mathf.Pow(Custom.ClampedRandomVariation(this.mobilityPreference[3], r * 0.4f, 0.1f), 2);
this.darkness = Custom.ClampedRandomVariation(this.darkness, arena ? 0.8f : 0.2f, 0.15f);
this.aggressive = Mathf.Clamp(this.aggressive + r * Custom.RandomDeviation(arena ? 9.0f : 3.0f), -10.0f, 10.0f);
this.baseSpeed = Custom.RandomDeviation(0.5f) + 4.0f * Mathf.Clamp(Mathf.Pow(this.aggressive / 6f, 2), 0.8f, 1.2f);
this.BalanceFix();
Debug.Log(string.Concat("After Randomized: ", this.mobilityPreference[0], "; ", this.mobilityPreference[1], "; ", this.mobilityPreference[2], "; ",
this.mobilityPreference[3], " (drk: ", this.darkness, "; agg: ", this.aggressive, ")"));
this.ChangeTemplate();
}
public void ChangeTemplate(CreatureTemplate.Type newType = CreatureTemplate.Type.LizardTemplate)
{
if (newType == CreatureTemplate.Type.LizardTemplate)
{
float m = Mathf.Max(mobilityPreference);
if (m.Equals(mobilityPreference[0])) { newType = EnumExt_Rainbow.FormulatedClimbLizard; }
else if (m.Equals(mobilityPreference[1])) { newType = EnumExt_Rainbow.FormulatedGroundLizard; }
else if (m.Equals(mobilityPreference[2])) { newType = EnumExt_Rainbow.FormulatedWallLizard; }
else { newType = EnumExt_Rainbow.FormulatedWaterLizard; darkBody = UnityEngine.Random.value < 0.3f; }
}
if (this.template == newType && this.lizard.abstractCreature.creatureTemplate.type == newType)
{
return;
}
Debug.Log(string.Concat(this.template, " ", this.lizard.abstractCreature.ID, " is now ", newType.ToString(),
" (mobilityPref: ", this.mobilityPreference[0], "; ", this.mobilityPreference[1], "; ", this.mobilityPreference[2],
"/ ", this.mobilityPreference[3], ", agg:", this.aggressive, ")"));
this.lizard.abstractCreature.creatureTemplate = StaticWorld.GetCreatureTemplate(newType);
this.template = newType;
if (this.template == EnumExt_Rainbow.FormulatedGroundLizard)
{
this.headGraphics = new int[] { 1, 1, 1, 1, 1 };
}
else if (this.template == EnumExt_Rainbow.FormulatedWaterLizard)
{
this.headGraphics = new int[] { 2, 2, 2, 2, 2 };
}
else
{
this.headGraphics = new int[] { 0, 0, 0, 0, 0 };
}
if (this.State.Blind || this.State.Camoflague) { this.headGraphics[4] = 3; }
else if (this.aggressive > 6f) { this.headGraphics[1] = 1; this.headGraphics[2] = 1; this.headGraphics[4] = 1; }
else if (this.aggressive < -6f) { this.headGraphics[0] = 1; this.headGraphics[3] = 1; }
}
/// <summary>
/// Rainbow version of Lineage for a sudden tuch of death
/// </summary>
public void Mutate(int seed, bool dark)
{
if (this.State == null) { return; }
int seedBackup = UnityEngine.Random.seed;
UnityEngine.Random.seed = seed;
/// 0: Climb 1: Ground 2: Wall 3: Water
float lineage;
switch ((this.State as IRainbowState).killer)
{
case KillerType.Player: lineage = 1.5f; break;
case KillerType.Scavenger: lineage = 1f; break;
case KillerType.PredatorGround: lineage = -1f; break;
case KillerType.PredatorWater: lineage = -0.5f; break;
case KillerType.PredatorSky: lineage = -2f; break;
case KillerType.Brethern: lineage = 2f; break;
default: lineage = 0f; break;
}
switch ((this.State as IRainbowState).reason)
{
case DeathReason.Starved:
this.mobilityPreference[1] += 0.7f; this.aggressive += 2f; break;
case DeathReason.Drowned:
this.mobilityPreference[3] += 0.5f; break;
case DeathReason.Electrocuted:
case DeathReason.Exploded:
this.mobilityPreference[1] += 0.5f; this.aggressive -= 2f; break;
case DeathReason.Burned:
this.mobilityPreference[1] += 0.5f; break;
case DeathReason.Eaten:
this.mobilityPreference[1] += 0.5f; lineage -= 1f; break;
case DeathReason.Speared:
this.mobilityPreference[1] += 0.4f + lineage * 0.4f;
break;
case DeathReason.Fallen:
this.mobilityPreference[1] -= 0.5f;
this.mobilityPreference[2] += 0.2f + 0.4f * lineage; break;
}
this.aggressive += lineage * 2f;
if (dark) { this.darkness += 0.5f; } else { this.darkness -= 0.2f; }
if (this.mobilityPreference[0] > 1f) { float d = this.mobilityPreference[0] - 0.7f; this.mobilityPreference[1] += d; this.mobilityPreference[0] = 0.6f; }
if (this.mobilityPreference[2] > 1f) { float d = this.mobilityPreference[2] - 0.8f; this.mobilityPreference[2] = 0.8f; this.aggressive += d * 3f; }
if (this.mobilityPreference[3] > 1f) { float d = this.mobilityPreference[3] - 0.5f; this.mobilityPreference[0] += d / 3f; this.mobilityPreference[2] += d / 2f; this.mobilityPreference[3] = 0.5f; }
if (this.mobilityPreference[1] > 1f) { this.mobilityPreference[1] = 1.0f; } //add defensiveness
this.aggressive = Mathf.Clamp(this.aggressive, -10f, 10f);
this.BalanceFix();
this.ChangeTemplate();
UnityEngine.Random.seed = seedBackup;
}
public RainbowLizardBreedParams Clone()
{
RainbowLizardBreedParams p = new RainbowLizardBreedParams(this.template)
{
terrainSpeeds = this.terrainSpeeds,
biteDelay = this.biteDelay,
biteInFront = this.biteInFront,
biteHomingSpeed = this.biteHomingSpeed,
biteChance = this.biteChance,
biteRadBonus = Mathf.Min(this.aggressionCurveExponent, 15f), //Nerf Red's range for reasonable
attemptBiteRadius = this.aggressionCurveExponent,
getFreeBiteChance = this.getFreeBiteChance,
biteDamage = this.biteDamage,
biteDamageChance = this.biteDamageChance,
toughness = this.toughness,
stunToughness = this.stunToughness,
regainFootingCounter = this.regainFootingCounter,
baseSpeed = this.baseSpeed,
bodyMass = this.bodyMass,
bodySizeFac = this.bodySizeFac,
floorLeverage = this.floorLeverage,
maxMusclePower = this.maxMusclePower,
wiggleSpeed = this.wiggleSpeed,
wiggleDelay = this.wiggleDelay,
bodyStiffnes = this.bodyStiffnes,
swimSpeed = this.swimSpeed,
idleCounterSubtractWhenCloseToIdlePos = this.idleCounterSubtractWhenCloseToIdlePos,
danger = this.danger,
aggressionCurveExponent = this.aggressionCurveExponent,
headShieldAngle = this.headShieldAngle,
canExitLounge = this.canExitLounge,
canExitLoungeWarmUp = this.canExitLoungeWarmUp,
findLoungeDirection = this.findLoungeDirection,
loungeDistance = this.loungeDistance,
preLoungeCrouch = this.preLoungeCrouch,
preLoungeCrouchMovement = this.preLoungeCrouchMovement,
loungeSpeed = this.loungeSpeed,
loungeMaximumFrames = this.loungeMaximumFrames,
loungePropulsionFrames = this.loungePropulsionFrames,
loungeJumpyness = this.loungeJumpyness,
loungeDelay = this.loungeDelay,
riskOfDoubleLoungeDelay = this.riskOfDoubleLoungeDelay,
postLoungeStun = this.postLoungeStun,
loungeTendensy = this.loungeTendensy,
perfectVisionAngle = this.perfectVisionAngle,
periferalVisionAngle = this.periferalVisionAngle,
biteDominance = this.biteDominance,
limbSize = this.limbSize,
stepLength = this.stepLength,
liftFeet = this.liftFeet,
feetDown = this.feetDown,
noGripSpeed = this.noGripSpeed,
limbSpeed = this.limbSpeed,
limbQuickness = this.limbQuickness,
limbGripDelay = this.limbGripDelay,
smoothenLegMovement = this.smoothenLegMovement,
legPairDisplacement = this.legPairDisplacement,
standardColor = this.standardColor,
walkBob = this.walkBob,
tailSegments = this.tailSegments,
tailStiffness = this.tailStiffness,
tailStiffnessDecline = this.tailStiffnessDecline,
tailLengthFactor = this.tailLengthFactor,
tailColorationStart = this.tailColorationStart,
tailColorationExponent = this.tailColorationExponent,
headSize = this.headSize,
neckStiffness = this.neckStiffness,
//headGraphics = new int[5],
jawOpenAngle = this.jawOpenAngle,
jawOpenLowerJawFac = this.jawOpenLowerJawFac,
jawOpenMoveJawsApart = this.jawOpenMoveJawsApart,
framesBetweenLookFocusChange = this.framesBetweenLookFocusChange,
tamingDifficulty = this.tamingDifficulty,
tongue = this.tongue,
//mobilityPreference = new float[4],
template = this.template,
darkness = this.darkness,
aggressive = this.aggressive,
lizard = this.lizard
};
/*
p.mobilityPreference[0] = this.mobilityPreference[0];
p.mobilityPreference[1] = this.mobilityPreference[1];
p.mobilityPreference[2] = this.mobilityPreference[2];
p.mobilityPreference[3] = this.mobilityPreference[3];*/
p.mobilityPreference = (float[])this.mobilityPreference.Clone();
p.headGraphics = (int[])this.headGraphics.Clone();
return p;
}
object ICloneable.Clone()
{
return this.Clone();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Xml;
namespace pjank.BossaAPI.Fixml
{
public enum TradingSessionStatus
{
Unknown = 0, // nieznany
Halted = 1, // wstrzymany
Open = 2, // otwarcie
Closed = 3, // zamknięcie
PreOpen = 4, // przed otwarciem
PreClose = 5, // przed zamknięciem
RequestRejected = 6 // odrzucenie żądania
}
internal static class TrdgSesStatusUtil
{
private static Dictionary<string, TradingSessionStatus> dict =
new Dictionary<string, TradingSessionStatus> {
// tu dopisać inne, nienumeryczne statusy zwracane przez NOLa
};
public static TradingSessionStatus Read(XmlElement xml, string name)
{
string str = FixmlUtil.ReadString(xml, name, true);
if (str == null) return TradingSessionStatus.Unknown;
uint number;
if (uint.TryParse(str, out number))
if (Enum.IsDefined(typeof(TradingSessionStatus), (TradingSessionStatus)number))
return (TradingSessionStatus)number;
if (!dict.ContainsKey(str))
FixmlUtil.Error(xml, name, str, "- unknown TradingSessionStatus");
return dict[str];
}
}
}
|
using System;
namespace Shared
{
public class CheckRequest
{
public string Domain { get; set; }
public int? Rank { get; set; }
}
public class LogoRequest
{
public Uri Uri { get; set; }
}
public class ScoreRequest
{
public Range Range { get; set; }
}
public class Range
{
public int From { get; set; }
public int To { get; set; }
}
} |
using System;
using UnityAtoms.BaseAtoms;
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Reference of type `GameObject`. Inherits from `AtomReference<GameObject, GameObjectPair, GameObjectConstant, GameObjectVariable, GameObjectEvent, GameObjectPairEvent, GameObjectGameObjectFunction, GameObjectVariableInstancer, AtomCollection, AtomList>`.
/// </summary>
[Serializable]
public sealed class GameObjectReference : AtomReference<
GameObject,
GameObjectPair,
GameObjectConstant,
GameObjectVariable,
GameObjectEvent,
GameObjectPairEvent,
GameObjectGameObjectFunction,
GameObjectVariableInstancer>, IEquatable<GameObjectReference>
{
public GameObjectReference() : base() { }
public GameObjectReference(GameObject value) : base(value) { }
public bool Equals(GameObjectReference other) { return base.Equals(other); }
protected override bool ValueEquals(GameObject other)
{
return Value == other;
}
}
}
|
// using Nancy;
// using System;
// using System.Collections.Generic;
// using WordCounter.Objects;
//
// namespace WordCounter
// {
// public class HomeModule : NancyModule
// {
// public HomeModule()
// {
// Get["/"] = _ =>{
// return View["index.cshtml"];
// };
// }
// }
// }
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Btf.Utilities.Hash
{
public interface IPasswordHash
{
string GetHash(string password);
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Entity;
using System.Globalization;
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 Schedule.Models;
using Task = Schedule.Models.Task;
namespace Schedule
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
TaskContext _context = new TaskContext();
public MainWindow()
{
InitializeComponent();
_context.Tasks.Load();
dataGrid1.ItemsSource = _context.Tasks.Local.ToBindingList();
ICollectionView cvTasks = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource);
if (cvTasks != null && cvTasks.CanGroup == true)
{
cvTasks.GroupDescriptions.Clear();
cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("ProjectName"));
cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("Complete"));
}
}
public void UnGroupBtn_Click(object sender, RoutedEventArgs e)
{
ICollectionView cvTasks = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource);
if (cvTasks != null)
{
cvTasks.GroupDescriptions.Clear();
}
}
public void GroupBtn_Click(object sender, RoutedEventArgs e)
{
ICollectionView cvTasks = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource);
if (cvTasks != null && cvTasks.CanGroup == true)
{
cvTasks.GroupDescriptions.Clear();
cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("ProjectName"));
cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("Complete"));
}
}
public void AddNewTask_Click(object sender, RoutedEventArgs e)
{
AddWindow addWindow = new AddWindow();
if (addWindow.ShowDialog() == true)
{
string projectName = addWindow.projectName.Text;
string taskName = addWindow.taskName.Text;
DateTime dueDate = addWindow.dueDate.SelectedDate ?? DateTime.Now;
bool complete = addWindow.complete.IsChecked ?? false;
if (!string.IsNullOrEmpty(projectName) && !string.IsNullOrEmpty(taskName))
{
Task newTask = new Task();
newTask.ProjectName = projectName;
newTask.TaskName = taskName;
newTask.DueDate = dueDate;
newTask.Complete = complete;
_context.Tasks.Add(newTask);
_context.SaveChanges();
dataGrid1.Items.Refresh();
MessageBox.Show("New assignments added");
}
else
MessageBox.Show("Please, enter name of task or project");
}
else
{
return;
}
}
public void DeleteTasks_Click(object sender, RoutedEventArgs e)
{
if (dataGrid1.SelectedItems.Count > 0)
{
for (int i = 0; i < dataGrid1.SelectedItems.Count; )
{
if (dataGrid1.SelectedItems[i] is Task task)
{
_context.Tasks.Remove(task);
_context.SaveChanges();
}
}
}
}
}
public class CompleteConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool complete = (bool)value;
if (complete)
{
return "Complete";
}
else
{
return "Active";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string strComplete = (string)value;
if (strComplete == "Complete")
{
return true;
}
else
return false;
}
}
}
|
using Cs_Notas.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Infra.Data.EntityConfig
{
public class ComplementosConfig: EntityTypeConfiguration<Complementos>
{
public ComplementosConfig()
{
HasKey(p => p.ComplementoId);
Property(p => p.ComplementoId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(p => p.Data)
.HasColumnType("Date")
.IsOptional();
Property(p => p.Cct)
.HasMaxLength(9)
.IsOptional();
Property(p => p.TipoCobranca)
.HasMaxLength(2)
.IsOptional();
Property(p => p.IdEscritura)
.IsOptional();
Property(p => p.DataPratica)
.HasColumnType("Date")
.IsOptional();
Property(p => p.Livro)
.IsOptional();
Property(p => p.FolhaInicio)
.IsOptional();
Property(p => p.FolhaFim)
.IsOptional();
Property(p => p.NumeroAto)
.IsOptional();
Property(p => p.Selo)
.HasMaxLength(9)
.IsOptional();
Property(p => p.Aleatorio)
.HasMaxLength(3)
.IsOptional();
Property(p => p.Emolumentos)
.IsOptional();
Property(p => p.Fetj)
.IsOptional();
Property(p => p.Fundperj)
.IsOptional();
Property(p => p.Funprj)
.IsOptional();
Property(p => p.Funarpen)
.IsOptional();
Property(p => p.Pmcmv)
.IsOptional();
Property(p => p.Iss)
.IsOptional();
Property(p => p.Total)
.IsOptional();
Property(p => p.NomeEscrevente)
.HasMaxLength(40)
.IsOptional();
Property(p => p.CpfEscrevente)
.HasMaxLength(11)
.IsOptional();
Property(p => p.Enviado)
.HasMaxLength(1)
.IsOptional();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.