text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core
{
/// <summary>
/// Parse the commandline arg input
/// Result:
/// 1. Exception flags -- record whether exception has been raised
/// CommandLegal -- 结果合法(允许duplicate
/// CommandDupli -- 结果中有重复的cmd,无其他语法错误,可以选择使用去掉重复后的list作为算法模块的输入 ///
/// 2. ParsedCommands -- store the parsed commands
/// 3. DistinctCommand -- store distinct version result (去掉重复,若无则 = parsed command
/// 外部调用:
/// var parser = new CommandArgInputParser();
/// parser.parse();
/// </summary>
public class CommandArgInputParser
{
public readonly string FilePath;
public bool CommandLegal
{
get;
private set;
}
public bool CommandDuplicated
{
get;
private set;
}
public string[] InitialCommands
{
get;
private set;
}
public List<string> LegalKeyWordCommands
{
get;
private set;
}
private List<Command> ParsedCommands;
private List<Command> DistinctParsedCommands;
#region ExceptionFlags
public bool IllegalCommandKeyWord
{
get;
private set;
}
public bool IllegalKeyWordCombination
{
get;
private set;
}
public bool MissingMustContainedKeyWord
{
get;
private set;
}
public bool InvalidStartChar
{
get;
private set;
}
public bool StartCharMissing
{
get;
private set;
}
public bool InvalidEndChar
{
get;
private set;
}
public bool EndCharMissing
{
get;
private set;
}
public bool UnExpectedChar
{
get;
private set;
}
#endregion
public CommandArgInputParser(string[] args)
{
FilePath = args[args.Length - 1];
//slice input arg
InitialCommands = new string[args.Length - 1];
Array.ConstrainedCopy(args,0,InitialCommands,0,args.Length -1);
LegalKeyWordCommands = new List<string>();
ParsedCommands = new List<Command>();
DistinctParsedCommands = new List<Command>();
CommandLegal = true;
CommandDuplicated = false;
#region Init exception flags
IllegalCommandKeyWord = false;
IllegalKeyWordCombination = false;
MissingMustContainedKeyWord = false;
StartCharMissing = false;
EndCharMissing = false;
UnExpectedChar = false;
#endregion
}
//将不合法的关键词去掉,结果存入LegalKeyWordCommands
//例 "-c -w -x -t [ a -r" --> "-c -w -t a -r",若有不合法关键字,CommandLegal = false
public void GetLegalKeyWords()
{
string ExtraExceptionMessage = "-->";
foreach (string Word in InitialCommands)
{
if (Command.LegalCommands.Contains(Word))
{
LegalKeyWordCommands.Add(Word);
}
else
{
bool IllegalKeywordException = false;
if (Word.Length == 1)
{
char CharWord = Char.Parse(Word);
//rule out start or end char setting
if( !(( CharWord >= 'a' && CharWord <= 'z') || (CharWord >= 'A' && CharWord <= 'Z')))
{
IllegalKeywordException = true;
ExtraExceptionMessage += CharWord.ToString() + " ";
}
else
{
LegalKeyWordCommands.Add(CharWord.ToString());
}
}
else
{
IllegalKeywordException = true;
ExtraExceptionMessage += Word + " ";
}
if (IllegalKeywordException)
{
try
{
throw new IllegalCommandKeyWord();
}
catch(IllegalCommandKeyWord e)
{
Console.WriteLine(e.Message + ExtraExceptionMessage);
CommandLegal = false;
IllegalCommandKeyWord = true;
}
}
}
}
}
//在GetLegalKeyWords结果的基础上,检查
//1.是否有-c -w之一
//2.是否-c -w都有
//设置相应的flag,出现其一就把commandLegal = false
public void CheckCommandCombinationLegal()
{
//check combination
if(!(LegalKeyWordCommands.Contains("-c") || LegalKeyWordCommands.Contains("-w"))){
try
{
throw new MissingMustContainedKeyWord();
}
catch (MissingMustContainedKeyWord e){
Console.WriteLine(e.Message + "--> Should at least contain one of -c or -w command");
CommandLegal = false;
MissingMustContainedKeyWord = true;
}
}
else
{
if (LegalKeyWordCommands.Contains("-c") && LegalKeyWordCommands.Contains("-w"))
{
try
{
throw new IllegalKeyWordCombination();
}
catch(IllegalKeyWordCombination e)
{
Console.WriteLine(e.Message + "--> Should not contain both -c and -w command");
CommandLegal = false;
IllegalKeyWordCombination = true;
}
}
}
}
//在CheckCommandCombinationLegal结果基础上
//检查重复关键字
//生成ParsedCommands和DistinctCommand
public void FormatInitialList()
{
void HandleMissingCharException(string CurrentWord)
{
if (CurrentWord == "-h")
{
try
{
throw new StartCharMissing();
}
catch (StartCharMissing e)
{
Console.WriteLine(e.Message);
CommandLegal = false;
StartCharMissing = true;
}
}
else
{
try
{
throw new EndCharMissing();
}
catch (EndCharMissing e)
{
Console.WriteLine(e.Message);
CommandLegal = false;
EndCharMissing = true;
}
}
}
for(int i = 0; i < LegalKeyWordCommands.Count; i++)
{
string CurrentWord = LegalKeyWordCommands[i];
// is command
if (Command.LegalCommands.Contains(CurrentWord)){
//-t -h find next char
if ( CurrentWord == "-t" || CurrentWord == "-h")
{
//"-t" or "-h" at the end of the list(no char after the command)
if (i == LegalKeyWordCommands.Count - 1)
{
HandleMissingCharException(CurrentWord);
}
//try to get the char from next item
else
{
//next item after t h is also command
if (Command.LegalCommands.Contains(LegalKeyWordCommands[i + 1]))
{
HandleMissingCharException(CurrentWord);
continue;
}
//find legal char on next item(char has been filtered in GetLegalKeyWords func)
else
{
ParsedCommands.Add(new Command(CurrentWord, Char.Parse(LegalKeyWordCommands[i+1])));
i += 1;
}
}
}
//-w -c -r
else
{
ParsedCommands.Add(new Command(CurrentWord));
}
}
//single char exception
else
{
try
{
throw new UnExpectedChar();
}
catch (UnExpectedChar e)
{
Console.WriteLine(e.Message + "-->" + CurrentWord);
CommandLegal = false;
UnExpectedChar = true;
}
}
}
//check duplicate commands and build distinct list
foreach (Command ParsedCommand in ParsedCommands)
{
int Count = 0;
if(ParsedCommand.CommandString != "-t" && ParsedCommand.CommandString != "-h")
{
foreach (Command parsedCommand in ParsedCommands)
{
if (ParsedCommand.Equals(parsedCommand))
{
Count += 1;
}
}
if (!DistinctParsedCommands.Contains(ParsedCommand))
{
DistinctParsedCommands.Add(ParsedCommand);
}
}
else
{
foreach (Command parsedCommand in ParsedCommands)
{
if (parsedCommand.CommandString == ParsedCommand.CommandString)
{
Count += 1;
}
if (Count == 1)
{
if (parsedCommand.Equals(ParsedCommand) && !DistinctParsedCommands.Contains(ParsedCommand))
{
DistinctParsedCommands.Add(ParsedCommand);
}
}
}
}
if(Count > 1)
{
try
{
throw new DuplicateKeyCommand();
}
catch (DuplicateKeyCommand e)
{
Console.WriteLine(e.Message + "-->" + ParsedCommand.CommandString + " " + ParsedCommand.StartOrEndChar);
CommandDuplicated = true;
}
}
}
}
public void Parse()
{
GetLegalKeyWords();
CheckCommandCombinationLegal();
FormatInitialList();
}
public List<Command> GetParsedCommandList(bool distinct = false)
{
if (distinct)
{
return DistinctParsedCommands;
}
else
{
return ParsedCommands;
}
}
public static string ConvertCommandListToString(List<Command> CommandList)
{
string WholeCommandString = "";
foreach (Command command in CommandList)
{
WholeCommandString += command.CommandString + " ";
if (command.StartOrEndChar != '\0')
{
WholeCommandString += command.StartOrEndChar.ToString() + " ";
}
}
return WholeCommandString;
}
public static List<string> ConvertCommandListToList(List<Command> CommandList)
{
List<string> CommandStringList = new List<string>();
foreach (Command command in CommandList)
{
CommandStringList.Add(command.CommandString);
if(command.StartOrEndChar != '\0')
{
CommandStringList.Add(command.StartOrEndChar.ToString());
}
}
return CommandStringList;
}
}
//命令类,"-w" "-c" "-r" "-t EndChar" "-h StartChar"之一
public class Command
{
public static readonly string[] LegalCommands = { "-w", "-c", "-r", "-t", "-h" };
public readonly string CommandString;
public readonly char StartOrEndChar;
public Command(string _CommandString, char _StartOrEndChar = '\0')
{
CommandString = _CommandString;
StartOrEndChar = _StartOrEndChar;
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
else
{
Command AnotherCommand = obj as Command;
if(AnotherCommand == null)
{
return false;
}
return (CommandString == AnotherCommand.CommandString && StartOrEndChar == AnotherCommand.StartOrEndChar);
}
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace Checkout.Payment.AcquiringBankMock.Application.Validations
{
public class CurrencyAttribute : ValidationAttribute
{
enum ValidCurrencies
{
USD,
EUR,
GBP
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return new ValidationResult("Currency is required");
}
if (Enum.TryParse(value.ToString(), out ValidCurrencies result))
{
return ValidationResult.Success;
}
return new ValidationResult($"Currency {value} is invalid");
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] Bullet bulletPrefab;
[SerializeField] float thrustSpeed = 5.0f;
[SerializeField] float turnSpeed = 1.0f;
[SerializeField] ParticleSystem fuelFX;
private bool _trusting;
private float _turnDirection;
private Rigidbody2D _rigidBody;
private void Awake()
{
_rigidBody = GetComponent<Rigidbody2D>();
}
private void Update()
{
PlayerMovement();
PlayerShoot();
}
private void PlayerShoot()
{
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();
}
}
private void PlayerMovement()
{
_trusting = (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow));
fuelFX.Play();
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
_turnDirection = 1.0f;
}
else if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
_turnDirection = -1.0f;
}
else
{
_turnDirection = 0;
fuelFX.Stop();
}
}
private void FixedUpdate()
{
PlayerTurn();
}
private void PlayerTurn()
{
if (_trusting)
{
_rigidBody.AddForce(transform.up * thrustSpeed);
}
if (_turnDirection != 0)
{
_rigidBody.AddTorque(_turnDirection * turnSpeed);
}
}
private void Shoot()
{
var bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
bullet.Project(transform.up);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Asteroid")
{
_rigidBody.velocity = Vector3.zero;
_rigidBody.angularVelocity = 0;
gameObject.SetActive(false);
FindObjectOfType<GameManager>().PlayerDead();
}
if (collision.gameObject.tag == "Bullet")
{
Debug.Log("Te pego un balaso el UFO");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using BookManagementApp.DAL;
using BookManagementApp.Models;
namespace BookManagementApp.Controllers
{
public class DebtsController : Controller
{
private BookContext db = new BookContext();
public ActionResult Index()
{
ViewBag.publishers = new SelectList(db.Publishers, "ID", "Name");
return View();
}
[HttpPost]
public ActionResult Index(int publisherID)
{
ViewBag.publishers = new SelectList(db.Publishers, "ID", "Name");
// borrow AgencyBookDebt model to store books debt
List<AgencyBookDebt> bookDebts = new List<AgencyBookDebt>();
if (!string.IsNullOrWhiteSpace(Request.Form["publisherID"]))
{
publisherID = Convert.ToInt32(Request.Form["publisherID"]);
DateTime filterDate = DateTime.Now;
if (!string.IsNullOrWhiteSpace(Request.Form["date"]))
{
var tempDate = Request.Form["date"].ToString();
TimeSpan time = new TimeSpan(23, 59, 59);
filterDate = DateTime.Parse(tempDate).Add(time);
}
int totalDebt = 0;
int totalAgencyPay = 0;
List<Receipt> receipts = db.Receipts
.Where(s => DbFunctions.TruncateTime(s.Date) <= filterDate
&& s.PublisherID == publisherID
)
.Include(s => s.ReceiptDetails)
.ToList();
List<AgencyReport> agencyReports = db.AgencyReports
.Where(s => DbFunctions.TruncateTime(s.Date) <= filterDate)
.Include(s=>s.AgencyReportDetails)
.ToList();
foreach (var x in receipts)
{
totalDebt += x.Total;
List<ReceiptDetail> receiptDetails = db.ReceiptDetails
.Where(s => s.ReceiptID == x.ID)
.Include(s => s.Book)
.ToList();
//return Json(receiptDetails, JsonRequestBehavior.AllowGet);
foreach (ReceiptDetail y in receiptDetails)
{
var bookDebt = bookDebts.Find(s => s.BookID == y.Book.ID);
if (bookDebt != null)
{
// if book exists, increase quantity
bookDebts.Find(s => s.BookID == y.Book.ID).Quantity += y.Quantity;
}
else
{
AgencyBookDebt a = new AgencyBookDebt()
{
BookID = y.BookID,
Quantity = y.Quantity,
Book = y.Book
};
bookDebts.Add(a);
}
}
}
foreach(AgencyReport x in agencyReports)
{
foreach(AgencyReportDetail y in x.AgencyReportDetails)
{
if(y.Book.PublisherID == publisherID)
{
totalAgencyPay += (y.Quantity * y.UnitPrice);
}
}
}
ViewBag.totalDebt = totalDebt;
ViewBag.totalAgencyPay = totalAgencyPay;
ViewBag.date = filterDate;
}
return View(bookDebts);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System.Text.Json.Serialization;
namespace PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json;
internal sealed class JsonDeletePmsIncomingMessage : JsonPacket
{
[JsonPropertyName("pm_array")]
public IReadOnlyCollection<uint> PMs { get; set; }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.CompilerServices;
using ERP_Palmeiras_LA.Core;
using ERP_Palmeiras_LA.Models;
using System.Data;
namespace ERP_Palmeiras_LA.Models.Facade
{
public partial class LogisticaAbastecimento
{
public void CriarCompraEquipamento(SolicitacaoCompraEquipamento s, DateTime dataPrevista)
{
s = model.TblSolicitacoesCompraEquipamento.Attach(s);
CompraEquipamento c = new CompraEquipamento();
c.DataPrevista = dataPrevista.Ticks;
c.Status = StatusCompra.COMPRA_SOLICITADA;
c.SolicitacaoCompraEquipamento = s;
s.CompraEquipamento = c;
model.TblCompraEquipamento.Add(c);
model.SaveChanges();
SolicitarCompra(c);
}
public void SolicitarCompra(CompraEquipamento c)
{
model.TblCompraEquipamento.Attach(c);
bool compraExternaSuccess = finClient.comprarEquipamento(
c.SolicitacaoCompraEquipamento.Equipamento.Nome,
c.SolicitacaoCompraEquipamento.Equipamento.Descricao,
c.SolicitacaoCompraEquipamento.Equipamento.NumeroSerie,
DateTime.Now, // quero comprar AGORA né?
c.SolicitacaoCompraEquipamento.Preco,
c.SolicitacaoCompraEquipamento.Equipamento.Fabricante.Banco.ToString(),
c.SolicitacaoCompraEquipamento.Equipamento.Fabricante.Agencia,
c.SolicitacaoCompraEquipamento.Equipamento.Fabricante.ContaCorrente,
c.Id);
if (!compraExternaSuccess)
{
c.Status = StatusCompra.ERRO_ORDEM_COMPRA;
}
else
{
c.Status = StatusCompra.COMPRA_SOLICITADA;
}
model.Entry(c).State = EntityState.Modified;
model.SaveChanges();
}
public void AlterarCompraEquipamento(CompraEquipamento c)
{
model.TblCompraEquipamento.Attach(c);
model.Entry(c).State = EntityState.Modified;
model.SaveChanges();
}
public CompraEquipamento BuscarCompraEquipamento(int id)
{
return model.TblCompraEquipamento.Find(id);
}
public IEnumerable<CompraEquipamento> BuscarComprasEquipamento()
{
return model.TblCompraEquipamento.Where<CompraEquipamento>(c => true);
}
public IEnumerable<CompraEquipamento> BuscarComprasEquipamento(StatusCompra status)
{
return model.TblCompraEquipamento.Where<CompraEquipamento>(c => c.Status.Value == (int)status);
}
}
} |
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using MyTestLib;
namespace WebMvc.Events
{
public class MyChunkingCookieManager : ICookieManager
{
private readonly ChunkingCookieManager _cookieManager;
public MyChunkingCookieManager()
{
_cookieManager = new ChunkingCookieManager();
}
public string GetRequestCookie(HttpContext context, string key)
{
return _cookieManager.GetRequestCookie(context, key);
}
public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
{
_cookieManager.AppendResponseCookie(context, key, value, options);
}
public void DeleteCookie(HttpContext context, string key, CookieOptions options)
{
var i = new FourSeven();
_cookieManager.DeleteCookie(context, key, options);
}
}
} |
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.IO;
using System.Data.SqlClient;
using System.Configuration;
namespace City_Gym // Ruth Davis 4201345 //
{
public partial class Membership_Form : Form
{
public Membership_Form()
{
InitializeComponent();
}
// code for the Exit Button
private void btnExit_Click(object sender, EventArgs e)
{
string message = "Are you sure you want to exit the programme"; // message to appear in the message box for the user
string title = "Exit"; // title of the message box
MessageBoxButtons buttons = MessageBoxButtons.YesNo; // assign buttons to the message box for the user to choose from
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning); // declare and initialise a DiaglogResult variable to show a message box
// to the user with the message, messagebox title, buttons and an exclamation
if (result == DialogResult.Yes) // point warning icon to the user. Variable capture user button choice
{
Application.Exit(); // if the user selects the yes button the application will be closed
} // if the user selects the no button the messagebox will close and the user will be able to
} // continue with the form and choose another option.
// Code for the Main Menu Button
private void btnMain_Click(object sender, EventArgs e)
{
MainMenu m = new MainMenu(); // return to the main menu and close this form
m.Show();
this.Close();
}
// code for Clear Form button
private void btnClear_Click(object sender, EventArgs e) // provide an option to clear all the fields and start over
{
textFirstName.Text = ""; // clear all text from the customer details section text fields
textLastName.Text = "";
textMobile.Text = "";
textAddress1.Text = "";
textAddress2.Text = "";
textCity.Text = "";
textPostCode.Text = "";
checkAccess.Checked = false; // clear all the optional extras section check boxes. Set to unchecked
checkPTrainer.Checked = false;
checkDiet.Checked = false;
checkVideo.Checked = false;
radioBasic.Checked = false; // clear all the membership details section radio buttons. Set to unchecked
radioRegular.Checked = false;
radioPremium.Checked = false;
radio3Mths.Checked = false;
radio12Mths.Checked = false;
radio24Mths.Checked = false;
radioWeekly.Checked = false; // clear all the payment details section radio buttons. Set to unchecked
radioMonthly.Checked = false;
radioDDYes.Checked = false;
radioDDNo.Checked = false;
textBaseCost.Text = ""; // clear all text from the Membership Costs section text boxes.
textDiscountAmount.Text = "";
textExtras.Text = "";
textNetCost.Text = "";
textRegPay.Text = "";
errorProvider1.SetError(labelFirstName, ""); // clear all error provider icons from the screen if there were any
errorProvider2.SetError(labelLastName, "");
errorProvider3.SetError(labelMobile, "");
errorProvider4.SetError(labelAddress1, "");
errorProvider5.SetError(labelCity, "");
errorProvider6.SetError(labelType, "");
errorProvider7.SetError(labelDuration, "");
errorProvider8.SetError(labelFrequency, "");
errorProvider9.SetError(labelDDebit, "");
errorProvider10.SetError(btnCalculate, "");
}
// code for the calculate button
private void btnCalculate_Click(object sender, EventArgs e)
{
//declare and initialise the local variables
decimal baseAmount = 0;
decimal duration = 0;
decimal debitDiscount = 0;
decimal totalDiscount;
decimal sevenDays = 0;
decimal pTrainer = 0;
decimal dietCons = 0;
decimal videos = 0;
decimal totalExtras;
decimal netMembership;
decimal regPay = 0;
// check membership type selected and apply the base cost
if (radioBasic.Checked) // set first condition for membership type - radio button basic is selected
{
baseAmount = 10; // set base amount as $10.00 per week
}
else if (radioRegular.Checked) // set second condition for membeshipi type - radio button regular is selected
{
baseAmount = 15; // set the base amount as $15.00 per week
}
else if (radioPremium.Checked) // set the third condition for membership type - radio button premium is selected
{
baseAmount = 20; // set the base amount as $20.00 per week
}
else
{
MembershipType(); // if no option selected call method MembershipType() to show the error message to the user
}
// check duration selected and assign the discount if applicable
if (radio3Mths.Checked) // set first condition for duration - 3 months
{
duration = 0; // discount is 0
}
else if (radio12Mths.Checked) // set second condition for duration - 12 months
{
duration = 2; // $2.00 per week discount assigned to the variable
}
else if (radio24Mths.Checked) // set third condition for duration - 24 months
{
duration = 5; // $5.00 per week discount assigned to the variable
}
else
{
Duration(); // if no option selected call method Duration() to show the error message to the user.
}
// check if user has opted in or out of payment by direct debit. Assign discount if applicable
if (radioDDYes.Checked) // set first condition for direct debit - yes
{
debitDiscount = baseAmount * 1 / 100; // assign 1% discount on the base cost to the variable debitDiscount
}
else if (radioDDNo.Checked) // set second condition for direct debit - no
{
debitDiscount = 0; // discount is 0
}
else
{
DirectDebit(); // if no option selected call method DirectDebit() to show the error message to the user.
}
// check for optional extras selected by user and assign costs if applicable.
if (checkAccess.Checked) // set condition for check box for 24hr/7day access selected
{
sevenDays = 1; // assign cost of $1.00 per week to the variable
}
else
{
// do nothing // if not selected do nothing and original assigned value of $0 is applied
}
if (checkPTrainer.Checked) // set condition for check box for personal trainer selected
{
pTrainer = 20; // assign cost of $20.00 per week to the variable
}
else
{
// do nothing // if not selected do nothing and original assigned value of $0 is applied
}
if (checkDiet.Checked) // set condition for check box for diet consultation selected
{
dietCons = 20; // assign cost of $20.00 per week to the variable
}
else
{
//do nothing // if not selected do nothing and original assigned value of $0 is applied
}
if (checkVideo.Checked) // set condition for check box for online video access selected
{
videos = 2; // assign cost of $2.00 per week to the variable
}
else
{
// do nothing // if not selected do nothing and original assigned value of $0 is applied
}
// calculate the costs for extras, discounts and net cost
totalExtras = sevenDays + pTrainer + dietCons + videos; // calculate total of all optional extras selected
totalDiscount = duration + debitDiscount; // calculate total of all discounts applied
netMembership = (baseAmount - totalDiscount) + totalExtras; // deduct the value of the discounts from the base cost and then add the total of the
// optional extras to get the net membership cost
// check payment frequency selected and calculate the applicable weekly or monthly payment cost
if (radioWeekly.Checked) // set the first condition for frequency - weekly payment
{
regPay = netMembership; // cost is equal to net membership as this is calculated on a weekly basis
}
else if (radioMonthly.Checked) // set the second condition for frequency - monthly payment
{
regPay = (netMembership * 52) / 12; // calculate as weekly (net membership) x 52 weeks in the year. Then divide into
} // 12 equal payments to be made monthly
else
{
Frequency(); // if no option selected from this group box call method Frequency() to show the
} // error message to the user.
// display the results in the text boxes in the Membership Cost section
textBaseCost.Text = baseAmount.ToString("C"); // use ("C") to show as currency with $ sign and decimal places
textDiscountAmount.Text = totalDiscount.ToString("C");
textExtras.Text = totalExtras.ToString("C");
textNetCost.Text = netMembership.ToString("C");
textRegPay.Text = regPay.ToString("C");
}
// methods for validation of fields to ensure users have entered text and made selections where mandatory on the form. Set up error messages for missing information
private void textFirstName_Validating(object sender, CancelEventArgs e)
{
FirstName(); // call method for FirstName
}
private bool FirstName() // method for FirstName
{
bool flag = true; //declare and initialise variable
if (textFirstName.Text == "")
{
errorProvider1.SetError(labelFirstName, "Please enter your first name."); // if the text box is empty use error provider 1 to mark the first name label and show
flag = false;
}
else
{
errorProvider1.SetError(labelFirstName, ""); // if first name text box contains text do not show an error
}
return flag;
}
private void textLastName_Validating(object sender, CancelEventArgs e) // validating that user has entered text in the Last Name text box
{
Surname(); // call method for Surname
}
private bool Surname() // method for Surname
{
bool flag = true; //declare and initialise variable
if (textLastName.Text == "") // if the text box is empty use error provider 2 to mark the last name label and show
{ // message to user to enter name
errorProvider2.SetError(labelLastName, "Please enter your last name.");
flag = false;
}
else
{
errorProvider2.SetError(labelLastName, ""); // if last name text box contains text do not show an error
}
return flag;
}
private void textMobile_Validating(object sender, CancelEventArgs e) // validating that user has entered text in the Mobile text box
{
Mobile(); // call method for mobile
}
private bool Mobile() // method for Mobile
{
bool flag = true; // declare and initialise the variable
if (textMobile.Text == "")
{ // if the text box is empty use error provider 3 to mark the mobile label and show
// message to user to enter name
errorProvider3.SetError(labelMobile, "Please enter your mobile number.");
flag = false;
}
else
{
errorProvider3.SetError(labelMobile, ""); // if mobile text box contains text do not show an error
}
return flag;
}
private void textAddress1_Validating(object sender, CancelEventArgs e) // validating that user has entered text in the Address 1 text box
{
Address1(); // call method for Address1
}
private bool Address1() // method for Address1
{
bool flag = true; // declare and initialise the variable
if (textAddress1.Text == "")
{ // if the text box is empty use error provider 4 to mark the address 1 label and show
// message to user to enter name
errorProvider4.SetError(labelAddress1, "Please enter your address.");
flag = false;
}
else
{
errorProvider4.SetError(labelAddress1, ""); // if address 1 text box contains text do not show an error
}
return flag;
}
private void textCity_Validating(object sender, CancelEventArgs e) // validating that user has entered text in the City text box
{
City(); // call method for City
}
private bool City() // method for City
{
bool flag = true; // declare and initialise the variable
if (textCity.Text == "")
{ // if the text box is empty use error provider 5 to mark the City label and show
// message to user to enter name
errorProvider5.SetError(labelCity, "Please enter your city.");
flag = false;
}
else
{
errorProvider5.SetError(labelCity, ""); // if City text box contains text do not show an error
}
return flag;
}
private bool MembershipType() // method to show error message to user if no membership type has been selected
{
bool flag = true;
if (!radioBasic.Checked || !radioRegular.Checked || !radioPremium.Checked) // if no option selected from the group box set error provider 6 to mark the label
{ // Type and show the message to the user
errorProvider6.SetError(labelType, "Please select a membership type");
flag = false;
}
else
{
errorProvider6.SetError(labelType, ""); // if a radio button in this group has been selected do not show an error
}
return flag;
}
private bool Duration() // method to show error message to user if no duration has been selected
{
bool flag = true;
if (!radio3Mths.Checked || !radio12Mths.Checked || !radio24Mths.Checked) // if no option selected from the group box set error provider 7 to mark the label
{ // Duration and show the message to the user
errorProvider7.SetError(labelDuration, "Please select a membership duration.");
flag = false;
}
else
{
errorProvider7.SetError(labelDuration, ""); // if a radio button in this group has been selected do not show an error
}
return flag;
}
private bool Frequency() // method to show error message to user if no frequency has been selected
{
bool flag = true;
if (!radioWeekly.Checked || !radioMonthly.Checked) // if no option selected from the group box set error provider 8 to mark the label
{ // Frequency and show the message to the user
errorProvider8.SetError(labelFrequency, "Please select a payment frequency.");
flag = false;
}
else
{
errorProvider8.SetError(labelFrequency, ""); // if a radio button in this group has been selected do not show an error
}
return flag;
}
private bool DirectDebit() // method to show error message to user if user has not opted in or out of direct debit
{
bool flag = true;
if (!radioDDYes.Checked || !radioDDNo.Checked) // if no option selected from the group box set error provider 9 to mark the label
{ // DDebit and show the message to the user
errorProvider9.SetError(labelDDebit, "Please select Yes or No for payment by direct debit.");
flag = false;
}
else
{
errorProvider9.SetError(labelDDebit, ""); // if a radio button in this group has been selected do not show an error
}
return flag;
}
private void textBaseCost_Validating(object sender, CancelEventArgs e) // validate if the text box for base cost has text in it using metohd BaseAmount(). Do not need to validate
{ // all the cost text boxes on submission because if the user has clicked on the calculate button, all costing
BaseAmount(); // fields will have text. If the user has not clicked on calculate button, no costing fields will have text.
} // So only need to validate 1 of the costing text boxes for form submission.
private bool BaseAmount() // method to check for text in the base cost text box.
{
bool flag = true;
if (textBaseCost.Text == "") // if the base cost text box is empty set error provider 10 to mark the calculate
{ // button and show the error message to the user.
errorProvider10.SetError(btnCalculate, "Please click the calculate button to calculate your membership cost.");
flag = false;
}
else
{
errorProvider10.SetError(btnCalculate, ""); // if the text box contains text do not show an error
}
return flag;
}
private void membersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.membersBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.gymDataSet);
}
private void Membership_Form_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'gymDataSet.Members' table. You can move, or remove it, as needed.
this.membersTableAdapter.Fill(this.gymDataSet.Members);
radioBasic.Checked = false; // clear all the membership details section radio buttons. Set to unchecked
radioRegular.Checked = false; // so that nothing is selected by default
radioPremium.Checked = false;
radio3Mths.Checked = false;
radio12Mths.Checked = false;
radio24Mths.Checked = false;
radioWeekly.Checked = false; // clear all the payment details section radio buttons. Set to unchecked
radioMonthly.Checked = false; // so that nothing is selected by default
radioDDYes.Checked = false;
radioDDNo.Checked = false;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
// assign boolean variables to call the methods and validate fields have been completed before allowing submission and writing to text file
bool name = FirstName();
bool surname = Surname();
bool mobile = Mobile();
bool address = Address1();
bool city = City();
bool calculate = BaseAmount();
if (name && surname && mobile && address && city && calculate) // set condition if all boolean values true - will write to database
{
//database variables
string connectionString;
SqlConnection con;
SqlCommand insert;
string sql;
string dDebit = ""; // get values from the radio buttons for payment for direct debit
if (radioDDYes.Checked)
{
dDebit = "Yes"; // and create the string to write to the database
}
if (radioDDNo.Checked)
{
dDebit = "No";
}
string payFreq = ""; // get values from the radio buttons for payment frequency
if (radioWeekly.Checked)
{
payFreq = "Weekly"; // and create the string to write to the database
}
if (radioMonthly.Checked)
{
payFreq = "Monthly";
}
string Access = "null"; // get values from the check boxes for optional extras and create the string to write to the database
if (checkAccess.Checked)
{
Access = "24/7 Access"; // and create the string to write to the database
}
string trainer = "null";
if (checkPTrainer.Checked)
{
trainer = "Personal Trainer";
}
string diet = "null";
if (checkDiet.Checked)
{
diet = "Diet Consultation";
}
string video = "null";
if (checkVideo.Checked)
{
video = "Access Online Fitness Videos";
}
string date = ""; // get values from the radio buttons for duration
if (radio3Mths.Checked)
{
DateTime currentDateTime = DateTime.Now;
DateTime expiryDate = currentDateTime.AddMonths(3); // calculate the expiry date based on the duration selected
date = expiryDate.ToString("dd MMM yyyy"); // convert the date to a string to write to the database
}
if (radio12Mths.Checked)
{
DateTime currentDateTime = DateTime.Now;
DateTime expiryDate = currentDateTime.AddMonths(12);
date = expiryDate.ToString("dd MMM yyyy");
}
if (radio24Mths.Checked)
{
DateTime currentDateTime = DateTime.Now;
DateTime expiryDate = currentDateTime.AddMonths(24);
date = expiryDate.ToString("dd MMM yyyy");
}
int type = 0; // get values from the radio buttons for membership type
if (radioBasic.Checked)
{
type = 1; // // and create the integer to write to the database
}
if (radioRegular.Checked)
{
type = 2;
}
if (radioPremium.Checked)
{
type = 3;
}
// create the connection details and query to insert the new member data into the database
connectionString = ConfigurationManager.ConnectionStrings["City_Gym.Properties.Settings.GymConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
sql = "INSERT INTO Members (FirstName, LastName, AddressOne, AddressTwo, City, PostCode, Mobile, DirectDebit, PaymentFrequency, AllDayAccess, PersonalTrainer, DietConsultation, AccessOnlineFitnessVideos, MembershipExpiry, MembershipID) " +
"VALUES (@FirstName, @LastName, @AddressOne, @AddressTwo, @City, @PostCode, @Mobile, @DirectDebit, @PaymentFrequency, @AllDayAccess, @PersonalTrainer, @DietConsultation, @AccessOnlineFitnessVideos, @MembershipExpiry, @MembershipID)";
insert = new SqlCommand(sql, con);
insert.Parameters.AddWithValue("@FirstName", textFirstName.Text); // get the values to insert from the text boxes
insert.Parameters.AddWithValue("@LastName", textLastName.Text);
insert.Parameters.AddWithValue("@AddressOne", textAddress1.Text);
insert.Parameters.AddWithValue("@AddressTwo", textAddress2.Text);
insert.Parameters.AddWithValue("@City", textCity.Text);
insert.Parameters.AddWithValue("@PostCode", textPostCode.Text);
insert.Parameters.AddWithValue("@Mobile", textMobile.Text);
insert.Parameters.AddWithValue("@DirectDebit", dDebit); // get the values to insert from the variables created above
insert.Parameters.AddWithValue("@PaymentFrequency", payFreq);
insert.Parameters.AddWithValue("@AllDayAccess", Access);
insert.Parameters.AddWithValue("@PersonalTrainer", trainer);
insert.Parameters.AddWithValue("@DietConsultation", diet);
insert.Parameters.AddWithValue("@AccessOnlineFitnessVideos", video);
insert.Parameters.AddWithValue("@MembershipExpiry", date);
insert.Parameters.AddWithValue("@MembershipID", type);
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = insert;
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Thank you for registering.", "Registration Successful"); // show message box to confirm sucessful registration
insert.Dispose();
con.Close();
// clear the form so user can enter details of the next new user without closing the application.
textFirstName.Text = ""; // clear all text from the customer details section text fields
textLastName.Text = "";
textMobile.Text = "";
textAddress1.Text = "";
textAddress2.Text = "";
textCity.Text = "";
textPostCode.Text = "";
checkAccess.Checked = false; // clear all the optional extras section check boxes. Set to unchecked
checkPTrainer.Checked = false;
checkDiet.Checked = false;
checkVideo.Checked = false;
radioBasic.Checked = false; // clear all the membership details section radio buttons. Set to unchecked
radioRegular.Checked = false;
radioPremium.Checked = false;
radio3Mths.Checked = false;
radio12Mths.Checked = false;
radio24Mths.Checked = false;
radioWeekly.Checked = false; // clear all the payment details section radio buttons. Set to unchecked
radioMonthly.Checked = false;
radioDDYes.Checked = false;
radioDDNo.Checked = false;
textBaseCost.Text = ""; // clear all text from the Membership Costs section text boxes.
textDiscountAmount.Text = "";
textExtras.Text = "";
textNetCost.Text = "";
textRegPay.Text = "";
errorProvider1.SetError(labelFirstName, ""); // clear all error provider icons from the screen if there were any
errorProvider2.SetError(labelLastName, "");
errorProvider3.SetError(labelMobile, "");
errorProvider4.SetError(labelAddress1, "");
errorProvider5.SetError(labelCity, "");
errorProvider6.SetError(labelType, "");
errorProvider7.SetError(labelDuration, "");
errorProvider8.SetError(labelFrequency, "");
errorProvider9.SetError(labelDDebit, "");
errorProvider10.SetError(btnCalculate, "");
}
else
{
// do nothing
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace лаба_13
{
class AESFileManager
{
public static string ReadListFilesAndDirs(string nameDisk = "D")
{
DirectoryInfo disk = new DirectoryInfo(nameDisk + @":\");
string filesAndDirs = "";
foreach (var file in disk.GetFiles())
filesAndDirs += file + "; ";
foreach (var dir in disk.GetDirectories())
filesAndDirs += dir + "; ";
return "Папки и файлы на диске " + nameDisk + ": " + filesAndDirs;
AESLog.Writer("ReadListFilesAndDirs", nameDisk);
}
public static void CreateDirAndFile(string path = "")
{
try
{
Directory.CreateDirectory(path + "AESInspect");
StreamWriter writer = new StreamWriter(path + @"AESInspect\AESInspect.txt");
writer.WriteLine(ReadListFilesAndDirs("D"));
writer.Close();
AESLog.Writer("CreateDirAndFile", path, "AESInspect.txt");
File.Copy(path + @"AESInspect\AESInspect.txt", path + @"AESInspect\CopyAESInspect.txt");
File.Delete(path + @"AESInspect\AESInspect.txt");
}
catch(Exception e)
{
Console.WriteLine("Ошибка: {0}", e.Message);
}
}
public static void CopyDir(string path1, string exp)
{
if (Directory.Exists(path1))
{
try
{
DirectoryInfo dir1 = new DirectoryInfo(path1);
DirectoryInfo dir2 = Directory.CreateDirectory("AESFiles");
AESLog.Writer("CopyDir", path1, "AESFiles");
foreach (var x in dir1.GetFiles())
{
if(exp == Path.GetExtension(x.FullName))
x.CopyTo(dir2.FullName + @"\" + x.Name);
}
if (Directory.Exists("AESInspect"))
{
Directory.Move("AESFiles", @"AESInspect\AESFiles");
}
else
{
throw new Exception("There is no such directory!!!");
}
}
catch (Exception e)
{
Console.WriteLine("ОШИБКА CopyDir: " + e.Message);
}
}
else
{
throw new Exception("There is no such directory!!!");
}
}
public static void XreateZIP(string dir)
{
string zipName = @"HDVFiles.zip";
if (new DirectoryInfo("HDVInspect").GetFiles("*.zip").Length == 0)
{
ZipFile.CreateFromDirectory(dir, zipName);
AESLog.Writer("CrearteZip", dir, zipName);
DirectoryInfo direct = new DirectoryInfo(dir);
foreach (var innerFile in direct.GetFiles())
innerFile.Delete();
direct.Delete();
ZipFile.ExtractToDirectory(zipName, dir);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Musher.EchoNest.Models;
namespace Musher.Web.Models
{
public class GenresGenreViewModel
{
public Genre Genre { get; set; }
public List<Artist> Artists { get; set; }
public List<Genre> SimilarGenres { get; set; }
}
public class GenresIndexViewModel
{
[DisplayName("Genres")]
public List<Genre> Genres { get; set; } = new List<Genre>();
public List<Genre> GetRandomGenres(int count)
{
Random random = new Random();
return Genres.OrderBy(x => random.Next()).Take(count).ToList();
}
}
public class GenresArtistsViewModel
{
public string Genre { get; set; }
public List<Artist> Artists { get; set; } = new List<Artist>();
}
}
|
namespace Vantage.Automation.VaultUITest.Helpers
{
public static class ProjectSpecificConstants
{
public const string DatetimeFormatForGrid = "M/d/yyyy h:mm tt";
public const string DatetimeFormatForDateField = "M/d/yyyy hh:mm:ss tt";
}
}
|
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class LowStockLevel
{
public String ItemTitle;
public String ItemNumber;
public Int32 Quantity;
public Int32 MinimumLevel;
public Int32 InBooks;
public String Location;
}
} |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace NetFabric.Hyperlinq
{
public static partial class ArrayExtensions
{
[GeneratorMapping("TPredicate", "NetFabric.Hyperlinq.FunctionInWrapper<TSource, bool>")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpanWhereRefEnumerable<TSource, FunctionInWrapper<TSource, bool>> Where<TSource>(this ReadOnlySpan<TSource> source, FunctionIn<TSource, bool> predicate)
=> source.WhereRef(new FunctionInWrapper<TSource, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpanWhereRefEnumerable<TSource, TPredicate> WhereRef<TSource, TPredicate>(this ReadOnlySpan<TSource> source, TPredicate predicate = default)
where TPredicate : struct, IFunctionIn<TSource, bool>
=> new(source, predicate);
[GeneratorIgnore]
[StructLayout(LayoutKind.Auto)]
public readonly ref struct ReadOnlySpanWhereRefEnumerable<TSource, TPredicate>
where TPredicate : struct, IFunctionIn<TSource, bool>
{
internal readonly ReadOnlySpan<TSource> source;
internal readonly TPredicate predicate;
internal ReadOnlySpanWhereRefEnumerable(ReadOnlySpan<TSource> source, TPredicate predicate)
{
this.source = source;
this.predicate = predicate;
}
public readonly WhereReadOnlyRefEnumerator<TSource, TPredicate> GetEnumerator()
=> new(source, predicate);
public bool SequenceEqual(IEnumerable<TSource> other, IEqualityComparer<TSource>? comparer = null)
{
if (Utils.UseDefault(comparer))
{
var enumerator = GetEnumerator();
using var otherEnumerator = other.GetEnumerator();
while (true)
{
var thisEnded = !enumerator.MoveNext();
var otherEnded = !otherEnumerator.MoveNext();
if (thisEnded != otherEnded)
return false;
if (thisEnded)
return true;
if (!EqualityComparer<TSource>.Default.Equals(enumerator.Current, otherEnumerator.Current))
return false;
}
}
else
{
comparer ??= EqualityComparer<TSource>.Default;
var enumerator = GetEnumerator();
using var otherEnumerator = other.GetEnumerator();
while (true)
{
var thisEnded = !enumerator.MoveNext();
var otherEnded = !otherEnumerator.MoveNext();
if (thisEnded != otherEnded)
return false;
if (thisEnded)
return true;
if (!comparer.Equals(enumerator.Current, otherEnumerator.Current))
return false;
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<int, TPredicate> source)
where TPredicate : struct, IFunctionIn<int, bool>
=> source.source.SumRef<int, int, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<int?, TPredicate> source)
where TPredicate : struct, IFunctionIn<int?, bool>
=> source.source.SumRef<int?, int, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<long, TPredicate> source)
where TPredicate : struct, IFunctionIn<long, bool>
=> source.source.SumRef<long, long, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<long?, TPredicate> source)
where TPredicate : struct, IFunctionIn<long?, bool>
=> source.source.SumRef<long?, long, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<float, TPredicate> source)
where TPredicate : struct, IFunctionIn<float, bool>
=> source.source.SumRef<float, float, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<float?, TPredicate> source)
where TPredicate : struct, IFunctionIn<float?, bool>
=> source.source.SumRef<float?, float, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<double, TPredicate> source)
where TPredicate : struct, IFunctionIn<double, bool>
=> source.source.SumRef<double, double, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<double?, TPredicate> source)
where TPredicate : struct, IFunctionIn<double?, bool>
=> source.source.SumRef<double?, double, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static decimal Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<decimal, TPredicate> source)
where TPredicate : struct, IFunctionIn<decimal, bool>
=> source.source.SumRef<decimal, decimal, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static decimal Sum<TPredicate>(this ReadOnlySpanWhereRefEnumerable<decimal?, TPredicate> source)
where TPredicate : struct, IFunctionIn<decimal?, bool>
=> source.source.SumRef<decimal?, decimal, TPredicate>(source.predicate);
}
}
|
using Microsoft.Extensions.Configuration;
namespace Fonlow.Testing
{
public sealed class TestingSettings
{
private TestingSettings()
{
}
public static TestingSettings Instance { get { return Nested.instance; } }
private class Nested
{
static Nested()
{
}
static TestingSettings Create()
{
var obj = new TestingSettings();
var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
//var appSettingsSection = config.GetSection("Testing");
config.Bind("Testing", obj);//work only when properties are not with private setter.
//obj.ConfigurationRoot = config;
return obj;
}
internal static readonly TestingSettings instance = Create();
}
//public IConfigurationRoot ConfigurationRoot { get; set; }
public string DotNetServiceAssemblyPath { get; set; }
public string BaseUrl { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string HostSite { get; set; }
public string HostSiteApplicationPool { get; set; }
public string SlnRoot { get; set; }
public string SlnName { get; set; }
public UsernamePassword[] Users { get; set; }
}
public sealed class UsernamePassword
{
public string Username { get; set; }
public string Password { get; set; }
}
}
|
using Amazon.Suporte.Model;
namespace Amazon.Suporte.Services
{
public interface IProblemService
{
Problem CreateProblem(Problem problem);
Problem GetProblemByIdentificator(string identificator);
}
} |
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace PasswordCheck.Tests
{
public class ForbiddenPasswordServiceTests : IClassFixture<TestFixture>
{
private readonly IForbiddenPasswordService _forbiddenPasswordService;
public ForbiddenPasswordServiceTests(TestFixture testFixture)
{
_forbiddenPasswordService = testFixture.Host.Services.GetRequiredService<IForbiddenPasswordService>();
}
[Theory()]
[InlineData("Password!")]
[InlineData("Pa55word!")]
[InlineData("P@ssword!")]
[InlineData("P@55word!")]
public void ForbiddenPasswordsAreLoadedFromFile(string password)
{
_forbiddenPasswordService.IsPasswordForbidden(password).Should().BeTrue();
}
[Theory()]
[InlineData("forbidden")]
[InlineData("Forbidden")]
[InlineData("F0rb1dd3n")]
[InlineData("F0rb1dd3n!123")]
public void ForbiddenPasswordsAreLoadedFromConfig(string password)
{
_forbiddenPasswordService.IsPasswordForbidden(password).Should().BeTrue();
}
}
}
|
using System.Drawing;
using System.Windows.Forms;
public class TransparentPictureBox : Control
{
public TransparentPictureBox()
{
/*MouseMove += new MouseEventHandler(ReadOnlyRichTextBox_Mouse);
MouseDown += new MouseEventHandler(ReadOnlyRichTextBox_Mouse);
MouseUp += new MouseEventHandler(ReadOnlyRichTextBox_Mouse);*/
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Transparent;
//SizeMode = PictureBoxSizeMode.StretchImage;
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x20;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
//Do not paint background
//if (Image != null)
//Launcher.DebugMsg("test");
}
protected override void OnPaintBackground(PaintEventArgs e)
{
//if (BackgroundImage != null)
//BackgroundImage.Dispose();
//BackgroundImage = new Bitmap(Width, Height);
/*if (null != BackgroundImage)
{
Graphics g = Graphics.FromImage(BackgroundImage);
Rectangle rct = new Rectangle(0, 0, Width, Height);
g.DrawImage(BackgroundImage, rct);
g.Dispose();
//BackgroundImage.Dispose();
}*/
}
/*[DefaultValue(PictureBoxSizeMode.StretchImage)]
public new PictureBoxSizeMode SizeMode
{
get { return base.SizeMode; }
set { base.SizeMode = value; }
}*/
}
|
namespace SampleConsoleApplication.Importers
{
using System;
using System.IO;
public class EmpleesImporter : IImporter
{
public string Message
{
get { return "Importing Emploees"; }
}
public int Order
{
get { return 2; }
}
public Action<CompanyEntities, TextWriter> Get
{
get
{
return (db, tr) =>
{
};
}
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace RiverCrossPuzzle
{
public class Shoreline
{
private List<Occupant> _occupants = new List<Occupant>();
public IEnumerable<Occupant> Occupants
{
get { return _occupants; }
}
public void AddOccupant(Occupant occupant)
{
_occupants.Add(occupant);
ValidateOccupants();
}
private void ValidateOccupants()
{
var foxes = getOccupantsOfType<Fox>();
var ducks = getOccupantsOfType<Duck>();
var corns = getOccupantsOfType<Corn>();
var farmers = getOccupantsOfType<Farmer>();
if (!farmers.Any())
{
if (foxes.Any() && ducks.Any())
throw new OccupantAteTheOtherException();
if (ducks.Any() && foxes.Any() || (ducks.Any() && corns.Any()))
throw new OccupantAteTheOtherException();
if (corns.Any() && ducks.Any())
throw new OccupantAteTheOtherException();
}
}
private IEnumerable<Occupant> getOccupantsOfType<T>() where T : Occupant
{
return _occupants.Where(d => d.GetType() == typeof(T));
}
public void RemoveOccupant(Occupant occupant)
{
_occupants.Remove(occupant);
ValidateOccupants();
}
}
} |
using Microsoft.Data.Entity;
using Microsoft.Framework.Logging;
using SearchEng.Search.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SearchEng.Search.RepositoryExtensions
{
public class EFSearchRepository<T> : ISearchRepository<T> where T : class
{
protected DbSet<T> _Dbset { get; set; }
Func<T, string, bool> _SearchFunction { get; set; }
Func<T, string> _SuggestionFunction { get; set; }
public EFSearchRepository(DbContext db, Func<T,string, bool> searchFunction, Func<T, string> suggestionFunction)
{
if (db == null)
{
throw new NullReferenceException("DbContext must be implemented");
}
if (searchFunction == null)
{
throw new NullReferenceException("searchTerm must be implemented");
}
if (suggestionFunction == null)
{
throw new NullReferenceException("suggestionFunction must be implemented");
}
_Dbset = db.Set<T>();
_SearchFunction = searchFunction;
_SuggestionFunction = suggestionFunction;
}
public virtual IEnumerable<T> Results(string term)
{
if (!string.IsNullOrWhiteSpace(term))
{
return _Dbset.Where(p=> _SearchFunction.Invoke(p,term));
}
else return new List<T>();
}
public virtual IEnumerable<string> Suggestions(string term)
{
if (!string.IsNullOrWhiteSpace(term))
{
return Results(term).Select(_SuggestionFunction);
}
else return new List<string>();
}
public virtual Task<IEnumerable<string>> SuggestionsAsync(string term)
{
Task<IEnumerable<string>> suggestasync = Task<IEnumerable<string>>.Factory.StartNew(() => { return Suggestions(term); });
return suggestasync;
}
public virtual Task<IEnumerable<T>> ResultsAsync(string term)
{
Task<IEnumerable<T>> resultasync = Task<IEnumerable<T>>.Factory.StartNew(() => { return Results(term); });
return resultasync;
}
}
} |
using App.Entity;
using App.Entity.AttibutesProperty;
using App.Logic;
using App.Utilities.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace App.Utilities.Access
{
/// <seealso cref="System.Windows.Forms.Form" />
public partial class FormLogin : FormMaster
{
/// <summary>
/// The list configuration
/// </summary>
private List<ConfigurationAttributes> lstConfiguration = new List<ConfigurationAttributes>();
/// <summary>
/// The user remebered
/// </summary>
private UserBE UserRemebered = null;
/// <summary>
/// Initializes a new instance of the <see cref="FormLogin"/> class.
/// </summary>
public FormLogin()
{
try
{
new InstallClass();
}
catch (Exception ex)
{
MessageCustom.Show(ex.Message);
}
InitializeComponent();
}
/// <summary>
/// Handles the TextChanged event of the Control control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
public void Control_TextChanged(object sender, EventArgs e)
{
bool isCorrect = true;
foreach (var control in this.Controls)
{
if (control.GetType() == typeof(TextControl))
isCorrect = isCorrect && ((TextControl)control).ValueCorrect;
}
BtnLogin.Enabled = isCorrect;
}
/// <summary>
/// Handles the Click event of the BtnLogin control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
public void BtnLogin_Click(object sender, EventArgs e)
{
ContextVariables.CurrentUser =
new UserLC().Select(
string.Format("UPPER(UserName) = '{0}' AND Password = '{1}'",
UserNameText.TextSelected.ToUpper(),
UserPasswordText.TextSelected));
if (ContextVariables.CurrentUser == null)
{
MessageCustom.Show("Usuario o contraseña errados. \n Por favor intente de nuevo.", MessageType.Warning);
return;
}
RememberMeLC RememberMeLC = new RememberMeLC();
if (CbRememberMe.Checked)
{
var r =
new RememberMeLC().Select(
string.Format(
" UserID = '{0}'",
ContextVariables.CurrentUser.ID));
if (r == null)
RememberMeLC.Insert(
new RememberMeBE
{
UserID = ContextVariables.CurrentUser.ID,
UserName = ContextVariables.CurrentUser.UserName,
SaveDate = DateTime.Now
});
}
else
{
RememberMeLC.Delete(string.Format(" UserID = {0}", ContextVariables.CurrentUser.ID));
}
ContextVariables.CurrentRol =
new RolLC().Select(
string.Format(" ID = '{0}'",
ContextVariables.CurrentUser.RolId));
ContextVariables.Company = new CompanyLC().SelectAll().FirstOrDefault();
UserPasswordText.TextSelected = string.Empty;
Hide();
var frm = new FormMDI();
frm.StartPosition = FormStartPosition.CenterScreen;
frm.WindowState = FormWindowState.Normal;
frm.Text = ContextVariables.Company.Name;
frm.Show();
}
/// <summary>
/// Handles the Load event of the FormLogin control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void FormLogin_Load(object sender, EventArgs e)
{
Text = "Ingreso";
ContextVariables.CurrentUser = new UserBE();
lstConfiguration = ContextVariables.CurrentUser.GetConfiguration();
UserNameText.ConfigurationAttributes = lstConfiguration.First(c => c.PropertyName == "UserName");
UserPasswordText.ConfigurationAttributes = lstConfiguration.First(c => c.PropertyName == "Password");
var list = new RememberMeLC().SelectAll();
if (list.Count > 0)
{
RememberMeBE rememberMe = list.OrderBy(u => u.SaveDate).FirstOrDefault();
if (rememberMe != null)
{
UserRemebered =
new UserLC().Select(
string.Format(
" ID = '{0}'",
rememberMe.UserID));
if (UserRemebered.Photo != null)
PicBoxUser.BackgroundImage = new FileControl().ByteToImage(UserRemebered.Photo);
CbRememberMe.Checked = true;
UserNameText.TextSelected = UserRemebered.UserName;
UserPasswordText.TextSelected = string.Empty;
}
}
UserNameText.TextChange += Control_TextChanged;
UserPasswordText.TextChange += Control_TextChanged;
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
} |
using System;
namespace Breezy.Sdk
{
public class BreezyApiException : Exception
{
public BreezyApiException(string message) : base(message)
{
}
}
} |
using System.Collections.Generic;
using GameLoanManager.Domain.Enums;
namespace GameLoanManager.Domain.Entities
{
public class Game : Entity
{
public string Name { get; set; }
public EGameType Type { get; set; }
public string Description { get; set; }
public bool Available { get; set; }
// Game Owner
public long IdUser { get; set; }
public virtual User User { get; set; }
public virtual ICollection<LoanedGame> LoanedGames { get; set; }
}
}
|
using CDSShareLib;
using Newtonsoft.Json.Linq;
namespace IoTHubReceiver.Model
{
class EventMessageModel
{
public int MessageId { get; set; }
public int EventRuleId { get; set; }
public string EventRuleName { get; set; }
public string EventRuleDescription { get; set; }
public string TriggeredTime { get; set; }
public bool EventSent { get; set; }
public string MessageDocumentId { get; set; }
public JObject Payload { get; set; }
public EventMessageModel(EventRuleCatalog eventRuleCatalog,
string triggeredTime, bool eventSent,
string messageDocumentId, JObject payload)
{
MessageId = eventRuleCatalog.MessageCatalogId;
EventRuleId = eventRuleCatalog.Id;
EventRuleName = eventRuleCatalog.Name;
EventRuleDescription = eventRuleCatalog.Description;
TriggeredTime = triggeredTime;
EventSent = eventSent;
MessageDocumentId = messageDocumentId;
Payload = payload;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Advertisements;
using GoogleMobileAds.Api;
public class ScoreScreenButtonController : ScoreScreenBehavior
{
public void onShareButtonPressed()
{
}
public void onMainMenuButtonPressed()
{
if (Ad.Count == 3)
{
//// Unity Ads
//ShowOptions currentOptions = new ShowOptions();
//currentOptions.resultCallback = adVideoFinished;
//Advertisement.Show("endGame", currentOptions);
Game.Ad.RequestRewardBasedVideo();
//if (Game.Ad.isAdRewarded)
//{
// Debug.Log("Game.Ad.isAdRewarded: true");
//Game.Ad.isAdRewarded = false;
Ad.Count = 1;
//SceneManager.LoadScene(Game.Scenes.MainMenu);
//}
//else
//{
// Debug.Log("Game.Ad.isAdRewarded: false");
// SceneManager.LoadScene(Game.Scenes.ScoreScreen);
//}
}
else
{
Ad.Count++;
//SceneManager.LoadScene(Game.Scenes.MainMenu);
}
SceneManager.LoadScene(Game.Scenes.MainMenu);
}
//// Unity Ads
//void adVideoFinished(ShowResult result)
//{
// if (result == ShowResult.Finished)
// SceneManager.LoadScene(Game.Scenes.MainMenu);
// else
// SceneManager.LoadScene(Game.Scenes.ScoreScreen);
//}
void Start() { }
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebSqlServerDocumentator.Models;
using SqlServerDocumentator;
namespace WebSqlServerDocumentator.Controllers
{
public class HomeController : Controller
{
private IDocumentator _documentator;
public HomeController(IDocumentator documentator)
{
_documentator = documentator;
}
[Route("")]
public IActionResult Index()
{
return View(_documentator.GetServers());
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
using Babylips.DB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Babylips.Service.Services
{
public class srvCity : BaseService<City>, IBaseService<City>
{
}
}
|
namespace HH.RulesEngine.Core.Conditions
{
using HH.RulesEngine.Core.Interfaces;
public class Equals : ICondition
{
private readonly string _actual;
private readonly string _expected;
public Equals(string actual, string expected)
{
_actual = actual;
_expected = expected;
}
public bool IsSatisfied()
{
return _actual == _expected;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Autofac;
using Microsoft.Bot.Builder.Dialogs.Internals;
using Microsoft.Bot.Builder.Scorables;
using Microsoft.Bot.Connector;
using MeetingRoomBot.Middlewares;
namespace MeetingRoomBot.Modules
{
public class GlobalHandlerModule:Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder
.Register(c => new CancelScorable(c.Resolve<IDialogTask>()))
.As<IScorable<IActivity, double>>()
.InstancePerLifetimeScope();
}
}
} |
using System;
using System.Linq;
using System.Net.Http.Formatting;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Entities;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi.Filters;
using Umbraco.Core.Services;
using Umbraco.Web.Actions;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Trees
{
[UmbracoTreeAuthorize(Constants.Trees.Macros)]
[Tree(Constants.Applications.Settings, Constants.Trees.Macros, "Macros", sortOrder: 4)]
[PluginController("UmbracoTrees")]
[CoreTree(TreeGroup = Constants.Trees.Groups.Settings)]
public class MacrosTreeController : TreeController
{
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
var root = base.CreateRootNode(queryStrings);
//check if there are any macros
root.HasChildren = Services.MacroService.GetAll().Any();
return root;
}
protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
var nodes = new TreeNodeCollection();
if (id == Constants.System.Root.ToInvariantString())
{
foreach (var macro in Services.MacroService.GetAll())
{
nodes.Add(CreateTreeNode(
macro.Id.ToString(),
id,
queryStrings,
macro.Name,
"icon-settings-alt",
false,
//TODO: Rebuild the macro editor in angular, then we dont need to have this at all (which is just a path to the legacy editor)
"/" + queryStrings.GetValue<string>("application") + "/framed/" +
Uri.EscapeDataString("/umbraco/developer/macros/editMacro.aspx?macroID=" + macro.Id)));
}
}
return nodes;
}
protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
{
var menu = new MenuItemCollection();
if (id == Constants.System.Root.ToInvariantString())
{
//Create the normal create action
menu.Items.Add<ActionNew>(Services.TextService, opensDialog: true)
//Since we haven't implemented anything for macros in angular, this needs to be converted to
//use the legacy format
.ConvertLegacyMenuItem(null, "initmacros", queryStrings.GetValue<string>("application"));
//refresh action
menu.Items.Add(new RefreshNode(Services.TextService, true));
return menu;
}
var macro = Services.MacroService.GetById(int.Parse(id));
if (macro == null) return new MenuItemCollection();
//add delete option for all macros
menu.Items.Add<ActionDelete>(Services.TextService, opensDialog: true)
//Since we haven't implemented anything for macros in angular, this needs to be converted to
//use the legacy format
.ConvertLegacyMenuItem(new EntitySlim
{
Id = macro.Id,
Level = 1,
ParentId = -1,
Name = macro.Name
}, "macros", queryStrings.GetValue<string>("application"));
return menu;
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace Ambassador.Migrations
{
public partial class ratingOptional : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "OrganizationReviewOfEventRating",
table: "Events",
nullable: true);
migrationBuilder.AlterColumn<int>(
name: "AmbassadorReviewOfEventRating",
table: "Events",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "OrganizationReviewOfEventRating",
table: "Events",
nullable: false);
migrationBuilder.AlterColumn<int>(
name: "AmbassadorReviewOfEventRating",
table: "Events",
nullable: false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Sesi.WebsiteDaSaude.WebApi.Interfaces;
using Sesi.WebsiteDaSaude.WebApi.Models;
namespace Sesi.WebsiteDaSaude.WebApi.Repositories
{
public class LocalRepository : ILocalRepository
{
public Locais BuscarPorId (int id)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var localBuscado = ctx.Locais
.Include(x => x.IdTipoLocalNavigation)
.Include(x => x.IdBairroNavigation)
.FirstOrDefault(x => x.IdLocal == id);
if (localBuscado != null)
{
return localBuscado;
}
return null;
}
}
public List<Locais> BuscarPorNome(string nomeBuscado)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var lista = ctx.Locais
.Where(x => EF.Functions.Like(x.NomeLocal, $"%{nomeBuscado}%"))
.Include(x => x.IdTipoLocalNavigation)
.Include(x => x.IdBairroNavigation)
.ToList();
return lista;
}
}
public void Cadastrar (Locais local)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
if (local.Cep.Contains("-"))
{
local.Cep = local.Cep.Replace("-","");
}
ctx.Add(local);
ctx.SaveChanges();
}
}
public void Editar (Locais localPassado)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var localBuscado = ctx.Locais.FirstOrDefault(x => x.IdLocal == localPassado.IdLocal);
if (localBuscado == null)
{
throw new Exception("Local não encontrado.");
} else
{
localBuscado.IdTipoLocal = localPassado.IdTipoLocal;
localBuscado.NomeLocal = localPassado.NomeLocal;
localBuscado.Capacidade = localPassado.Capacidade;
localBuscado.Cep = localPassado.Cep;
localBuscado.IdBairro = localPassado.IdBairro;
localBuscado.Logradouro = localPassado.Logradouro;
localBuscado.Numero = localPassado.Numero;
localBuscado.Telefone = localPassado.Telefone;
if (localBuscado.Cep.Contains("-"))
{
localBuscado.Cep = localBuscado.Cep.Replace("-","");
}
ctx.Update(localBuscado);
ctx.SaveChanges();
}
}
}
public void Excluir (int id)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var localBuscado = ctx.Locais.FirstOrDefault(x => x.IdLocal == id);
if (localBuscado == null)
{
throw new Exception("Local não encontrado.");
} else
{
ctx.Locais.Remove(localBuscado);
ctx.SaveChanges();
}
}
}
public List<Locais> Listar ()
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext ())
{
var lista = ctx.Locais
.Include (x => x.IdTipoLocalNavigation)
.Include (x => x.IdBairroNavigation)
.ToList ();
foreach (var item in lista)
{
item.IdTipoLocalNavigation.Locais = null;
item.IdBairroNavigation.Locais = null;
item.IdBairroNavigation.Usuarios = null;
}
return lista;
}
}
public List<Locais> ListarComServicos()
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var lista = ctx.Locais
.Include (x => x.IdTipoLocalNavigation)
.Include (x => x.IdBairroNavigation)
.Include (x => x.ServicosPrestados).ThenInclude(y => y.IdSituacaoNavigation)
.Include (x => x.ServicosPrestados).ThenInclude(y => y.IdServicoNavigation).ThenInclude(z => z.IdCategoriaNavigation)
.ToList ();
foreach (var item in lista)
{
foreach (var servico in item.ServicosPrestados)
{
servico.IdServicoNavigation.IdCategoriaNavigation.Servicos = null;
servico.IdServicoNavigation.ServicosPrestados = null;
servico.IdSituacaoNavigation.ServicosPrestados = null;
}
item.IdTipoLocalNavigation.Locais = null;
item.IdBairroNavigation.Locais = null;
item.IdBairroNavigation.Usuarios = null;
}
return lista;
}
}
public List<Locais> ListarPorBairro (int idBairro)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var lista = ctx.Locais
.Where (x => x.IdBairro == idBairro)
.Include (x => x.IdTipoLocalNavigation)
.Include (x => x.IdBairroNavigation)
.ToList ();
foreach (var item in lista)
{
item.IdTipoLocalNavigation.Locais = null;
item.IdBairroNavigation.Locais = null;
item.IdBairroNavigation.Usuarios = null;
}
return lista;
}
}
public List<Locais> ListarPorTipoDeLocal (int idTipoLocal)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext ())
{
var lista = ctx.Locais
.Where (x => x.IdTipoLocal == idTipoLocal)
.Include (x => x.IdTipoLocalNavigation)
.Include (x => x.IdBairroNavigation)
.ToList ();
foreach (var item in lista)
{
item.IdTipoLocalNavigation.Locais = null;
item.IdBairroNavigation.Locais = null;
item.IdBairroNavigation.Usuarios = null;
}
return lista;
}
}
public bool LocalJaExiste(string nomeLocal)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var localBuscado = ctx.Locais.FirstOrDefault(x => x.NomeLocal.ToLower() == nomeLocal.ToLower());
return localBuscado == null ? false : true;
}
}
}
} |
using UnityEngine;
public class ParallaxMouseMove : MonoBehaviour
{
private Vector3 pz;
private Vector3 StartPos;
public float modifier;
void Start()
{
StartPos = transform.position;
}
void Update()
{
var pz = Camera.main.ScreenToViewportPoint(Input.mousePosition);
pz.z = 0;
gameObject.transform.position = pz;
transform.position = new Vector3(StartPos.x + (pz.x * modifier), StartPos.y + (pz.y * modifier), 0);
}
}
|
using System;
using System.Linq.Expressions;
using Microsoft.Extensions.Configuration;
using System.IO;
using MySql.Data.MySqlClient;
using OnlyOrm.Exetnds;
using OnlyOrm.Pool;
using System.Reflection;
using OnlyOrm.Cache;
using System.Collections.Generic;
using System.Data;
namespace OnlyOrm
{
///<summary>
/// 实体类的拓展泛型方法,可以通过泛型进行操作ORM,,
/// 暂时不支持联表查询
/// 暂时不支持多个或语句,比如:Orm.FindWhere<SuperUser>(u=>u.Id == 2 || u.Id == 3);因为暂时没法把表达式目录树转为in语句
///</summary>
public static class Orm
{
private static string _connctStr;
private static string _sqlType;
static Orm()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var config = builder.Build();
_connctStr = config["OnlyOrm:ConnectString"];
_sqlType = config["OnlyOrm:Type"];
MontageSqlHelper.SqlPrifix = MontageSqlHelper.GetSqlTypePrix(_sqlType);
}
///<summary>
/// 按照主键进行查找对应的数据库数据
///</summary>
public static T Find<T>(string key) where T : OrmBaseModel
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("primary key can't be null");
var sqlStr = SqlCache<T>.GetSql(SqlType.Find);
var parameters = SqlCache<T>.GetFindMySqlParameter(key);
return ExceteSql<T>(sqlStr, parameters, command =>
{
MySqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
Type type = typeof(T);
PropertyInfo[] properies = SqlCache<T>.AllProperties;
T result = Activator.CreateInstance<T>();
foreach (var proerty in properies)
{
var value = reader[proerty.GetMappingName()];
proerty.SetValue(result, value is DBNull ? null : value);
}
return result;
}
return default(T);
});
}
/// <summary>
/// 批量获取符合条件的数据
/// </summary>
/// <param name="conditions">查找的条件</param>
public static IList<T> FindWhere<T>(Expression<Func<T, bool>> conditions) where T : OrmBaseModel
{
SqlVisitor visitor = new SqlVisitor();
visitor.Visit(conditions);
var sqlStr = SqlCache<T>.GetSql(SqlType.FindWhere) + visitor.GetSql();
var parameters = visitor.GetParameters();
return ExceteSql<IList<T>>(sqlStr, parameters, command =>
{
var result = new List<T>();
var type = typeof(T);
var properies = SqlCache<T>.AllProperties;
var adapter = new MySqlDataAdapter(command);
var dataSet = new DataSet();
var count = adapter.Fill(dataSet);
for (var i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
T t = Activator.CreateInstance<T>();
foreach (var proerty in properies)
{
var value = dataSet.Tables[0].Rows[i][proerty.GetMappingName()];
proerty.SetValue(t, value is DBNull ? null : value);
}
result.Add(t);
}
return result;
});
}
/// <summary>
/// 插入实体,如果实体的主键是自动增长的,会被过滤掉
/// </summary>
public static bool Insert<T>(T t) where T : OrmBaseModel
{
if (null == t)
throw new ArgumentNullException("instance can't be null");
var parameters = SqlCache<T>.GetInsertMySqlParameters(t);
var sqlStr = SqlCache<T>.GetSql(SqlType.Insert);
return ExceteSql<bool>(sqlStr, parameters, command =>
{
var result = command.ExecuteNonQuery();
return result == 1;
});
}
/// <summary>
/// 根据实例主键进行更新
/// </summary>
public static bool Update<T>(T t) where T : OrmBaseModel
{
if (null == t)
throw new ArgumentNullException("instance can't be null");
var parameters = SqlCache<T>.GetUpdateMySqlParameters(t);
var sqlStr = SqlCache<T>.GetSql(SqlType.Update);
return ExceteSql<bool>(sqlStr, parameters, command =>
{
var result = command.ExecuteNonQuery();
return result == 1;
});
}
/// <summary>
/// 根据实例主键进行更新
/// </summary>
/// <param name="action">更新动作</param>
/// <param name="conditions">更新的条件</param>
public static bool UpdateWhere<T>(Expression<Action<T>> action, Expression<Func<T, bool>> conditions) where T : OrmBaseModel
{
SqlVisitor visitor = new SqlVisitor();
visitor.Visit(action);
var setStr = visitor.GetSql();
var setPrarmes = visitor.GetParameters();
visitor.Visit(conditions);
var whereStr = visitor.GetSql();
var wherePrarmes = visitor.GetParameters();
var sqlStr = SqlCache<T>.GetSql(SqlType.UpdateWhere) + setStr + " WHERE " + whereStr;
var allParames = new List<MySqlParameter>();
allParames.AddRange(setPrarmes);
allParames.AddRange(wherePrarmes);
return ExceteSql<bool>(sqlStr, allParames.ToArray(), command =>
{
var result = command.ExecuteNonQuery();
return result >= 1;
});
}
/// <summary>
/// 按主键值进行删除
/// </summary>
public static bool Deleate<T>(string key) where T : OrmBaseModel
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("primary key can't be null");
var sqlStr = SqlCache<T>.GetSql(SqlType.Deleate);
var parameters = SqlCache<T>.GetDelMySqlParameters(key);
return ExceteSql<bool>(sqlStr, parameters, command =>
{
var result = command.ExecuteNonQuery();
return result == 1;
});
}
/// <summary>
/// 根据表达式目录树,批量的删除
/// </summary>
/// <param name="conditions">删除的条件</param>
public static bool DeleateWhere<T>(Expression<Func<T, bool>> conditions) where T : OrmBaseModel
{
if (null == conditions)
return false;
SqlVisitor visitor = new SqlVisitor();
visitor.Visit(conditions);
var sqlStr = SqlCache<T>.GetSql(SqlType.DeleateWhere) + visitor.GetSql();
var parameters = visitor.GetParameters();
return ExceteSql<bool>(sqlStr, parameters, command =>
{
var result = command.ExecuteNonQuery();
return result >= 1;
});
}
private static T ExceteSql<T>(string sqlStr, MySqlParameter[] parameters, Func<MySqlCommand, T> callback)
{
using (MySqlConnection conn = new MySqlConnection(_connctStr))
{
MySqlCommand command = new MySqlCommand(sqlStr, conn);
if (null != parameters)
{
command.Parameters.AddRange(parameters);
}
conn.Open();
return callback.Invoke(command);
}
}
}
}
|
using System;
using System.Collections.Generic;
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 TwitchLib;
using TwitchLib.Models.API;
namespace TwtichPracaBot
{
/// <summary>
/// Logika interakcji dla klasy MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//private static TwitchLib.TwitchAPI api;
//private static
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Connect();
//Task t = Task.Run(async () =>
//{
// //api = new TwitchLib.TwitchAPI("rxz5pppetn8rety2xl0jq6ighu8h4m", "pmnj871u2ddlmovup6ousnflfboqka");
// var channel = await api.Channels.v5.GetChannelAsync();
// var allSubscriptions = await api.Channels.v5.GetAllSubscribersAsync(channel.Id);
// bool isStreaming = await api.Streams.v5.BroadcasterOnlineAsync(channel.Id);
// MessageBox.Show(isStreaming.ToString());
// //foreach (var item in allSubscriptions)
// //{
// // Console.WriteLine("Uzytkownik {0}, ID: {1}",item.User.Name, item.Id);
// //}
//});
//t.Wait();
}
public async void Connect()
{
TwitchAPI api = new TwitchLib.TwitchAPI("o9atkbd9c8z95a2955e8zs1vv8pp7o", "qn73zxxaxf7pggww2uv3l3mtjy77he");
var id = await api.Channels.v5.GetChannelAsync();
MessageBox.Show(id.Followers.ToString(),"Korona Kielce Kurwa Widelce" ,MessageBoxButton.OK);
}
}
}
|
using PDV.DAO.Entidades;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PDV.CONTROLLER.NFCE.Util
{
public class TributoNFCe
{
public decimal IDProduto { get; set; }
public decimal PercentualEstadual { get; set; }
public decimal PercentualFederal { get; set; }
public decimal PercentualMunicipal { get; set; }
public Ncm NCM { get; set; }
public TributoNFCe()
{
}
}
}
|
namespace com.faithstudio.Editor
{
using UnityEngine;
using UnityEditor;
public class EditorAppPreviewMaker
{
#if UNITY_EDITOR
[MenuItem("AppPreview/Screenshot")]
static public void OnTakeScreenshot()
{
ScreenCapture.CaptureScreenshot(EditorUtility.SaveFilePanel("Save Screenshot As", "", "", "png"));
}
#endif
}
}
|
using System;
using System.Runtime.InteropServices;
namespace POG.Automation
{
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("0449A389-9A23-4DC5-AA08-6F3B8223F5A0")]
public interface IPogCorral
{
void Login(string url, string username, string password);
void MakePost(string title, string content);
void SendPM(string to, string title, string content);
void SendPMToGroup(string[] to, string title, string content);
void StartPolling(Int32 startPost, object startTime, object stopTime);
void Stop();
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NChampions.Infra.Data.Context;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace NChampions.WebApi
{
public class MigrationWorker : IHostedService
{
readonly IServiceProvider provider;
public MigrationWorker(IServiceProvider provider)
{
this.provider = provider;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
using var scope = provider.CreateScope();
using var context = scope.ServiceProvider.GetRequiredService<NChampionsContext>();
await context.Database.MigrateAsync();
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
} |
using System;
using System.Threading.Tasks;
using Prism.Mvvm;
using Prism.Commands;
using System.Threading;
using FuzzyLogic.Model;
using System.Collections.ObjectModel;
using System.Windows;
using FuzzyLogic.Helper;
namespace FuzzyLogic
{
class ViewModel : BindableBase
{
#region Temp
//ChartName
public string ChartTempTittle { get; } = StartValues.ChartTempTittle;
//for chart Axis
private int _TempMin;
public int TempMin
{
get { return _TempMin; }
set { SetProperty(ref _TempMin, value); }
}
private int _TempMax;
public int TempMax
{
get { return _TempMax; }
set { SetProperty(ref _TempMax, value); }
}
//for listbox
private ObservableCollection<int> _TempList;
public ObservableCollection<int> TempList
{
get
{
if (_TempList == null)
{
_TempList = new ObservableCollection<int>();
for (int i = StartValues.TempExpectedMin; i <= StartValues.TempExpectedMax; i += StartValues.ChartPre)
{
_TempList.Add(i);
}
}
return _TempList;
}
set { SetProperty(ref _TempList, value); }
}
private int _TempExpected = StartValues.TempExpectedDefault;
public int TempExpected
{
get { return _TempExpected; }
set
{
SetProperty(ref _TempExpected, value);
StartValues.TempExpectedDefault = value;
Line_Temp = new Temp();
//Line_Conditioner = new Conditioner();
//Line_Heat = new Heat(StartValues.HeatMin, StartValues.HeatMax, 20, StartValues.TempChartPrecision);
}
}
//DataCollection
private Temp _Line_Temp;
public Temp Line_Temp
{
get
{
if (_Line_Temp == null)
_Line_Temp = new Temp();
TempMin = _Line_Temp.XAxisMin;
TempMax = _Line_Temp.XAxisMax;
return _Line_Temp;
}
set
{
SetProperty(ref _Line_Temp, value);
}
}
#endregion
#region WorkHours
public string ChartWorkHoursTittle { get; } = StartValues.ChartWorkHoursTittle;
//ListBox
private ObservableCollection<int> _WorkHourMinList;
public ObservableCollection<int> WorkHourMinList
{
get
{
if (_WorkHourMinList == null)
{
_WorkHourMinList = new ObservableCollection<int>();
for (int i = 0; i < 24; i++)
{
_WorkHourMinList.Add(i);
}
}
return _WorkHourMinList;
}
set { SetProperty(ref _WorkHourMinList, value); }
}
private ObservableCollection<int> _WorkHourMaxList;
public ObservableCollection<int> WorkHourMaxList
{
get
{
if (_WorkHourMaxList == null)
{
_WorkHourMaxList = new ObservableCollection<int>();
for (int i = 0; i < 24; i++)
{
_WorkHourMaxList.Add(i);
}
}
return _WorkHourMaxList;
}
set { SetProperty(ref _WorkHourMaxList, value); }
}
//ListBox Selection
private int _SelectedWorkHourMin = StartValues.WorkHoursDefaultBegin;
public int SelectedWorkHourMin
{
get { return _SelectedWorkHourMin; }
set
{
SetProperty(ref _SelectedWorkHourMin, value);
Line_WorkHours = new WorkHour(SelectedWorkHourMin, SelectedWorkHourMax);
}
}
private int _SelectedWorkHourMax = StartValues.WorkHoursDefaultEnd;
public int SelectedWorkHourMax
{
get { return _SelectedWorkHourMax; }
set
{
SetProperty(ref _SelectedWorkHourMax, value);
Line_WorkHours = new WorkHour(SelectedWorkHourMin, SelectedWorkHourMax);
}
}
//DataCollection
private WorkHour _Line_WorkHours;
public WorkHour Line_WorkHours
{
get
{
if (_Line_WorkHours == null)
_Line_WorkHours = new WorkHour(SelectedWorkHourMin, SelectedWorkHourMax);
return _Line_WorkHours;
}
set
{
SetProperty(ref _Line_WorkHours, value);
}
}
#endregion
#region Heat
public string ChartHeatTittle { get; } = StartValues.ChartHeatTittle;
private int _HeatMin;
public int HeatMin
{
get { return _HeatMin; }
set { SetProperty(ref _HeatMin, value); }
}
private int _HeatMax;
public int HeatMax
{
get { return _HeatMax; }
set { SetProperty(ref _HeatMax, value); }
}
private Heat _Line_Heat = null;
public Heat Line_Heat
{
get
{
if (_Line_Heat == null)
{
_Line_Heat = new Heat();
HeatMin = _Line_Heat.XAxisMin;
HeatMax = _Line_Heat.XAxisMax;
}
return _Line_Heat;
}
set { SetProperty(ref _Line_Heat, value); }
}
#endregion
#region Conditioner
//for chart
public string ChartConditionerTittle { get; } = StartValues.ChartConditionerTittle;
private int _CondirionerMin;
public int ConditionerMin
{
get { return _CondirionerMin; }
set { SetProperty(ref _CondirionerMin, value); }
}
private int _CondirionerMax;
public int ConditionerMax
{
get { return _CondirionerMax; }
set { SetProperty(ref _CondirionerMax, value); }
}
private Conditioner _Line_Conditioner;
public Conditioner Line_Conditioner
{
get
{
if (_Line_Conditioner == null)
{ _Line_Conditioner = new Conditioner();
ConditionerMin = _Line_Conditioner.XAxisMin;
ConditionerMax = _Line_Conditioner.XAxisMax;
}
return _Line_Conditioner;
}
set
{
SetProperty(ref _Line_Conditioner, value);
}
}
#endregion
#region Weather
public string ChartWeatherTittle { get; } = StartValues.ChartWeatherTittle;
//przycinanie charta z lewej
public int _WeatherXmin = 0;
public int WeatherXmin { get { return _WeatherXmin; } set { SetProperty(ref _WeatherXmin, value); } }
public int _WeatherXmax= StartValues.HoursOnChart;
public int WeatherXmax { get { return _WeatherXmax; } set { SetProperty(ref _WeatherXmax, value); } }
private Weather _Line_Weather;
public Weather Line_Weather
{
get
{
if (_Line_Weather == null)
{ _Line_Weather = new Weather(); }
return _Line_Weather;
}
set
{
SetProperty(ref _Line_Weather, value);
}
}
#endregion
#region RoomArea
private int _SelectedRoomArea = StartValues.RoomAreaDefaultIndex;
public int SelectedRoomArea
{
get { return _SelectedRoomArea; }
set { SetProperty(ref _SelectedRoomArea, value); }
}
private ObservableCollection<int> _RoomAreaList;
public ObservableCollection<int> RoomAreaList
{
get
{
if (_RoomAreaList == null)
{
_RoomAreaList = new ObservableCollection<int>();
for (int i = StartValues.RoomAreaMin; i < StartValues.RoomAreaMax; i += StartValues.RoomAreaListInc)
{
_RoomAreaList.Add(i);
}
}
return _RoomAreaList;
}
set { SetProperty(ref _RoomAreaList, value); }
}
#endregion
#region WindowArea
private int _SelectedWindowArea = StartValues.WindowAreaDefaultIndex;
public int SelectedWindowArea
{
get { return _SelectedWindowArea; }
set { SetProperty(ref _SelectedWindowArea, value); }
}
private ObservableCollection<int> _WindowAreaList;
public ObservableCollection<int> WindowAreaList
{
get
{
if (_WindowAreaList == null)
{
_WindowAreaList = new ObservableCollection<int>();
for (int i = StartValues.WindowAreatMin; i < StartValues.WindowAreaMax; i += StartValues.WindowAreaIncrement)
{
_WindowAreaList.Add(i);
}
}
return _WindowAreaList;
}
set { SetProperty(ref _WindowAreaList, value); }
}
#endregion
#region WallHeight
private int _SelectedWallHeight = StartValues.WindowAreaDefaultIndex;
public int SelectedWallHeight
{
get { return _SelectedWallHeight; }
set { SetProperty(ref _SelectedWallHeight, value); }
}
private ObservableCollection<int> _WallHeightList;
public ObservableCollection<int> WallHeightList
{
get
{
if (_WallHeightList == null)
{
_WallHeightList = new ObservableCollection<int>();
for (int i = StartValues.WallHeightMin; i < StartValues.WallHeightMax; i += StartValues.WallHeightIncrement)
{
_WallHeightList.Add(i);
}
}
return _WallHeightList;
}
set { SetProperty(ref _WallHeightList, value); }
}
#endregion
#region Helper
public string ChartHelperTittle { get; } = StartValues.ChartHelperTittle;
private int _HelperMin = 0;
public int HelperMin
{
get { return _HelperMin; }
set { SetProperty(ref _HelperMin, value); }
}
private int _HelperMax = 100;
public int HelperMax
{
get { return _HelperMax; }
set { SetProperty(ref _HelperMax, value); }
}
private int _TempHeat = 0;
public int TempHeat
{
get { return _TempHeat; }
set { SetProperty(ref _TempHeat, value); }
}
private int _TempConditioner = 0;
public int TempConditioner
{
get { return _TempConditioner; }
set { SetProperty(ref _TempConditioner, value); }
}
private double _TempNow = 0;
public double TempNow
{
get { return _TempNow; }
set { SetProperty(ref _TempNow, value); }
}
#endregion
#region Time
private Task TaskClock;
public int _ClockSpeed = StartValues.TimeSpeed;
private TimeSpan _Time = new TimeSpan(0, 0, 0, 0);
public string Time
{
get { return _Time.Days.ToString() + "D " + _Time.Hours.ToString() + "H"; }
set
{
var TimeNow = new TimeSpan((int)_Time.TotalHours + Convert.ToInt32(value), 0, 0);
if (TimeNow.TotalHours >= 0)
SetProperty(ref _Time, TimeNow);
}
}
public DelegateCommand<object> ClockAddCommand { get; private set; }
public DelegateCommand<object> ClockSpeedCommand { get; private set; }
#endregion
SystemWnioskowania x = new SystemWnioskowania();
//konstruktor, dodanie command(cos ala event)
public ViewModel()
{
ClockSpeedCommand = new DelegateCommand<object>(Execute_ClockSpeed);
TaskClock = new Task(Clock_Increment_Task);
TaskClock.Start();
}
//zamiana parametru z kliknietego buttonu na tryb szybkosci
private void Execute_ClockSpeed(object speed)
{
_ClockSpeed = Int32.Parse(speed.ToString());
}
//wywoływanie metod w tasku oraz usypianie taska wg zadanego trybu
private void Clock_Increment_Task()
{
while (true)
{
switch (_ClockSpeed)
{
default:
Thread.Sleep(1000);
break;
case 1:
TaskMethodHelper(StartValues.TimeSpeed1);
break;
case 2:
TaskMethodHelper(StartValues.TimeSpeed2);
break;
case 3:
TaskMethodHelper(StartValues.TimeSpeed3);
break;
}
}
}
//imitacja czasu
int hour = 0;
//metoda wywoływana na okrągło(przerwy jako task.sleep) ma za zadanie
//dodanie temp pogody (co godzine)
//obliczenie środkow ciezkosci
//wyliczanie zmiany temp w pomieszczeniu
//przesuwanie wykresu pogody
private void TaskMethodHelper(int sleep)
{
Time = "1";
try
{
Application.Current.Dispatcher.Invoke((Action)(() =>
{
//dodanie kolejnej temp na wykresie pogody
int nextWeatherTemp = Line_Weather.NextTemp();
for (int i = 0; i < StartValues.UpdateTime; i++)
{
//wyliczanie środkow ciezkosci dla klimy i pieca (wyniki dostepne w geterach)
x.Rozmywanie(Line_Heat, Line_Conditioner, Line_Temp, (int)Math.Round(TempNow), Line_WorkHours, hour);
//wyliczanie temp pieca i klimatyzacji na podstawie środka ciezkosci
CalculateTempOfHeater(x.CenterOfGravityHeater);
CalculateTempOfConditioner(x.CenterOfGravityConditioner);
//wyliczanie zmiany temp w pomieszczeniu
TempUpdate(TempExpected, (int)Math.Round(TempNow), TempHeat, TempConditioner, nextWeatherTemp);
}
Line_Weather.xWeather+=StartValues.UpdateTime;
hour = (hour == 23) ? 0 : hour + 1 ;
//przesuwanie wykresu pogody
if (_Line_Weather.Count >= StartValues.HoursOnChart)
{
WeatherXmin +=4;
WeatherXmax +=4;
}
}));
}
catch (System.NullReferenceException)
{
//nic sie nie stało wanego
}
Thread.Sleep(sleep);
}
//liczymy temp pieca na podstawie maxTempPiecam tempExpected i gravity
private void CalculateTempOfHeater(double centerOfGravity)
{
int result = ((int)Math.Round(TempExpected + StartValues.maxTempHeat * centerOfGravity / 100));
if (result > StartValues.maxTempHeat) result = StartValues.maxTempHeat;
TempHeat = result;
}
//liczymy temp Klimatyzacji na podstawie maxTempPiecam tempExpected i gravity
private void CalculateTempOfConditioner(double centerOfGravity)
{
int result = ((int)Math.Round(TempExpected - StartValues.minTempConditioner * centerOfGravity / 100));
if (result < StartValues.minTempConditioner) result = StartValues.minTempConditioner;
TempConditioner = result;
}
//tu liczymy wpływy na temp w pomieszczeniu - piec klima pogoda rozmiar budynku
public void TempUpdate(int TExpected, int TNow, int THeat, int TConditioner, int TWeather)
{
double conditioner = (TExpected - TNow >= 0) ? 0 : (TConditioner / 2.5);
double heater = (TExpected - TNow <= 0) ? 0 : (THeat / 5.0);
if (Line_WorkHours[hour].Y == 0)
{
conditioner = 0;
heater = 0;
}
double weather = ((TNow + 1.0) - TWeather==0)? 0:Math.Log10(Math.Abs((TNow + 1.0) - TWeather));
if (TWeather < TNow) weather *= -1;
double buildingDimension = (((WallHeightList[SelectedWallHeight] / 100 * Math.Sqrt(RoomAreaList[SelectedRoomArea]) + WindowAreaList[SelectedWindowArea] / 2) * Math.Sqrt(RoomAreaList[SelectedRoomArea]) / 10));
double result = (heater / buildingDimension + weather - Math.Abs(conditioner));
result = (result > 0) ? (result/StartValues.UpdateTime) : (result/ StartValues.UpdateTime);
TempNow += result;
Line_Weather.AddNext(TempNow, TWeather);
}
}
} |
namespace Common
{
public struct StartGame
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using Negocio;
using System.Threading;
namespace Servidor
{
class Program
{
static void Main(string[] args)
{
//Cria um objeto TcpListener para "escutar" conexões na porta 5000
TcpListener servidor = new TcpListener(5555);
//Inicia o servidor
servidor.Start();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Servidor aguardando conexões na porta 5555");
Console.ResetColor();
while (true)
{
Socket conexao = servidor.AcceptSocket(); //Aceita uma conexão
Console.WriteLine("Nova conexão aceita!");
ConexaoCliente c = new ConexaoCliente(conexao); //Cria um objeto ConexaoCliente para a conexão aceita
Thread cc = new Thread(new ThreadStart(c.processarConexao)); //Processa os dados da conexão como uma Thread independente
cc.Start(); //Inicia a Thread criada
}
}
}
class ConexaoCliente
{
//Objetos de fluxo de dados necessários para a conexão
NetworkStream fluxos;
BinaryReader entrada;
BinaryWriter saida;
Socket cliente;
//Quando um objeto ConexaoCliente é criado, o socket da conexão deve ser passado como referência
public ConexaoCliente(Socket s)
{
//Inicia os objetos
this.cliente = s;
fluxos = new NetworkStream(this.cliente);
entrada = new BinaryReader(fluxos);
saida = new BinaryWriter(fluxos);
}
public void processarConexao()
{
try
{
if (entrada != null)
{
String msg = entrada.ReadString(); //Lê a mensagem do cliente
while (msg != "fim")
{
Console.WriteLine("Mensagem recebida: " + msg);
//Faz o registro da passagem
msg = new NMovimentacaoClube().RegistrarPassagem(int.Parse(msg));
saida.Write("RESPOSTA: " + msg.ToUpper()); //"Processa" a resposta (só converte para maiúscula)
Console.WriteLine("Mensagem retornada: " + msg);
msg = entrada.ReadString(); //Lê a próxima mensagem
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
//Finaliza os componentes no final da conexão
entrada.Close();
saida.Close();
fluxos.Close();
cliente.Close();
}
Console.WriteLine("Conexão finalizada!");
}
}
}
// class Program
// {
// static void Main(string[] args)
// {
// //Declara um objeto que irá "escutar" a rede na porta especificada
// TcpListener servidor = new TcpListener(5555);
// //Inicializa o serviço do servidor
// servidor.Start();
// //Aguarda a conexao, e cria o objeto com a conexão do cliente
// //quando estabelecida
// Console.WriteLine("Aguardando conexão do cliente");
// Socket conexaoCliente = servidor.AcceptSocket();
// Console.ForegroundColor = ConsoleColor.Green;
// Console.WriteLine("Conexão estabelecida!");
// Console.ResetColor();
// //Cria um streaming de conexão com o cliente
// NetworkStream dadosConexao = new NetworkStream(conexaoCliente);
// //Cria o objeto para ler as informações enviadas pelo cliente
// BinaryReader entradaDados = new BinaryReader(dadosConexao);
// //Cria o objeto para escrever informações para o cliente
// BinaryWriter saidaDados = new BinaryWriter(dadosConexao);
// while (true)
// {
// Teste t = new Teste();
// Thread cc = new Thread(new ThreadStart(t.VerificarPassagem(entradaDados, saidaDados)));
// cc.Start(); //Inicia a Thread criada
// }
// //Para o servidor
// servidor.Stop();
// Console.WriteLine("Fim da execução");
// }
// }
// class Teste
// {
//
// }
//}
|
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
namespace DotCom.Pages.Util
{
/// <summary>
/// Utility class to house convenience methods specifically around IWebElement objects.
/// </summary>
public class WebElementHelper : SearchContextWrapper
{
// This subclass of PageHelper deals specifically with convenience methods that require
// an IWebElement instead of an ISearchContext.
private IWebElement element;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="element"></param>
public WebElementHelper(IWebElement element) : base(element)
{
this.element = element;
}
/// <summary>
/// Retrieves the original driver from the WebElement.
/// </summary>
public IWebDriver Driver {
get
{
RemoteWebElement re = (RemoteWebElement)element;
return re.WrappedDriver;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model.Security.MembershipManagement;
using Model.DataEntity;
using Business.Helper;
using Model.Locale;
using eIVOGo.Module.Base;
using Uxnet.Web.WebUI;
using System.Text.RegularExpressions;
using Utility;
namespace eIVOGo.Module.SAM
{
public partial class EditBuyer : EditEntityItemBase<EIVOEntityDataContext, InvoiceBuyer>
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreRender += new EventHandler(EditBuyer_PreRender);
this.Done+=new EventHandler(EditBuyer_Done);
this.QueryExpr = m => m.InvoiceID == (int?)modelItem.DataItem;
}
void EditBuyer_PreRender(object sender, EventArgs e)
{
this.BindData();
if (_entity != null)
{
modelItem.DataItem = _entity.InvoiceID;
}
}
void EditBuyer_Done(object sender, EventArgs e)
{
Response.Redirect("~/SAM/register_msg.aspx?" + String.Format("backUrl=BuyerManager.aspx&action={0}&back={1}", Server.UrlEncode(actionItem.ItemName), Server.UrlEncode("回買受人資料維護")));
}
protected override bool saveEntity()
{
var mgr = dsEntity.CreateDataManager();
loadEntity();
if (_entity != null)
{
_entity.ContactName = this.ContactName.Text.Trim();
_entity.Phone = this.Phone.Text.Trim();
_entity.Address = this.Addr.Text.Trim();
mgr.SubmitChanges();
}
return true;
}
}
} |
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using Telerik.Web.UI;
#endregion
namespace DotNetNuke.Web.UI.WebControls
{
public class DnnDockCommand : DockCommand
{
public DnnDockCommand()
{
}
public DnnDockCommand(string clientTypeName, string cssClass, string name, string text, bool autoPostBack) : base(clientTypeName, cssClass, name, text, autoPostBack)
{
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System.IO;
using DotNetNuke.ComponentModel;
namespace DotNetNuke.Services.FileSystem.Internal
{
public class DirectoryWrapper : ComponentBase<IDirectory, DirectoryWrapper>, IDirectory
{
public void Delete(string path, bool recursive)
{
if (Exists(path))
{
Directory.Delete(path, recursive);
}
}
public bool Exists(string path)
{
return Directory.Exists(path);
}
public string[] GetDirectories(string path)
{
return Directory.GetDirectories(path);
}
public string[] GetFiles(string path)
{
return Directory.GetFiles(path);
}
public void Move(string sourceDirName, string destDirName)
{
Directory.Move(sourceDirName, destDirName);
}
public void CreateDirectory(string path)
{
Directory.CreateDirectory(path);
}
}
}
|
using REQFINFO.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace REQFINFO.Business.Interfaces
{
public interface IUDFValidationBusiness
{
List<UDFFieldsValidationsModel> GetValidations(Int32 IDUDFDefinition);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlocksScript : GameManager {
public GameObject BetterBlock;
bool first = false;
static int blockCounter = 0;
static bool useless = false;
public GameObject victoryBlock;
public GameObject spawnPoint;
public EdgeCollider2D beGone;
public AudioSource clown;
public GameObject Win;
// Use this for initialization
void Start () {
useless = false;
blockCounter = 0;
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.name == "Qbert"&& !first && useless) {
Instantiate(BetterBlock, transform.position,transform.rotation);
first = true;
blockCounter++;
score+= 25;
beGone.enabled = false;
Invoke ("victory", .4f);
}
if (other.gameObject.name == "Qbert" && this.gameObject.name == "CandyCubeS")
{
useless = true;
}
}
public void victory(){
if (blockCounter == 28)
{
clown.Play ();
Invoke ("congratz", 2.5f);
Instantiate (victoryBlock, spawnPoint.transform.position, spawnPoint.transform.rotation);
score+=1000;
if(diskCounter<= 0)
{
diskCounter = 0;
}
score=(diskCounter*100)+score;
gameOver = true;
gmMover = false;
}
}
public void congratz(){
Time.timeScale = 0;
Win.SetActive (true);
}
}
|
using System;
using BehaviorScripts;
using ManagerScripts;
using UnityEditor;
namespace Editor
{
[CustomEditor(typeof(ShooterBehavior), true)]
public class ShooterEditor : UnityEditor.Editor
{
private SerializedProperty _damageMultiplier;
private SerializedProperty _attackSpeedMultiplier;
private SerializedProperty _additionalBullets;
private SerializedProperty _sightMultiplier;
//Array of all properties shared by both enemies and the player
private SerializedProperty[] _sharedProperties;// = new SerializedProperty[6];
//Is this an enemy object?
private void OnEnable()
{
try
{
_sightMultiplier = serializedObject.FindProperty("sightMultiplier");
_damageMultiplier = serializedObject.FindProperty("damageMultiplier");
_attackSpeedMultiplier = serializedObject.FindProperty("attackSpeedMultiplier");
_additionalBullets = serializedObject.FindProperty("additionalBulletsFired");
_sharedProperties = new []
{
serializedObject.FindProperty("lockingRangeMultiplier"),
serializedObject.FindProperty("bulletSpeedMultiplier"),
serializedObject.FindProperty("noiseMultiplier"),
};
}
catch (Exception)
{
//Nearly every line above raises a SerializedObjectNotCreateableException, whose type I can't access
//(which is why a general Exception is being caught instead)
//I can't find any information on it, but suppressing it like this doesn't cause any noticeable issues.
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
var shooter = serializedObject.targetObject as ShooterBehavior;
if (shooter.transform.parent)
{
var owner = shooter.transform.parent.GetComponent<Entity>();
if (owner is EnemyScript e)
{
EditorGUILayout.PropertyField(_sightMultiplier);
if (e.isElite)
{
EditorGUILayout.PropertyField(_attackSpeedMultiplier);
EditorGUILayout.PropertyField(_damageMultiplier);
EditorGUILayout.PropertyField(_additionalBullets);
}
else
{
EditorGUILayout.LabelField($"Attack Speed Multiplier {_attackSpeedMultiplier.floatValue}");
EditorGUILayout.LabelField($"Damage Multiplier {_damageMultiplier.floatValue}");
EditorGUILayout.LabelField($"Additional Bullets {_additionalBullets.intValue}");
}
}
else
{
EditorGUILayout.PropertyField(_attackSpeedMultiplier);
EditorGUILayout.PropertyField(_damageMultiplier);
EditorGUILayout.PropertyField(_additionalBullets);
}
EditorGUILayout.LabelField("Damage Per Second", $"{shooter.uiDamagePerSecond}");
EditorGUILayout.LabelField("Attacks Per Second", $"{shooter.uiAttacksPerSecond}");
}
else
{
EditorGUILayout.PropertyField(_attackSpeedMultiplier);
EditorGUILayout.PropertyField(_damageMultiplier);
EditorGUILayout.PropertyField(_additionalBullets);
}
foreach (var p in _sharedProperties)
{
EditorGUILayout.PropertyField(p);
}
serializedObject.ApplyModifiedProperties();
}
}
} |
using Assets.Scripts.RobinsonCrusoe_Game.Cards;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assets.Scripts.RobinsonCrusoe_Game.GameAttributes
{
public static class BuildingCosts
{
public static RessourceCosts GetBuildingCosts()
{
if (Player.PartyHandler.PartySize == 3) return new RessourceCosts(3, 0, 0);
if (Player.PartyHandler.PartySize == 4) return new RessourceCosts(4, 0, 0);
return new RessourceCosts(2, 0, 0);
}
}
}
|
public class BTInput {
} |
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Grubber.Web.Models;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Grubber.Web.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
{
//Configuration.LazyLoadingEnabled = false;
//Configuration.ProxyCreationEnabled = false;
Database.SetInitializer(new ApplicationDbInitializer());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Add(new DateTime2Convention());
// Configure Code First to ignore PluralizingTableName convention
// If you keep this convention then the generated tables will have pluralized names.
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<IdentityRole>().ToTable("Role", "Grubber");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim", "Grubber");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin", "Grubber");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole", "Grubber");
modelBuilder.Entity<ApplicationUser>().ToTable("User", "Grubber");
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
} |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using Clime.MVVMUtils;
using Clime.MVVMUtils.DataServices;
using GalaSoft.MvvmLight;
using Clime.Model;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
namespace Clime.ViewModel
{
class MainViewModel : ViewModelBase
{
private readonly IDataService _dataService;
public RelayCommand ShowAllMeasurementsViewCommand { get; private set; }
public RelayCommand ShowNewMeasurementViewCommand { get; private set; }
public RelayCommand ShowAboutViewCommand { get; private set; }
private int _selectedContinentId;
public int SelectedContinentId
{
get { return _selectedContinentId; }
set
{
if (_selectedContinentId == value)
return;
_selectedContinentId = value;
ContinentFilterSelected();
RaisePropertyChanged("SelectedContinentId");
}
}
private Country _selectedCountry;
public Country SelectedCountry
{
get { return _selectedCountry; }
set
{
if (_selectedCountry == value)
return;
_selectedCountry = value;
CountryFilterSelected();
RaisePropertyChanged("SelectedCountry");
}
}
public ObservableCollection<Country> CountriesRaw { get; set; }
public ObservableCollection<Country> Countries { get; set; }
public ObservableCollection<City> CitiesRaw { get; set; }
public ObservableCollection<City> Cities { get; set; }
public ObservableCollection<string> Continents { get; set; }
public MainViewModel(IDataService dataService)
{
CountriesRaw = new ObservableCollection<Country>();
Countries = new ObservableCollection<Country>();
CitiesRaw = new ObservableCollection<City>();
Cities = new ObservableCollection<City>();
Continents = new ObservableCollection<string>();
_dataService = dataService;
_dataService.GetGeographyRepository(GeographyRepositoryLoaded);
ShowAllMeasurementsViewCommand = new RelayCommand(ShowAllMeasurementsView);
ShowNewMeasurementViewCommand = new RelayCommand(ShowAddNewMeasurementView);
ShowAboutViewCommand = new RelayCommand(ShowAboutView);
Messenger.Default.Register<Messages.NewMeasurementAddedMessage>(this, AddedNewMeasurement);
}
private void ShowAllMeasurementsView()
{
var newView = new View.AllMeasurementsView();
newView.ShowDialog();
}
private void ShowAddNewMeasurementView()
{
var newView = new View.NewMeasurementView();
newView.ShowDialog();
}
private void ShowAboutView()
{
var newView = new View.AboutView();
newView.ShowDialog();
}
private bool IsCountryBelongToSelectedContinent(Country country)
{
// Meta Continent: "Whole World"
if (SelectedContinentId == 0)
return true;
// Meta Country: "Any Country"
if (country.ContinentId == ContinentsEnum.Special)
return true;
return country.ContinentId == (ContinentsEnum)(SelectedContinentId - 1);
}
private void ContinentFilterSelected()
{
Countries.Clear();
foreach (var country in CountriesRaw.Where(IsCountryBelongToSelectedContinent))
{
Countries.Add(country);
}
SelectedCountry = Countries[0];
}
private bool IsCityBelongToSelectedCountry(City city)
{
if (SelectedCountry == null)
return false;
// Meta Country: "Any Country"
if (SelectedCountry.ContinentId == ContinentsEnum.Special)
{
return IsCountryBelongToSelectedContinent(city.CountryOwner);
}
return city.CountryCode == SelectedCountry.CountryCode;
}
private void CountryFilterSelected()
{
Cities.Clear();
if (SelectedCountry == null)
return;
foreach (var city in CitiesRaw.Where(IsCityBelongToSelectedCountry))
{
Cities.Add(city);
}
}
private void GeographyRepositoryLoaded(GeographyRepository repo, Exception error)
{
if (error != null)
{
Messenger.Default.Send(new DialogMessage(error.ToString(), null) { Button = MessageBoxButton.OK, Caption = "Error" });
return;
}
Continents.Clear();
foreach (var continent in repo.Continents)
{
Continents.Add(continent);
}
CountriesRaw.Clear();
foreach (var country in repo.Countries)
{
CountriesRaw.Add(country);
}
CitiesRaw.Clear();
foreach (var city in repo.Cities)
{
CitiesRaw.Add(city);
}
ContinentFilterSelected();
}
private static void AddedNewMeasurement(Messages.NewMeasurementAddedMessage message)
{
if (message == null)
return;
// todo:
Messenger.Default.Send(new DialogMessage("Added " + message.MeasurementAdded, null) { Button = MessageBoxButton.OK, Caption = "Caption??" });
}
}
} |
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
namespace NopSolutions.NopCommerce.DataAccess.Orders
{
/// <summary>
/// Acts as a base class for deriving custom order provider
/// </summary>
[DBProviderSectionName("nopDataProviders/OrderProvider")]
public abstract partial class DBOrderProvider : BaseDBProvider
{
#region Methods
/// <summary>
/// Gets an order
/// </summary>
/// <param name="OrderID">The order identifier</param>
/// <returns>Order</returns>
public abstract DBOrder GetOrderByID(int OrderID);
/// <summary>
/// Search orders
/// </summary>
/// <param name="StartTime">Order start time; null to load all orders</param>
/// <param name="EndTime">Order end time; null to load all orders</param>
/// <param name="CustomerEmail">Customer email</param>
/// <param name="OrderStatusID">Order status identifier; null to load all orders</param>
/// <param name="PaymentStatusID">Order payment status identifier; null to load all orders</param>
/// <param name="ShippingStatusID">Order shipping status identifier; null to load all orders</param>
/// <returns>Order collection</returns>
public abstract DBOrderCollection SearchOrders(DateTime? StartTime, DateTime? EndTime, string CustomerEmail, int? OrderStatusID, int? PaymentStatusID, int? ShippingStatusID);
/// <summary>
/// Get order product variant sales report
/// </summary>
/// <param name="StartTime">Order start time; null to load all</param>
/// <param name="EndTime">Order end time; null to load all</param>
/// <param name="OrderStatusID">Order status identifier; null to load all orders</param>
/// <param name="PaymentStatusID">Order payment status identifier; null to load all orders</param>
/// <returns>Result</returns>
public abstract IDataReader OrderProductVariantReport(DateTime? StartTime, DateTime? EndTime, int? OrderStatusID, int? PaymentStatusID);
/// <summary>
/// Get the bests sellers report
/// </summary>
/// <param name="LastDays">Last number of days</param>
/// <param name="RecordsToReturn">Number of products to return</param>
/// <param name="OrderBy">1 - order by total count, 2 - Order by total amount</param>
/// <returns>Result</returns>
public abstract List<DBBestSellersReportLine> BestSellersReport(int LastDays, int RecordsToReturn, int OrderBy);
/// <summary>
/// Get order average report
/// </summary>
/// <param name="OrderStatusID">Order status identifier</param>
/// <returns>Result</returns>
public abstract DBOrderAverageReportLine OrderAverageReport(int OrderStatusID);
/// <summary>
/// Gets all orders by customer identifier
/// </summary>
/// <param name="CustomerID">Customer identifier</param>
/// <returns>Order collection</returns>
public abstract DBOrderCollection GetOrdersByCustomerID(int CustomerID);
/// <summary>
/// Gets an order by authorization transaction identifier
/// </summary>
/// <param name="AuthorizationTransactionID">Authorization transaction identifier</param>
/// <param name="PaymentMethodID">Payment method identifier</param>
/// <returns>Order</returns>
public abstract DBOrder GetOrderByAuthorizationTransactionIDAndPaymentMethodID(string AuthorizationTransactionID, int PaymentMethodID);
/// <summary>
/// Gets all orders by affiliate identifier
/// </summary>
/// <param name="AffiliateID">Affiliate identifier</param>
/// <returns>Order collection</returns>
public abstract DBOrderCollection GetOrdersByAffiliateID(int AffiliateID);
/// <summary>
/// Inserts an order
/// </summary>
/// <param name="OrderGUID">The order identifier</param>
/// <param name="CustomerID">The customer identifier</param>
/// <param name="CustomerLanguageID">The customer language identifier</param>
/// <param name="CustomerTaxDisplayTypeID">The customer tax display type identifier</param>
/// <param name="OrderSubtotalInclTax">The order subtotal (incl tax)</param>
/// <param name="OrderSubtotalExclTax">The order subtotal (excl tax)</param>
/// <param name="OrderShippingInclTax">The order shipping (incl tax)</param>
/// <param name="OrderShippingExclTax">The order shipping (excl tax)</param>
/// <param name="PaymentMethodAdditionalFeeInclTax">The payment method additional fee (incl tax)</param>
/// <param name="PaymentMethodAdditionalFeeExclTax">The payment method additional fee (excl tax)</param>
/// <param name="OrderTax">The order tax</param>
/// <param name="OrderTotal">The order total</param>
/// <param name="OrderDiscount">The order discount</param>
/// <param name="OrderSubtotalInclTaxInCustomerCurrency">The order subtotal incl tax (customer currency)</param>
/// <param name="OrderSubtotalExclTaxInCustomerCurrency">The order subtotal excl tax (customer currency)</param>
/// <param name="OrderShippingInclTaxInCustomerCurrency">The order shipping incl tax (customer currency)</param>
/// <param name="OrderShippingExclTaxInCustomerCurrency">The order shipping excl tax (customer currency)</param>
/// <param name="PaymentMethodAdditionalFeeInclTaxInCustomerCurrency">The payment method additional fee incl tax (customer currency)</param>
/// <param name="PaymentMethodAdditionalFeeExclTaxInCustomerCurrency">The payment method additional fee excl tax (customer currency)</param>
/// <param name="OrderTaxInCustomerCurrency">The order tax (customer currency)</param>
/// <param name="OrderTotalInCustomerCurrency">The order total (customer currency)</param>
/// <param name="CustomerCurrencyCode">The customer currency code</param>
/// <param name="OrderWeight">The order weight</param>
/// <param name="AffiliateID">The affiliate identifier</param>
/// <param name="OrderStatusID">The order status identifier</param>
/// <param name="AllowStoringCreditCardNumber">The value indicating whether storing of credit card number is allowed</param>
/// <param name="CardType">The card type</param>
/// <param name="CardName">The card name</param>
/// <param name="CardNumber">The card number</param>
/// <param name="MaskedCreditCardNumber">The masked credit card number</param>
/// <param name="CardCVV2">The card CVV2</param>
/// <param name="CardExpirationMonth">The card expiration month</param>
/// <param name="CardExpirationYear">The card expiration year</param>
/// <param name="PaymentMethodID">The payment method identifier</param>
/// <param name="PaymentMethodName">The payment method name</param>
/// <param name="AuthorizationTransactionID">The authorization transaction ID</param>
/// <param name="AuthorizationTransactionCode">The authorization transaction code</param>
/// <param name="AuthorizationTransactionResult">The authorization transaction result</param>
/// <param name="CaptureTransactionID">The capture transaction ID</param>
/// <param name="CaptureTransactionResult">The capture transaction result</param>
/// <param name="PurchaseOrderNumber">The purchase order number</param>
/// <param name="PaymentStatusID">The payment status identifier</param>
/// <param name="BillingFirstName">The billing first name</param>
/// <param name="BillingLastName">The billing last name</param>
/// <param name="BillingPhoneNumber">he billing phone number</param>
/// <param name="BillingEmail">The billing email</param>
/// <param name="BillingFaxNumber">The billing fax number</param>
/// <param name="BillingCompany">The billing company</param>
/// <param name="BillingAddress1">The billing address 1</param>
/// <param name="BillingAddress2">The billing address 2</param>
/// <param name="BillingCity">The billing city</param>
/// <param name="BillingStateProvince">The billing state/province</param>
/// <param name="BillingStateProvinceID">The billing state/province identifier</param>
/// <param name="BillingZipPostalCode">The billing zip/postal code</param>
/// <param name="BillingCountry">The billing country</param>
/// <param name="BillingCountryID">The billing country identifier</param>
/// <param name="ShippingStatusID">The shipping status identifier</param>
/// <param name="ShippingFirstName">The shipping first name</param>
/// <param name="ShippingLastName">The shipping last name</param>
/// <param name="ShippingPhoneNumber">The shipping phone number</param>
/// <param name="ShippingEmail">The shipping email</param>
/// <param name="ShippingFaxNumber">The shipping fax number</param>
/// <param name="ShippingCompany">The shipping company</param>
/// <param name="ShippingAddress1">The shipping address 1</param>
/// <param name="ShippingAddress2">The shipping address 2</param>
/// <param name="ShippingCity">The shipping city</param>
/// <param name="ShippingStateProvince">The shipping state/province</param>
/// <param name="ShippingStateProvinceID">The shipping state/province identifier</param>
/// <param name="ShippingZipPostalCode">The shipping zip/postal code</param>
/// <param name="ShippingCountry">The shipping country</param>
/// <param name="ShippingCountryID">The shipping country identifier</param>
/// <param name="ShippingMethod">The shipping method</param>
/// <param name="ShippingRateComputationMethodID">The shipping rate computation method identifier</param>
/// <param name="ShippedDate">The shipped date and time</param>
/// <param name="Deleted">A value indicating whether the entity has been deleted</param>
/// <param name="CreatedOn">The date and time of order creation</param>
/// <returns>Order</returns>
public abstract DBOrder InsertOrder(Guid OrderGUID, int CustomerID, int CustomerLanguageID,
int CustomerTaxDisplayTypeID, decimal OrderSubtotalInclTax, decimal OrderSubtotalExclTax,
decimal OrderShippingInclTax, decimal OrderShippingExclTax,
decimal PaymentMethodAdditionalFeeInclTax, decimal PaymentMethodAdditionalFeeExclTax,
decimal OrderTax, decimal OrderTotal, decimal OrderDiscount,
decimal OrderSubtotalInclTaxInCustomerCurrency, decimal OrderSubtotalExclTaxInCustomerCurrency,
decimal OrderShippingInclTaxInCustomerCurrency, decimal OrderShippingExclTaxInCustomerCurrency,
decimal PaymentMethodAdditionalFeeInclTaxInCustomerCurrency, decimal PaymentMethodAdditionalFeeExclTaxInCustomerCurrency,
decimal OrderTaxInCustomerCurrency, decimal OrderTotalInCustomerCurrency,
string CustomerCurrencyCode, decimal OrderWeight,
int AffiliateID, int OrderStatusID, bool AllowStoringCreditCardNumber, string CardType,
string CardName, string CardNumber, string MaskedCreditCardNumber, string CardCVV2,
string CardExpirationMonth, string CardExpirationYear, int PaymentMethodID,
string PaymentMethodName, string AuthorizationTransactionID, string AuthorizationTransactionCode,
string AuthorizationTransactionResult, string CaptureTransactionID, string CaptureTransactionResult,
string PurchaseOrderNumber, int PaymentStatusID, string BillingFirstName, string BillingLastName,
string BillingPhoneNumber, string BillingEmail, string BillingFaxNumber, string BillingCompany,
string BillingAddress1, string BillingAddress2, string BillingCity, string BillingStateProvince,
int BillingStateProvinceID, string BillingZipPostalCode, string BillingCountry,
int BillingCountryID, int ShippingStatusID, string ShippingFirstName,
string ShippingLastName, string ShippingPhoneNumber, string ShippingEmail,
string ShippingFaxNumber, string ShippingCompany, string ShippingAddress1,
string ShippingAddress2, string ShippingCity, string ShippingStateProvince,
int ShippingStateProvinceID, string ShippingZipPostalCode,
string ShippingCountry, int ShippingCountryID, string ShippingMethod, int ShippingRateComputationMethodID, DateTime? ShippedDate,
bool Deleted, DateTime CreatedOn);
/// <summary>
/// Updates the order
/// </summary>
/// <param name="OrderID">The order identifier</param>
/// <param name="OrderGUID">The order identifier</param>
/// <param name="CustomerID">The customer identifier</param>
/// <param name="CustomerLanguageID">The customer language identifier</param>
/// <param name="CustomerTaxDisplayTypeID">The customer tax display type identifier</param>
/// <param name="OrderSubtotalInclTax">The order subtotal (incl tax)</param>
/// <param name="OrderSubtotalExclTax">The order subtotal (excl tax)</param>
/// <param name="OrderShippingInclTax">The order shipping (incl tax)</param>
/// <param name="OrderShippingExclTax">The order shipping (excl tax)</param>
/// <param name="PaymentMethodAdditionalFeeInclTax">The payment method additional fee (incl tax)</param>
/// <param name="PaymentMethodAdditionalFeeExclTax">The payment method additional fee (excl tax)</param>
/// <param name="OrderTax">The order tax</param>
/// <param name="OrderTotal">The order total</param>
/// <param name="OrderDiscount">The order discount</param>
/// <param name="OrderSubtotalInclTaxInCustomerCurrency">The order subtotal incl tax (customer currency)</param>
/// <param name="OrderSubtotalExclTaxInCustomerCurrency">The order subtotal excl tax (customer currency)</param>
/// <param name="OrderShippingInclTaxInCustomerCurrency">The order shipping incl tax (customer currency)</param>
/// <param name="OrderShippingExclTaxInCustomerCurrency">The order shipping excl tax (customer currency)</param>
/// <param name="PaymentMethodAdditionalFeeInclTaxInCustomerCurrency">The payment method additional fee incl tax (customer currency)</param>
/// <param name="PaymentMethodAdditionalFeeExclTaxInCustomerCurrency">The payment method additional fee excl tax (customer currency)</param>
/// <param name="OrderTaxInCustomerCurrency">The order tax (customer currency)</param>
/// <param name="OrderTotalInCustomerCurrency">The order total (customer currency)</param>
/// <param name="CustomerCurrencyCode">The customer currency code</param>
/// <param name="OrderWeight">The order weight</param>
/// <param name="AffiliateID">The affiliate identifier</param>
/// <param name="OrderStatusID">The order status identifier</param>
/// <param name="AllowStoringCreditCardNumber">The value indicating whether storing of credit card number is allowed</param>
/// <param name="CardType">The card type</param>
/// <param name="CardName">The card name</param>
/// <param name="CardNumber">The card number</param>
/// <param name="MaskedCreditCardNumber">The masked credit card number</param>
/// <param name="CardCVV2">The card CVV2</param>
/// <param name="CardExpirationMonth">The card expiration month</param>
/// <param name="CardExpirationYear">The card expiration year</param>
/// <param name="PaymentMethodID">The payment method identifier</param>
/// <param name="PaymentMethodName">The payment method name</param>
/// <param name="AuthorizationTransactionID">The authorization transaction ID</param>
/// <param name="AuthorizationTransactionCode">The authorization transaction code</param>
/// <param name="AuthorizationTransactionResult">The authorization transaction result</param>
/// <param name="CaptureTransactionID">The capture transaction ID</param>
/// <param name="CaptureTransactionResult">The capture transaction result</param>
/// <param name="PurchaseOrderNumber">The purchase order number</param>
/// <param name="PaymentStatusID">The payment status identifier</param>
/// <param name="BillingFirstName">The billing first name</param>
/// <param name="BillingLastName">The billing last name</param>
/// <param name="BillingPhoneNumber">he billing phone number</param>
/// <param name="BillingEmail">The billing email</param>
/// <param name="BillingFaxNumber">The billing fax number</param>
/// <param name="BillingCompany">The billing company</param>
/// <param name="BillingAddress1">The billing address 1</param>
/// <param name="BillingAddress2">The billing address 2</param>
/// <param name="BillingCity">The billing city</param>
/// <param name="BillingStateProvince">The billing state/province</param>
/// <param name="BillingStateProvinceID">The billing state/province identifier</param>
/// <param name="BillingZipPostalCode">The billing zip/postal code</param>
/// <param name="BillingCountry">The billing country</param>
/// <param name="BillingCountryID">The billing country identifier</param>
/// <param name="ShippingStatusID">The shipping status identifier</param>
/// <param name="ShippingFirstName">The shipping first name</param>
/// <param name="ShippingLastName">The shipping last name</param>
/// <param name="ShippingPhoneNumber">The shipping phone number</param>
/// <param name="ShippingEmail">The shipping email</param>
/// <param name="ShippingFaxNumber">The shipping fax number</param>
/// <param name="ShippingCompany">The shipping company</param>
/// <param name="ShippingAddress1">The shipping address 1</param>
/// <param name="ShippingAddress2">The shipping address 2</param>
/// <param name="ShippingCity">The shipping city</param>
/// <param name="ShippingStateProvince">The shipping state/province</param>
/// <param name="ShippingStateProvinceID">The shipping state/province identifier</param>
/// <param name="ShippingZipPostalCode">The shipping zip/postal code</param>
/// <param name="ShippingCountry">The shipping country</param>
/// <param name="ShippingCountryID">The shipping country identifier</param>
/// <param name="ShippingMethod">The shipping method</param>
/// <param name="ShippingRateComputationMethodID">The shipping rate computation method identifier</param>
/// <param name="ShippedDate">The shipped date and time</param>
/// <param name="Deleted">A value indicating whether the entity has been deleted</param>
/// <param name="CreatedOn">The date and time of order creation</param>
/// <returns>Order</returns>
public abstract DBOrder UpdateOrder(int OrderID, Guid OrderGUID, int CustomerID, int CustomerLanguageID,
int CustomerTaxDisplayTypeID, decimal OrderSubtotalInclTax, decimal OrderSubtotalExclTax,
decimal OrderShippingInclTax, decimal OrderShippingExclTax,
decimal PaymentMethodAdditionalFeeInclTax, decimal PaymentMethodAdditionalFeeExclTax,
decimal OrderTax, decimal OrderTotal, decimal OrderDiscount,
decimal OrderSubtotalInclTaxInCustomerCurrency, decimal OrderSubtotalExclTaxInCustomerCurrency,
decimal OrderShippingInclTaxInCustomerCurrency, decimal OrderShippingExclTaxInCustomerCurrency,
decimal PaymentMethodAdditionalFeeInclTaxInCustomerCurrency, decimal PaymentMethodAdditionalFeeExclTaxInCustomerCurrency,
decimal OrderTaxInCustomerCurrency, decimal OrderTotalInCustomerCurrency,
string CustomerCurrencyCode, decimal OrderWeight,
int AffiliateID, int OrderStatusID, bool AllowStoringCreditCardNumber, string CardType,
string CardName, string CardNumber, string MaskedCreditCardNumber, string CardCVV2,
string CardExpirationMonth, string CardExpirationYear, int PaymentMethodID,
string PaymentMethodName, string AuthorizationTransactionID, string AuthorizationTransactionCode,
string AuthorizationTransactionResult, string CaptureTransactionID, string CaptureTransactionResult,
string PurchaseOrderNumber, int PaymentStatusID, string BillingFirstName, string BillingLastName,
string BillingPhoneNumber, string BillingEmail, string BillingFaxNumber, string BillingCompany,
string BillingAddress1, string BillingAddress2, string BillingCity, string BillingStateProvince,
int BillingStateProvinceID, string BillingZipPostalCode, string BillingCountry,
int BillingCountryID, int ShippingStatusID, string ShippingFirstName,
string ShippingLastName, string ShippingPhoneNumber, string ShippingEmail,
string ShippingFaxNumber, string ShippingCompany, string ShippingAddress1,
string ShippingAddress2, string ShippingCity, string ShippingStateProvince,
int ShippingStateProvinceID, string ShippingZipPostalCode,
string ShippingCountry, int ShippingCountryID, string ShippingMethod, int ShippingRateComputationMethodID, DateTime? ShippedDate,
bool Deleted, DateTime CreatedOn);
/// <summary>
/// Gets an order note
/// </summary>
/// <param name="OrderNoteID">Order note identifier</param>
/// <returns>Order note</returns>
public abstract DBOrderNote GetOrderNoteByID(int OrderNoteID);
/// <summary>
/// Gets an order notes by order identifier
/// </summary>
/// <param name="OrderID">Order identifier</param>
/// <returns>Order note collection</returns>
public abstract DBOrderNoteCollection GetOrderNoteByOrderID(int OrderID);
/// <summary>
/// Deletes an order note
/// </summary>
/// <param name="OrderNoteID">Order note identifier</param>
public abstract void DeleteOrderNote(int OrderNoteID);
/// <summary>
/// Inserts an order note
/// </summary>
/// <param name="OrderID">The order identifier</param>
/// <param name="Note">The note</param>
/// <param name="CreatedOn">The date and time of order note creation</param>
/// <returns>Order note</returns>
public abstract DBOrderNote InsertOrderNote(int OrderID, string Note, DateTime CreatedOn);
/// <summary>
/// Updates the order note
/// </summary>
/// <param name="OrderNoteID">The order note identifier</param>
/// <param name="OrderID">The order identifier</param>
/// <param name="Note">The note</param>
/// <param name="CreatedOn">The date and time of order note creation</param>
/// <returns>Order note</returns>
public abstract DBOrderNote UpdateOrderNote(int OrderNoteID, int OrderID, string Note, DateTime CreatedOn);
/// <summary>
/// Gets an order product variant
/// </summary>
/// <param name="OrderProductVariantID">Order product variant identifier</param>
/// <returns>Order product variant</returns>
public abstract DBOrderProductVariant GetOrderProductVariantByID(int OrderProductVariantID);
/// <summary>
/// Gets an order product variants by the order identifier
/// </summary>
/// <param name="OrderID">The order identifier</param>
/// <returns>Order product variant collection</returns>
public abstract DBOrderProductVariantCollection GetOrderProductVariantsByOrderID(int OrderID);
/// <summary>
/// Inserts a order product variant
/// </summary>
/// <param name="OrderID">The order identifier</param>
/// <param name="ProductVariantID">The product variant identifier</param>
/// <param name="UnitPriceInclTax">The unit price in primary store currency (incl tax)</param>
/// <param name="UnitPriceExclTax">The unit price in primary store currency (excl tax)</param>
/// <param name="PriceInclTax">The price in primary store currency (incl tax)</param>
/// <param name="PriceExclTax">The price in primary store currency (excl tax)</param>
/// <param name="UnitPriceInclTaxInCustomerCurrency">The unit price in primary store currency (incl tax)</param>
/// <param name="UnitPriceExclTaxInCustomerCurrency">The unit price in customer currency (excl tax)</param>
/// <param name="PriceInclTaxInCustomerCurrency">The price in primary store currency (incl tax)</param>
/// <param name="PriceExclTaxInCustomerCurrency">The price in customer currency (excl tax)</param>
/// <param name="AttributeDescription">The attribute description</param>
/// <param name="Quantity">The quantity</param>
/// <param name="DiscountAmountInclTax">The discount amount (incl tax)</param>
/// <param name="DiscountAmountExclTax">The discount amount (excl tax)</param>
/// <param name="DownloadCount">The download count</param>
/// <returns>Order product variant</returns>
public abstract DBOrderProductVariant InsertOrderProductVariant(int OrderID, int ProductVariantID,
decimal UnitPriceInclTax, decimal UnitPriceExclTax, decimal PriceInclTax, decimal PriceExclTax,
decimal UnitPriceInclTaxInCustomerCurrency, decimal UnitPriceExclTaxInCustomerCurrency,
decimal PriceInclTaxInCustomerCurrency, decimal PriceExclTaxInCustomerCurrency,
string AttributeDescription, int Quantity,
decimal DiscountAmountInclTax, decimal DiscountAmountExclTax, int DownloadCount);
/// <summary>
/// Updates the order product variant
/// </summary>
/// <param name="OrderProductVariantID">The order product variant identifier</param>
/// <param name="OrderID">The order identifier</param>
/// <param name="ProductVariantID">The product variant identifier</param>
/// <param name="UnitPriceInclTax">The unit price in primary store currency (incl tax)</param>
/// <param name="UnitPriceExclTax">The unit price in primary store currency (excl tax)</param>
/// <param name="PriceInclTax">The price in primary store currency (incl tax)</param>
/// <param name="PriceExclTax">The price in primary store currency (excl tax)</param>
/// <param name="UnitPriceInclTaxInCustomerCurrency">The unit price in primary store currency (incl tax)</param>
/// <param name="UnitPriceExclTaxInCustomerCurrency">The unit price in customer currency (excl tax)</param>
/// <param name="PriceInclTaxInCustomerCurrency">The price in primary store currency (incl tax)</param>
/// <param name="PriceExclTaxInCustomerCurrency">The price in customer currency (excl tax)</param>
/// <param name="AttributeDescription">The attribute description</param>
/// <param name="Quantity">The quantity</param>
/// <param name="DiscountAmountInclTax">The discount amount (incl tax)</param>
/// <param name="DiscountAmountExclTax">The discount amount (excl tax)</param>
/// <param name="DownloadCount">The download count</param>
/// <returns>Order product variant</returns>
public abstract DBOrderProductVariant UpdateOrderProductVariant(int OrderProductVariantID,
int OrderID, int ProductVariantID,
decimal UnitPriceInclTax, decimal UnitPriceExclTax, decimal PriceInclTax, decimal PriceExclTax,
decimal UnitPriceInclTaxInCustomerCurrency, decimal UnitPriceExclTaxInCustomerCurrency,
decimal PriceInclTaxInCustomerCurrency, decimal PriceExclTaxInCustomerCurrency,
string AttributeDescription, int Quantity,
decimal DiscountAmountInclTax, decimal DiscountAmountExclTax, int DownloadCount);
/// <summary>
/// Gets an order status by ID
/// </summary>
/// <param name="OrderStatusID">Order status identifier</param>
/// <returns>Order status</returns>
public abstract DBOrderStatus GetOrderStatusByID(int OrderStatusID);
/// <summary>
/// Gets all order statuses
/// </summary>
/// <returns>Order status collection</returns>
public abstract DBOrderStatusCollection GetAllOrderStatuses();
/// <summary>
/// Gets an order report
/// </summary>
/// <param name="OrderStatusID">Order status identifier; null to load all orders</param>
/// <param name="PaymentStatusID">Order payment status identifier; null to load all orders</param>
/// <param name="ShippingStatusID">Order shipping status identifier; null to load all orders</param>
/// <returns>IDataReader</returns>
public abstract IDataReader GetOrderReport(int? OrderStatusID, int? PaymentStatusID, int? ShippingStatusID);
#endregion
}
}
|
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Distributions.Fitting
{
using Accord.Math;
using System;
using System.Threading.Tasks;
/// <summary>
/// Expectation Maximization algorithm for mixture model fitting in the log domain.
/// </summary>
///
/// <typeparam name="TObservation">The type of the observations being fitted.</typeparam>
///
/// <remarks>
/// <para>
/// This class implements a generic version of the Expectation-Maximization algorithm
/// which can be used with both univariate or multivariate distribution types.</para>
/// </remarks>
///
public class LogExpectationMaximization<TObservation>
{
/// <summary>
/// Gets or sets the fitting options to be used
/// when any of the component distributions need
/// to be estimated from the data.
/// </summary>
///
public IFittingOptions InnerOptions { get; set; }
/// <summary>
/// Gets or sets convergence properties for
/// the expectation-maximization algorithm.
/// </summary>
///
public ISingleValueConvergence Convergence { get; set; }
/// <summary>
/// Gets the current coefficient values.
/// </summary>
///
public double[] Coefficients { get; private set; }
/// <summary>
/// Gets the current component distribution values.
/// </summary>
///
public IFittableDistribution<TObservation>[] Distributions { get; private set; }
/// <summary>
/// Gets the responsibility of each input vector when estimating
/// each of the component distributions, in the last iteration.
/// </summary>
///
public double[][] LogGamma { get; private set; }
/// <summary>
/// Creates a new <see cref="LogExpectationMaximization{TObservation}"/> algorithm.
/// </summary>
///
/// <param name="coefficients">The initial coefficient values.</param>
/// <param name="distributions">The initial component distributions.</param>
///
public LogExpectationMaximization(double[] coefficients,
IFittableDistribution<TObservation>[] distributions)
{
Coefficients = coefficients;
Distributions = distributions;
Convergence = new RelativeConvergence(0, 1e-3);
LogGamma = new double[coefficients.Length][];
}
/// <summary>
/// Estimates a mixture distribution for the given observations
/// using the Expectation-Maximization algorithm.
/// </summary>
///
/// <param name="observations">The observations from the mixture distribution.</param>
///
/// <returns>The log-likelihood of the estimated mixture model.</returns>
///
public double Compute(TObservation[] observations)
{
return compute(observations);
}
private double compute(TObservation[] observations)
{
// Estimation parameters
double[] coefficients = Coefficients;
var components = Distributions;
// 1. Initialize means, covariances and mixing coefficients
// and evaluate the initial value of the log-likelihood
int N = observations.Length;
// Initialize responsibilities
double[] lnnorms = new double[N];
for (int k = 0; k < LogGamma.Length; k++)
LogGamma[k] = new double[N];
// Clone the current distribution values
double[] logPi = coefficients.Log();
var pdf = new IFittableDistribution<TObservation>[components.Length];
for (int i = 0; i < components.Length; i++)
pdf[i] = (IFittableDistribution<TObservation>)components[i];
// Prepare the iteration
Convergence.NewValue = LogLikelihood(logPi, pdf, observations);
// Start
do
{
// 2. Expectation: Evaluate the component distributions
// responsibilities using the current parameter values.
Parallel.For(0, LogGamma.Length, k =>
{
double[] logGammak = LogGamma[k];
for (int i = 0; i < observations.Length; i++)
logGammak[i] = logPi[k] + pdf[k].LogProbabilityFunction(observations[i]);
});
Parallel.For(0, lnnorms.Length, i =>
{
double lnsum = Double.NegativeInfinity;
for (int k = 0; k < LogGamma.Length; k++)
lnsum = Special.LogSum(lnsum, LogGamma[k][i]);
lnnorms[i] = lnsum;
});
try
{
Parallel.For(0, LogGamma.Length, k =>
{
double[] lngammak = LogGamma[k];
double lnsum = Double.NegativeInfinity;
for (int i = 0; i < lngammak.Length; i++)
{
double value = double.NegativeInfinity;
if (lnnorms[i] != Double.NegativeInfinity)
value = lngammak[i] - lnnorms[i];
lngammak[i] = value;
lnsum = Special.LogSum(lnsum, value);
}
if (Double.IsNaN(lnsum))
lnsum = Double.NegativeInfinity;
// 3. Maximization: Re-estimate the distribution parameters
// using the previously computed responsibilities
logPi[k] = lnsum;
if (lnsum == Double.NegativeInfinity)
return;
for (int i = 0; i < lngammak.Length; i++)
lngammak[i] = Math.Exp(lngammak[i] - lnsum);
pdf[k].Fit(observations, lngammak, InnerOptions);
});
}
catch (AggregateException ex)
{
if (ex.InnerException is NonPositiveDefiniteMatrixException)
throw ex.InnerException;
}
double lnsumPi = Double.NegativeInfinity;
for (int i = 0; i < logPi.Length; i++)
lnsumPi = Special.LogSum(lnsumPi, logPi[i]);
for (int i = 0; i < logPi.Length; i++)
logPi[i] -= lnsumPi;
// 4. Evaluate the log-likelihood and check for convergence
Convergence.NewValue = LogLikelihood(logPi, pdf, observations);
} while (!Convergence.HasConverged);
double newLikelihood = Convergence.NewValue;
if (Double.IsNaN(newLikelihood) || Double.IsInfinity(newLikelihood))
throw new ConvergenceException("Fitting did not converge.");
// Become the newly fitted distribution.
for (int i = 0; i < logPi.Length; i++)
Coefficients[i] = Math.Exp(logPi[i]);
for (int i = 0; i < pdf.Length; i++)
Distributions[i] = pdf[i];
return newLikelihood;
}
/// <summary>
/// Computes the log-likelihood of the distribution
/// for a given set of observations.
/// </summary>
///
public static double LogLikelihood(double[] lnpi, IDistribution<TObservation>[] pdf,
TObservation[] observations)
{
double logLikelihood = 0.0;
#if NET35
for (int i = 0; i < observations.Length; i++)
{
var x = observations[i];
for (int k = 0; k < lnpi.Length; k++)
logLikelihood = Special.LogSum(logLikelihood, lnpi[k] + pdf[k].LogProbabilityFunction(x));
}
#else
object syncObj = new object();
Parallel.For(0, observations.Length,
() => 0.0,
(i, status, partial) =>
{
var x = observations[i];
for (int k = 0; k < lnpi.Length; k++)
partial = Special.LogSum(partial, lnpi[k] + pdf[k].LogProbabilityFunction(x));
return partial;
},
(partial) =>
{
lock (syncObj)
{
logLikelihood = Special.LogSum(logLikelihood, partial);
}
}
);
#endif
System.Diagnostics.Debug.Assert(!Double.IsNaN(logLikelihood));
return logLikelihood;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TahoeExtensions;
namespace Lesson3Example1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write some text: ");
string inputText = Console.ReadLine();
string inputTextEdit = inputText.DotifyString();
Console.WriteLine();
Console.WriteLine("Input text edited: " + inputTextEdit);
Console.WriteLine("-----------------");
Console.ReadLine();
}
}
}
|
namespace Bteam.Specifications.Tests.Fakes
{
public class FakeSpec5 : ISpecification<FakeEntity, FakeEntity, FakeEntity, FakeEntity, FakeEntity>
{
/// <summary>
/// Determines whether [is satisfied by] [the specified candidate].
/// </summary>
/// <param name="candidate">The candidate.</param>
/// <param name="candidate2">The candidate2.</param>
/// <param name="candidate3">The candidate3.</param>
/// <param name="candidate4">The candidate4.</param>
/// <param name="candidate5">The candidate5.</param>
/// <returns>
/// <c>true</c> if [is satisfied by] [the specified candidate]; otherwise, <c>false</c>.
/// </returns>
public bool IsSatisfiedBy(FakeEntity candidate, FakeEntity candidate2, FakeEntity candidate3, FakeEntity candidate4, FakeEntity candidate5)
{
return true;
}
}
} |
using UnityEngine;
using System.Collections;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System;
public static class CryptographHelper
{
private static string Base64(this string source)
{
byte[] bytes = Encoding.UTF8.GetBytes(source);
return Convert.ToBase64String(bytes, 0, bytes.Length);
}
private static byte[] FormatByte(this string strVal, Encoding encoding)
{
return encoding.GetBytes(strVal.Base64().Substring(0, 0x10).ToUpper());
}
public static string UnAesStr(this string source, string keyVal, string ivVal)
{
string str;
Encoding encoding = Encoding.UTF8;
byte[] rgbKey = keyVal.FormatByte(encoding);
byte[] rgbIV = ivVal.FormatByte(encoding);
byte[] buffer = Convert.FromBase64String(source);
Rijndael rijndael = Rijndael.Create();
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream stream2 = new CryptoStream(stream, rijndael.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
{
stream2.Write(buffer, 0, buffer.Length);
stream2.FlushFinalBlock();
str = encoding.GetString(stream.ToArray());
}
}
rijndael.Clear();
return str;
}
public static string CryptString(string source)
{
byte[] hash = Encoding.UTF8.GetBytes(source);
string outStr = System.Convert.ToBase64String(hash);
outStr = outStr.Replace("=", "");
outStr = outStr.Replace(@"/", "-");
return outStr;
}
public static byte[] Encrypt(byte[] plainBytes, byte[] Key, byte[] IV)
{
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(plainBytes, 0, plainBytes.Length);
csEncrypt.FlushFinalBlock();
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
public static byte[] Decrypt(byte[] encryptedBytes, byte[] Key, byte[] IV)
{
// Create an RijndaelManaged object
// with the specified key and IV.
byte[] original = null;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(encryptedBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (MemoryStream originalMemory = new MemoryStream())
{
byte[] Buffer = new byte[1024];
int readBytes = 0;
while ((readBytes = csDecrypt.Read(Buffer, 0, Buffer.Length)) > 0)
{
originalMemory.Write(Buffer, 0, readBytes);
}
original = originalMemory.ToArray();
}
}
}
}
return original;
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YoctoScheduler.Core.Database
{
public class Configuration
{
protected Dictionary<string, string> _config = new Dictionary<string, string>();
public string this[string key]
{
get
{
return _config[key];
}
}
public Configuration(SqlConnection conn)
{
using (SqlCommand cmd = new SqlCommand(tsql.Extractor.Get("Configuration.GetAll"), conn))
{
cmd.Prepare();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
_config[reader.GetString(0)] = reader.GetString(1);
}
}
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class ChaoHueristicScript : HueristicScript {
GameObject[,] pos;
public override float Hueristic(int x, int y, Vector3 start, Vector3 goal, GridScript gridScript){
pos = gridScript.GetGrid();
GameObject go = pos[x,y];
Material mat = go.GetComponent<MeshRenderer>().sharedMaterial;
if (mat.name == "Forest" || mat.name == "Water") {
return 1000000000;
}
else return 0;
}
}
|
namespace Mixed_Phones
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class MixedPhones
{
public static void Main(string[] args)
{
//read command for phone and name;
var command = Console.ReadLine();
//dictionary for phone book;
var phoneBook = new Dictionary<string, long>();
while (command != "Over")
{
//var for left command;
var leftCommand = command.Split(new string[] {" : "}, StringSplitOptions.RemoveEmptyEntries)[0];
//var for right operand;
var rightCommand = command.Split(new string[] { " : " }, StringSplitOptions.RemoveEmptyEntries)[1];
//var for key for phone book;
var key = "";
//var for value for phone book;
var value = 0L;
if (CheckOnlyDigit(leftCommand))
{
key = rightCommand;
value = long.Parse(leftCommand);
}
else
{
key = leftCommand;
value = long.Parse(rightCommand);
}
//fill the phone book;
if (!phoneBook.ContainsKey(key))
{
phoneBook.Add(key, value);
}
else
{
phoneBook[key] = value;
}
command = Console.ReadLine();
}//end of while loop;
foreach (var item in phoneBook.OrderBy(x => x.Key))
{
Console.WriteLine("{0} -> {1}", item.Key, item.Value);
}
}
//method to check if string is only digit;
public static bool CheckOnlyDigit(string value)
{
return value.All(x => Char.IsDigit(x));
}
}
}
|
//
// - RegexValueSerializer.cs -
//
// Copyright 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Text.RegularExpressions;
namespace Carbonfrost.Commons.PropertyTrees.ValueSerializers {
class RegexValueSerializer : ValueSerializer {
public override object ConvertFromString(string text, Type destinationType, IValueSerializerContext context) {
if (text != null)
return new Regex(text);
return base.ConvertFromString(text, destinationType, context);
}
public override string ConvertToString(object value, IValueSerializerContext context) {
if (value == null)
throw new ArgumentNullException("value");
Regex r = value as Regex;
if (r != null) {
return value.ToString();
}
return base.ConvertToString(value, context);
}
}
}
|
using CTB.Entities;
using SIC.BL;
using SIC.Site.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace SIC.Site.Controllers
{
[Authorize]
public class DireccionController : Controller
{
private IPersonaService personaService;
private Parametros parametros;
public DireccionController(IPersonaService personaService, Parametros parametros)
{
this.personaService = personaService;
this.parametros = parametros;
}
public ActionResult Index()
{
return View();
}
public ActionResult Create(int Persona)
{
ViewData["TipDomicilio"] = parametros.getTipDomicilio();
ViewData["TipVia"] = parametros.getTipVia();
ViewData["TipZona"] = parametros.getTipZona();
Session["PER_COD"] = Persona;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(GEN_PER_DIR Model)
{
if (this.ModelState.IsValid)
{
Model.PER_COD = (int)Session["PER_COD"];
Model.PER_DIR_COM = parametros.obtenerDscTipVia(Model.PER_DIR_TIP_VIA) + " " + Model.PER_DIR_NOM_VIA + " Nro." + Model.PER_DIR_NRO_VIA ;
this.personaService.CreateDireccion(Model);
Session["PER_COD"] = null;
return this.RedirectToAction("DetailContribuyente", "Contribuyente", new { id = Model.PER_COD });
}
else
{
return View(Model);
}
}
public ActionResult Edit(long? id)
{
long? per_cod = 0;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
GEN_PER_DIR direccion = this.personaService.GetOneDireccion(per_cod, id);
if (direccion == null)
{
return HttpNotFound();
}
ViewData["TipDomicilio"] = parametros.getTipDomicilio();
ViewData["TipVia"] = parametros.getTipVia();
ViewData["TipZona"] = parametros.getTipZona();
Session["PER_COD"] = direccion.PER_COD;
return View(direccion);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(GEN_PER_DIR direccion)
{
if (ModelState.IsValid)
{
direccion.PER_DIR_COM = parametros.obtenerDscTipVia(direccion.PER_DIR_TIP_VIA) + " " + direccion.PER_DIR_NOM_VIA + " Nro." + direccion.PER_DIR_NRO_VIA;
this.personaService.EditDireccion(direccion);
return this.RedirectToAction("DetailContribuyente", "Contribuyente", new { id = direccion.PER_COD });
}
else
{
return View(direccion);
}
}
public ActionResult Details(long? id)
{
long? per_cod = 0;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
GEN_PER_DIR direccion = this.personaService.GetOneDireccion(per_cod, id);
if (direccion == null)
{
return HttpNotFound();
}
ViewData["TipDomicilio"] = parametros.getTipDomicilio();
ViewData["TipVia"] = parametros.getTipVia();
ViewData["TipZona"] = parametros.getTipZona();
Session["PER_COD"] = direccion.PER_COD;
return View(direccion);
}
public ActionResult Delete(long? id)
{
long? per_cod = 0;
GEN_PER_DIR direccion = this.personaService.GetOneDireccion(per_cod, id);
ViewData["TipDomicilio"] = parametros.getTipDomicilio();
ViewData["TipVia"] = parametros.getTipVia();
ViewData["TipZona"] = parametros.getTipZona();
Session["PER_COD"] = direccion.PER_COD;
return View(direccion);
}
[HttpPost]
[ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult PostDelete(int id)
{
long? per_cod = 0;
GEN_PER_DIR direccion = this.personaService.GetOneDireccion(per_cod, id);
if (direccion != null)
{
try
{
per_cod = direccion.PER_COD;
this.personaService.DeleteDireccion(direccion);
}
catch (Exception ex)
{
this.ModelState.AddModelError("", ex);
ViewData["TipDomicilio"] = parametros.getTipDomicilio();
ViewData["TipVia"] = parametros.getTipVia();
ViewData["TipZona"] = parametros.getTipZona();
Session["PER_COD"] = direccion.PER_COD;
return View(direccion);
}
}
return this.RedirectToAction("DetailContribuyente", "Contribuyente", new { id = per_cod });
}
}
} |
using PMA.Store_Domain.Masters.Entities;
using PMA.Store_Framework.Domain;
namespace PMA.Store_Domain.Orders.Entities
{
public class OrderLine : BaseEntity
{
public Order Order { get; set; }
public long OrderId { get; set; }
public long MasterProductsId { get; set; }
public MasterProduct MasterProduct { get; set; }
public int Count { get; set; }
public long Price { get; set; }
public long Discount { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum TerrierState { SLEEPING, AWAKE }
public class TerrierSpawner : MonoBehaviour
{
public GameObject CoalBall;
public float SpawnFrequency = 1000;
public SpriteRenderer Glow;
public float GlowDuration = .5f;
public TerrierState Status;
private float m_counter;
private static Queue<GameObject> m_ballPool;
private Animator m_animator;
private Color m_glowColor;
private static Color m_transparent;
public static List<TerrierSpawner> AwokeTerriers;
// Start is called before the first frame update
void Start()
{
AwokeTerriers = new List<TerrierSpawner>();
m_animator = GetComponent<Animator>();
if (m_ballPool == null)
{
m_ballPool = new Queue<GameObject>();
}
m_ballPool.Clear(); // Because of fast play mode, doesn't reload static vars
Status = TerrierState.SLEEPING;
m_counter = SpawnFrequency;
m_glowColor = Glow.color;
m_transparent = new Color(m_glowColor.r, m_glowColor.g, m_glowColor.b, 0.2f);
Glow.color = m_transparent;
}
// Update is called once per frame
void Update()
{
switch (Status)
{
case TerrierState.AWAKE:
if (m_counter < SpawnFrequency)
{
m_counter += Time.deltaTime;
} else
{
m_counter = 0;
NewBallAt(transform.position);
}
break;
case TerrierState.SLEEPING:
break;
}
}
public void Awaken()
{
if (Status == TerrierState.AWAKE)
{
return;
}
Status = TerrierState.AWAKE;
StartCoroutine(GlowOn());
if (WorldGenerator.Instance.PlayerInstance.transform.position.x < transform.position.x)
{
m_animator.SetTrigger("Left");
} else
{
m_animator.SetTrigger("Right");
}
AwokeTerriers.Add(this);
}
public void PutToSleep()
{
if (Status == TerrierState.SLEEPING)
{
return;
}
Status = TerrierState.SLEEPING;
StartCoroutine(GlowOff());
AwokeTerriers.Remove(this);
}
private IEnumerator GlowOn()
{
float d = 0;
while (d < GlowDuration)
{
d += Time.deltaTime;
var r = Mathf.Lerp(m_transparent.r, m_glowColor.r, d / GlowDuration);
var g = Mathf.Lerp(m_transparent.g, m_glowColor.g, d / GlowDuration);
var b = Mathf.Lerp(m_transparent.b, m_glowColor.b, d / GlowDuration);
var a = Mathf.Lerp(m_transparent.a, m_glowColor.a, d / GlowDuration);
Glow.color = new Color(r, g, b, a);
yield return null;
}
}
private IEnumerator GlowOff()
{
float d = 0;
while (d < GlowDuration)
{
d += Time.deltaTime;
var r = Mathf.Lerp(m_glowColor.r, m_transparent.r, d / GlowDuration);
var g = Mathf.Lerp(m_glowColor.g, m_transparent.g, d / GlowDuration);
var b = Mathf.Lerp(m_glowColor.b, m_transparent.b, d / GlowDuration);
var a = Mathf.Lerp(m_glowColor.a, m_transparent.a, d / GlowDuration);
Glow.color = new Color(r, g, b, a);
yield return null;
}
}
private void NewBallAt(Vector3 pos)
{
if (m_ballPool.Count == 0)
{
Instantiate(CoalBall, pos, Quaternion.identity);
} else
{
var gO = m_ballPool.Dequeue();
gO.SetActive(true);
gO.transform.position = pos;
gO.GetComponent<CoalBall>().Init();
}
}
public static void ReleaseBall(GameObject gO)
{
gO.SetActive(false);
m_ballPool.Enqueue(gO);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("LightFire"))
{
AwokeTerriers.Remove(this);
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("LightFire"))
{
if (!AwokeTerriers.Contains(this))
{
AwokeTerriers.Add(this);
}
}
}
}
|
using System;
using System.ComponentModel;
using System.Diagnostics;
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;
using System.Linq;
namespace ControleDeGastos
{
public class CurrencyViewModel : INotifyPropertyChanged
{
private long _MOE_ID;
/// <summary>
/// Sample accountsModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public long MOE_ID
{
get
{
return _MOE_ID;
}
set
{
if (value != _MOE_ID)
{
_MOE_ID = value;
NotifyPropertyChanged("MOE_ID");
}
}
}
private string _MOE_NOME;
/// <summary>
/// Sample accountsModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public string MOE_NOME
{
get
{
return _MOE_NOME;
}
set
{
if (value != _MOE_NOME)
{
_MOE_NOME = value;
NotifyPropertyChanged("MOE_NOME");
}
}
}
private decimal _MOE_COTACAO;
/// <summary>
/// Sample accountsModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public decimal MOE_COTACAO
{
get
{
return _MOE_COTACAO;
}
set
{
if (value != _MOE_COTACAO)
{
_MOE_COTACAO = value;
NotifyPropertyChanged("MOE_COTACAO");
}
}
}
private bool _MOE_PADRAO;
/// <summary>
/// Sample accountsModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public bool MOE_PADRAO
{
get
{
return _MOE_PADRAO;
}
set
{
if (value != _MOE_PADRAO)
{
_MOE_PADRAO = value;
NotifyPropertyChanged("MOE_PADRAO");
}
}
}
private string _MOE_SIGLA;
/// <summary>
/// Sample accountsModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public string MOE_SIGLA
{
get
{
return _MOE_SIGLA;
}
set
{
if (value != _MOE_SIGLA)
{
_MOE_SIGLA = value;
NotifyPropertyChanged("MOE_SIGLA");
}
}
}
private bool _MOE_FLAG_ATIVA;
/// <summary>
/// Sample accountsModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public bool MOE_FLAG_ATIVA
{
get
{
return _MOE_FLAG_ATIVA;
}
set
{
if (value != _MOE_FLAG_ATIVA)
{
_MOE_FLAG_ATIVA = value;
NotifyPropertyChanged("MOE_FLAG_ATIVA");
}
}
}
private string _MOE_OBSERVACAO;
/// <summary>
/// Sample accountsModel property; this property is used in the view to display its value using a Binding.
/// </summary>
/// <returns></returns>
public string MOE_OBSERVACAO
{
get
{
return _MOE_OBSERVACAO;
}
set
{
if (value != _MOE_OBSERVACAO)
{
_MOE_OBSERVACAO = value;
NotifyPropertyChanged("MOE_OBSERVACAO");
}
}
}
public IList<TB_MOEDA> GetCurrency()
{
IList<TB_MOEDA> list = null;
using (var ctx = new ControleDeGastosDataContext(App.Connection))
{
IQueryable<TB_MOEDA> query = ctx.TB_MOEDAs;
list = query.ToList();
}
return list;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
} |
using System;
using DAL.Model;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace DAL
{
public class DatabaseContext : IdentityDbContext<UserAccount>
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Answer>().HasData(
new Answer {Text = "Krowa dająca mleko", IsAppropriate = true, Id = 1},
new Answer {Text = "Jeżyk w lesie", IsAppropriate = true, Id = 2},
new Answer {Text = "Blender i coś obok", IsAppropriate = true, Id = 3},
new Answer {Text = "Spodenki do ćpania", IsAppropriate = true, Id = 4},
new Answer {Text = "Pokaz tanców ognia", IsAppropriate = true, Id = 5},
new Answer {Text = "Chleb z cukrem", IsAppropriate = true, Id = 6},
new Answer {Text = "Ananas na pizzy", IsAppropriate = true, Id = 7},
new Answer {Text = "Ruch antyszczepionkowców", IsAppropriate = true, Id = 8},
new Answer {Text = "Hakuje mainframe", IsAppropriate = true, Id = 9},
new Answer {Text = "Kopsnij ino piątaka ksieciuniu", IsAppropriate = true, Id = 10},
new Answer {Text = "Gdzie jest nemo?", IsAppropriate = true, Id = 11},
new Answer {Text = "Żelatyna", IsAppropriate = true, Id = 12});
}
public DbSet<UserAccount> UserAccounts { get; set; }
public DbSet<Room> Rooms { get; set; }
public DbSet<RoomConnection> RoomConnections { get; set; }
public DbSet<Answer> Answers { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class IncorruptEdu_EdayQuestionundoList : System.Web.UI.Page
{
string strwhere;
public string t_rand = "";
PDTech.OA.BLL.OA_EDUQUESTION edubll = new PDTech.OA.BLL.OA_EDUQUESTION();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txteTime.Text = DateTime.Now.ToShortDateString();
if (DateTime.Now.Day > 26)
{
BindData();
}
}
}
private void BindData()
{
t_rand = DateTime.Now.ToString("yyyyMMddHHmmssff");
int record = 0;
IList<PDTech.OA.Model.OA_EDUQUESTION> edayList = new List<PDTech.OA.Model.OA_EDUQUESTION>();
//strwhere = new StringBuilder();
//strwhere.Append(string.Format(" ANSWER_PERSON={0}", CurrentAccount.USER_ID));
//if (!string.IsNullOrEmpty(txtsTime.Text.Trim()))
//{
// strwhere.Append(string.Format(@" AND DATEDIFF(DAY,ANSWER_TIME,'{0}')<=0", (Convert.ToDateTime(txtsTime.Text).ToString("yyyy-MM-dd"))));
//}
//if (!string.IsNullOrEmpty(txteTime.Text.Trim()))
//{
// strwhere.Append(string.Format(@" AND DATEDIFF(DAY,ANSWER_TIME,'{0}')>=0 ", (Convert.ToDateTime(txteTime.Text).ToString("yyyy-MM-dd"))));
//}
strwhere = string.Format("ANSWER_PERSON={0} and ANSWER_TIME>=(CONVERT(varchar(7), getdate() , 120) + '-1')",CurrentAccount.USER_ID.ToString());
edayList = edubll.Get_Paging_List_ByCondition(strwhere, AspNetPager.PageSize, AspNetPager.CurrentPageIndex, out record);
rpt_EdayQuestionList.DataSource = edayList;
rpt_EdayQuestionList.DataBind();
AspNetPager.RecordCount = record;
}
protected void AspNetPager_PageChanged(object sender, EventArgs e)
{
BindData();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
BindData();
}
} |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(PWA_Maesai.Startup))]
namespace PWA_Maesai
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public AudioSource carCrash;
public AudioSource carEnter;
public void carCrashTurnOn()
{
if(carCrash.isPlaying == false)
{
carCrash.Play();
// Debug.Log("Çalıyor");
}
}
public void carEnterTurnOn()
{
if(carEnter.isPlaying == false)
{
carEnter.Play();
}
}
}
|
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class MeshCombiner : MonoBehaviour
{
/* public void AdvancedCombineMeshes()
{
MeshFilter myMeshFilter = GetComponent<MeshFilter>();
MeshRenderer myMeshRenderer = GetComponent<MeshRenderer>();
Mesh finalMesh = myMeshFilter.sharedMesh;
var transform1 = transform;
Quaternion oldRot = transform1.rotation;
Vector3 oldPos = transform1.position;
transform1.rotation = Quaternion.identity;
transform1.position = Vector3.zero;
if (finalMesh == null)
{
finalMesh = new Mesh();
myMeshFilter.sharedMesh = finalMesh;
}
else
{
finalMesh.Clear();
}
// Every MeshFilter (Parent included)
MeshFilter[] filters = GetComponentsInChildren<MeshFilter>(false);
// All the meshes in our children (just a big list)
List<Material> materials = new List<Material>();
MeshRenderer[] renderers = GetComponentsInChildren<MeshRenderer>(false);
foreach (MeshRenderer rend in renderers)
{
if (rend.transform == transform)
continue;
Material[] localMats = rend.sharedMaterials;
foreach (Material localMat in localMats)
if (!materials.Contains (localMat))
materials.Add (localMat);
}
// Each material will have a mesh for it.
List<Mesh> subMeshes = new List<Mesh>();
foreach (Material material in materials)
{
// Make a combiner for each (sub)mesh that is mapped to the right material.
List<CombineInstance>combiners = new List<CombineInstance>();
foreach (MeshFilter filter in filters)
{
if (filter.transform == transform)
continue;
// The mesh-renderer holds the reference to the material(s)
MeshRenderer rend = filter.GetComponent<MeshRenderer>();
if (rend == null)
{
Debug.LogError (filter.name + " has no MeshRenderer");
continue;
}
// Let's see if their materials are the one we want right now.
Material[] localMaterials = rend.sharedMaterials;
for (int materialIndex = 0; materialIndex < localMaterials.Length; materialIndex++)
{
if (localMaterials [materialIndex] != material)
continue;
// This sub-mesh is the material we're looking for right now.
CombineInstance ci = new CombineInstance
{
mesh = filter.sharedMesh,
subMeshIndex = materialIndex,
transform = filter.transform.localToWorldMatrix
};
combiners.Add (ci);
}
}
// Flatten into a single mesh.
Mesh mesh = new Mesh ();
mesh.CombineMeshes (combiners.ToArray(), true);
subMeshes.Add(mesh);
}
// The final mesh: combine all the material-specific meshes as independent sub-meshes.
List<CombineInstance>finalCombiners = new List<CombineInstance>();
foreach (Mesh mesh in subMeshes)
{
CombineInstance ci = new CombineInstance
{
mesh = mesh,
subMeshIndex = 0,
transform = Matrix4x4.identity
};
finalCombiners.Add (ci);
}
finalMesh.CombineMeshes (finalCombiners.ToArray(), false);
myMeshFilter.sharedMesh = finalMesh;
myMeshRenderer.sharedMaterials = materials.ToArray();
Debug.Log ("Final mesh has " + subMeshes.Count + " materials.");
//Reset the position to how it was before
transform1.rotation = oldRot;
transform1.position = oldPos;
//Hide the pieces (you can also delete them, but then you won't be able to make changes)
for (int a = 0; a < transform.childCount; a++)
{
transform.GetChild(a).gameObject.SetActive(false);
}
}
public void SaveMesh(string path)
{
Debug.Log ("Saving Mesh?");
string fullPath = path + transform.name + ".asset";
Mesh m1 = transform.GetComponent<MeshFilter>().sharedMesh;
if (AssetDatabase.Contains(m1))
{
Debug.Log("Mesh is already saved! Mesh will be overridden on combine!");
return;
}
if (AssetDatabase.LoadAssetAtPath(fullPath, typeof(Mesh)) != null)
AssetDatabase.DeleteAsset(fullPath);
AssetDatabase.CreateAsset(m1, fullPath); // saves to "assets/"
AssetDatabase.SaveAssets();
}*/
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JoveZhao.Framework.ScheduleTask
{
public class OneTimeSchedule : Schedule
{
DateTime _startTime;
public OneTimeSchedule(DateTime startTime)
{
this._startTime = startTime;
}
public override DateTime GetNextExecuteTime()
{
DateTime now = DateTime.Now;
if (_startTime > now)
return _startTime;
else
return DateTime.MaxValue;
}
}
}
|
using DryIoc;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol.Progress;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Client
{
internal class WorkspaceLanguageClient : LanguageProtocolProxy, IWorkspaceLanguageClient
{
public WorkspaceLanguageClient(
IResponseRouter requestRouter, IResolverContext resolverContext, IProgressManager progressManager,
ILanguageProtocolSettings languageProtocolSettings
) : base(requestRouter, resolverContext, progressManager, languageProtocolSettings)
{
}
}
}
|
using Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAccessLayer.Repository
{
public class UserRepository :BaseRepository<User>
{
public UserRepository(DatabaseContext context):base(context)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class mainmenu : MonoBehaviour
{
public GameObject coni;
public GameObject anamenu;
private void Start()
{
Time.timeScale = 1f;
}
public void Startgo()
{
Time.timeScale = 0;
coni.SetActive(true);
anamenu.SetActive(false);
audiosc.PlaySound("button");
}
public void mapback()
{
audiosc.PlaySound("button");
coni.SetActive(true);
}
public void Quit()
{
audiosc.PlaySound("button");
Application.Quit();
}
public void Garage()
{
audiosc.PlaySound("button");
SceneManager.LoadScene(1);
}
public void Jail()
{
audiosc.PlaySound("button");
SceneManager.LoadScene(2);
}
public void back()
{
audiosc.PlaySound("button");
coni.SetActive(false);
anamenu.SetActive(true);
}
public void play()
{
audiosc.PlaySound("button");
SceneManager.LoadScene( 3);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrailColor : MonoBehaviour {
private TrailRenderer trailRenderer;
// Use this for initialization
void Start () {
trailRenderer = GetComponent<TrailRenderer>();
}
public void SetColor(Color c)
{
trailRenderer.materials[0].SetColor("_Color", c);
}
}
|
using FatCat.Nes.OpCodes.ClearingFlags;
using JetBrains.Annotations;
namespace FatCat.Nes.Tests.OpCodes.ClearingFlags
{
[UsedImplicitly]
public class ClearOverflowFlagTests : ClearFlagTests
{
protected override string ExpectedName => "CLV";
protected override CpuFlag Flag => CpuFlag.Overflow;
public ClearOverflowFlagTests() => opCode = new ClearOverflowFlag(cpu, addressMode);
}
} |
using Peppy.Core.Amqp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace Peppy
{
public class RabbitMQReceiveAttribute : AmqpAttribute
{
public RabbitMQReceiveAttribute(string exchangeName, string queueName)
: base(exchangeName, queueName)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace oopsconcepts
{
// Structs
//Just like Classes Structs can have
//1) Private Fields
//2)Public Properties
//3) COnstructors
//4)Methods
//Object Initializers Syntax introduced in C# 3.0 can be used to initialize either
//a struct or a class
//Note: there are several differeces between Class and Structucts
interface Emp
{
void test();
}
public struct Structure:Emp
{
private int _id;
private string _name;
public int ID
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public Structure(int id, string name)
{
this._id = id;
this._name = name;
}
public void test()
{
Console.WriteLine("Test the Interface method");
}
public void fullname()
{
Console.WriteLine("Employee ID " + ID);
Console.WriteLine("Employee Full name " + Name);
}
}
public class sample_Ex
{
public static void Main()
{
Structure st = new Structure();
st.ID = 10;
st.Name = "Suresh";
st.test();
st.fullname();
Structure constructorobj = new Structure(20, "suresh mogulada");
constructorobj.fullname();
//Object initializer from C# 3.0
Structure objin = new Structure
{
ID = 30,
Name = "Suresh kumar moguldala"
};
objin.fullname();
Console.ReadKey();
}
}
}
|
namespace Plus.Communication.Packets.Outgoing.Navigator
{
internal class CanCreateRoomComposer : MessageComposer
{
public bool Error { get; }
public int MaxRoomsPerUser { get; }
public CanCreateRoomComposer(bool error, int maxRoomsPerUser)
: base(ServerPacketHeader.CanCreateRoomMessageComposer)
{
Error = error;
MaxRoomsPerUser = maxRoomsPerUser;
}
public override void Compose(ServerPacket packet)
{
packet.WriteInteger(Error ? 1 : 0);
packet.WriteInteger(MaxRoomsPerUser);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP.ShareNS.Exceptions
{
/**
* Exception for illegal attempts to modify an id of a share
* @since 9.1.0
*/
class IllegalIDChangeException : GenericShareException { }
}
|
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace IssueLog_Api.Models
{
public class IssueLogDbContext : IdentityDbContext<ApplicationUser>
{
public IssueLogDbContext():base("IssueLogDbContext")
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<Issue> Issues { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//AspNetUsers -> User
modelBuilder.Entity<ApplicationUser>()
.ToTable("User");
//AspNetRoles -> Role
modelBuilder.Entity<IdentityRole>()
.ToTable("Role");
//AspNetUserRoles -> UserRole
modelBuilder.Entity<IdentityUserRole>()
.ToTable("UserRole");
//AspNetUserClaims -> UserClaim
modelBuilder.Entity<IdentityUserClaim>()
.ToTable("UserClaim");
//AspNetUserLogins -> UserLogin
modelBuilder.Entity<IdentityUserLogin>()
.ToTable("UserLogin");
modelBuilder.Entity<Project>()
.HasRequired(m => m.ProjectManager)
.WithMany(t => t.ProjectManager)
.HasForeignKey(m => m.ProjectManagerId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Project>()
.HasRequired(m => m.Client)
.WithMany(t => t.Client)
.HasForeignKey(m => m.ClientId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Project>()
.HasRequired(m => m.ProjectLeader)
.WithMany(t => t.ProjectLeader)
.HasForeignKey(m => m.ProjectLeaderId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Issue>()
.HasRequired(m => m.Project)
.WithMany(t => t.Issues)
.HasForeignKey(m => m.ProjectId)
.WillCascadeOnDelete(false);
}
}
} |
namespace Fano
{
public static class Utilities
{
public static bool IsSequenceEqual(WordFrequency bitArray1, WordFrequency bitArray2)
{
if (bitArray1.Word.Length != bitArray2.Word.Length)
{
return false;
}
for (int i = 0; i < bitArray1.Word.Length; i++)
{
if (bitArray1.Word[i] != bitArray2.Word[i])
{
return false;
}
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace innovation4austria.web.Models.Ausstattung
{
public class AusstattungModel
{
public int ID { get; set; }
public string Bezeichnung { get; set; }
}
} |
/********************************************************************
* FulcrumWeb RAD Framework - Fulcrum of your business *
* Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED *
* *
* THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED *
* FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE *
* COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE *
* AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT *
* AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE *
* AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. *
********************************************************************/
using System;
using System.Collections;
using System.Xml;
using Framework.Utils;
using System.Collections.Generic;
namespace Framework.Metadata
{
/// <summary>
/// Class that holds information about child entity usage.
/// </summary>
public class CxEntityUsageToEditMetadata : CxMetadataObject
{
//----------------------------------------------------------------------------
protected List<string> m_PKColumns = null; // List of primary key columns to use to find entity
protected List<string> m_Columns = null; // List of columns that should corresponds to the entity usage
//----------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
/// <param name="element">XML element that holds metadata</param>
public CxEntityUsageToEditMetadata(CxMetadataHolder holder, XmlElement element) :
base(holder, element, "child_id")
{
m_PKColumns = CxText.DecomposeWithSeparator(this["pk_columns"], ",");
m_Columns = CxText.DecomposeWithSeparator(this["columns"].ToUpper(), ",");
}
//----------------------------------------------------------------------------
/// <summary>
/// List of primary key columns to use to find entity.
/// </summary>
public List<string> PKColumns
{
get { return m_PKColumns; }
}
//----------------------------------------------------------------------------
/// <summary>
/// ID of the entity usage to edit.
/// </summary>
public string EntityUsageId
{
get { return this["entity_usage_id"]; }
}
//----------------------------------------------------------------------------
/// <summary>
/// Entity usage to edit.
/// </summary>
public CxEntityUsageMetadata EntityUsage
{
get { return Holder.EntityUsages[EntityUsageId]; }
}
//----------------------------------------------------------------------------
/// <summary>
/// ID of the entity usage chooser class.
/// </summary>
public string ChooserClassId
{
get { return this["chooser_class_id"]; }
}
//----------------------------------------------------------------------------
/// <summary>
/// Entity usage chooser class.
/// </summary>
public CxClassMetadata ChooserClass
{
get { return Holder.Classes[ChooserClassId]; }
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns true if the given column should be edited by this entity usage.
/// </summary>
/// <param name="columnName">name of the column to check</param>
/// <param name="exact">if false an ansence of column names means compliance</param>
/// <returns>true if the given column should be edited by this entity usage</returns>
public bool Complies(string columnName, bool exact)
{
return ((m_Columns.Count == 0 && ! exact) ||
m_Columns.IndexOf(columnName.ToUpper()) != -1);
}
//----------------------------------------------------------------------------
}
}
|
using QuestomAssets.BeatSaber;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Collections.Specialized;
namespace QuestomAssets
{
public class MusicConfigCache
{
//keyed on PlaylistID (aka PackID)
public Dictionary<string, PlaylistAndSongs> PlaylistCache { get; } = new Dictionary<string, PlaylistAndSongs>();
//keyed on SongID (aka LevelID)
public Dictionary<string, SongAndPlaylist> SongCache { get; } = new Dictionary<string, SongAndPlaylist>();
//we will see if this cache is enough of a performance boost to warrant the extra hassle of keeping it up to date
public MusicConfigCache(MainLevelPackCollectionObject mainPack)
{
Log.LogMsg("Building cache...");
Stopwatch sw = new Stopwatch();
try
{
sw.Start();
PlaylistCache.Clear();
SongCache.Clear();
int plCtr = 0;
foreach (var x in mainPack.BeatmapLevelPacks)
{
if (PlaylistCache.ContainsKey(x.Object.PackID))
{
Log.LogErr($"Cache building: playlist ID {x.Object.PackID} exists multiple times in the main level list! Skipping redundant copies...");
}
else
{
var pns = new PlaylistAndSongs() { Playlist = x.Object, Order = plCtr };
int ctr = 0;
foreach (var y in x.Object.BeatmapLevelCollection.Object.BeatmapLevels)
{
if (pns.Songs.ContainsKey(y.Object.LevelID))
{
Log.LogErr($"Cache building: song ID {y.Object.LevelID} exists multiple times in playlist {x.Object.PackID}!");
}
else
{
pns.Songs.Add(y.Object.LevelID, new OrderedSong() { Song = y.Object, Order = ctr });
}
if (SongCache.ContainsKey(y.Object.LevelID))
{
Log.LogErr($"Cache building: cannot add song ID {y.Object.LevelID} in playlist ID {x.Object.PackID} because it already exists in {SongCache[y.Object.LevelID].Playlist.PackID}!");
}
else
{
SongCache.Add(y.Object.LevelID, new SongAndPlaylist() { Song = y.Object, Playlist = x.Object });
}
ctr++;
}
PlaylistCache.Add(x.Object.PackID, pns);
plCtr++;
}
}
sw.Stop();
Log.LogMsg($"Building cache took {sw.ElapsedMilliseconds}ms");
}
catch (Exception ex)
{
Log.LogErr("Exception building cache!", ex);
throw;
}
}
public class PlaylistAndSongs
{
public int Order { get; set; }
public BeatmapLevelPackObject Playlist { get; set; }
public Dictionary<string, OrderedSong> Songs = new Dictionary<string, OrderedSong>();
}
public class SongAndPlaylist
{
public BeatmapLevelPackObject Playlist { get; set; }
public BeatmapLevelDataObject Song { get; set; }
}
public class OrderedSong
{
public int Order { get; set; }
public BeatmapLevelDataObject Song { get; set; }
}
}
}
|
namespace NodeGraph.View {
public class NodeFlowPortView : NodePortView {
#region Constructor
public NodeFlowPortView(bool isInput) : base(isInput) {
//
}
#endregion // Constructor
}
}
|
using BusinessLogic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LinkCloud.Areas.Admin.Controllers
{
public class BaseAdminController : Controller
{
protected AdminBL objAdminBL;
public BaseAdminController()
{
objAdminBL = new AdminBL();
}
}
} |
using System;
using System.Collections.Generic;
using Athena.Data;
using Athena.Data.StoragePlaces;
namespace AthenaTests.Helpers.Data.Lists {
public class StoragePlacesListGenerator {
public static List<StoragePlace> Generate() {
return new List<StoragePlace> {
new StoragePlace {
Id = Guid.NewGuid(),
StoragePlaceName = "Biurko Anki",
Comment = null
},
new StoragePlace {
Id = Guid.NewGuid(),
StoragePlaceName = "V",
Comment = "Białe, po butach"
}
};
}
}
} |
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Netfilmes.Business.Entidades;
using Netfilmes.Repository.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Netfilmes.Repository.Classes
{
public class FilmeDAO : IFilmeDAO
{
private String _connectionString;
private SqlConnection _databaseConnection;
public FilmeDAO(IConfiguration configuration)
{
_connectionString = configuration["ConnectionStrings"];
}
// Recebe um objeto do tipo Filme e o insere ou atualiza um registro dele já existente no banco
public bool Cadastrar(Filme filme)
{
try
{
// Cria uma instancia de ApplicationContext
using (var applicationContext = new ApplicationContext())
{
// Se a entidade possuir um Id, então a operação de atualização será executada,
// caso contrário, a operação de inserção será executada
if (filme.Id > 0)
{
// Altera um objeto do tipo filme no banco de dados
applicationContext.Filme.Update(filme);
}
else
{
// Adiciona o objeto do tipo Filme a ser gravado no banco de dados
applicationContext.Filme.Add(filme);
}
// Realiza a operação de inserção ou alteração, dependendo do estado do objeto
return applicationContext.SaveChanges() > 0;
}
}
catch (Exception e)
{
throw e;
}
}
// Lista todos os filmes cadastrados no banco de dados
public List<Filme> ListarTodos()
{
List<Filme> filmes = null;
// Define o código SQL a ser executado
StringBuilder sql = new StringBuilder();
sql.Append(" SELECT ");
sql.Append(" F.* ");
sql.Append(" , G.* ");
sql.Append(" , L.* ");
sql.Append(" FROM Filme F ");
sql.Append(" LEFT JOIN Genero G ON F.GeneroId = G.Id ");
sql.Append(" LEFT JOIN Locacao L ON F.LocacaoId = L.Id ");
sql.Append(" ORDER BY F.Id DESC ");
try
{
// Obtem uma conexão com o banco de dados
using (_databaseConnection = new SqlConnection(_connectionString))
{
// Abre a conexão
_databaseConnection.Open();
// Executa o código SQL e armazena o resultado na variavel filmes
filmes = _databaseConnection.Query<Filme, Genero, Locacao, Filme>(sql.ToString(),
(f, g, l) =>
{
f.Genero = g;
f.Locacao = l;
return f;
},
splitOn: "Id,Id,Id").ToList();
}
return filmes;
}
catch (Exception e)
{
throw e;
}
finally
{
// Verifica se a conexão com o banco está aberta
if (_databaseConnection.State != ConnectionState.Closed)
{
// Fecha a conexão com o banco apos a operação
_databaseConnection.Close();
}
// Destroi a instancia de conexão utilizada
_databaseConnection = null;
}
}
// Remove do banco de dados os filmes selecionados
public bool RemoverSelecionados(List<Filme> filmes)
{
try
{
// Cria uma instancia de ApplicationContext
using (var applicationContext = new ApplicationContext())
{
// Remove do banco de dados os filmes que estão na lista
applicationContext.RemoveRange(filmes);
return applicationContext.SaveChanges() > 0;
}
}
catch (Exception e)
{
throw e;
}
}
// Obtem um filme pelo seu Id
public Filme ConsultarPorId(int id)
{
Filme filme = null;
// Define o código SQL a ser executado
StringBuilder sql = new StringBuilder();
sql.Append(" SELECT * FROM Filme ");
sql.Append(" WHERE Id = @Id ");
try
{
// Define os parâmetros usados no código SQL
var parametros = new
{
@Id = id
};
// Obtem uma conexão com o banco de dados
using (_databaseConnection = new SqlConnection(_connectionString))
{
// Abre a conexão
_databaseConnection.Open();
// Executa o código SQL e armazena o resultado na variavel filme
filme = _databaseConnection.Query<Filme>(sql.ToString(), parametros).FirstOrDefault();
}
return filme;
}
catch (Exception e)
{
throw e;
}
finally
{
// Verifica se a conexão com o banco está aberta
if (_databaseConnection.State != ConnectionState.Closed)
{
// Fecha a conexão com o banco apos a operação
_databaseConnection.Close();
}
// Destroi a instancia de conexão utilizada
_databaseConnection = null;
}
}
// Remove um filme pelo seu Id
public bool RemoverPorId(int id)
{
bool sucesso = false;
// Define o código SQL a ser executado
StringBuilder sql = new StringBuilder();
sql.Append(" DELETE FROM Filme ");
sql.Append(" WHERE Id = @Id ");
try
{
// Define os parâmetros usados no código SQL
var parametros = new
{
@Id = id
};
// Obtem uma conexão com o banco de dados
using (_databaseConnection = new SqlConnection(_connectionString))
{
// Abre a conexão
_databaseConnection.Open();
// Executa o código SQL
sucesso = _databaseConnection.Execute(sql.ToString(), parametros) > 0;
}
return sucesso;
}
catch (Exception e)
{
throw e;
}
finally
{
// Verifica se a conexão com o banco está aberta
if (_databaseConnection.State != ConnectionState.Closed)
{
// Fecha a conexão com o banco apos a operação
_databaseConnection.Close();
}
// Destroi a instancia de conexão utilizada
_databaseConnection = null;
}
}
// Lista todos os filmes ativos e não locados
public List<Filme> ListarNaoLocados()
{
List<Filme> filmes = null;
// Define o código SQL a ser executado
StringBuilder sql = new StringBuilder();
sql.Append(" SELECT ");
sql.Append(" F.* ");
sql.Append(" , G.* ");
sql.Append(" FROM Filme F ");
sql.Append(" INNER JOIN Genero G ON F.GeneroId = G.Id ");
sql.Append(" WHERE F.LocacaoID IS NULL ");
sql.Append(" AND F.Ativo = 1 ");
sql.Append(" ORDER BY f.Id DESC ");
try
{
// Obtem uma conexão com o banco de dados
using (_databaseConnection = new SqlConnection(_connectionString))
{
// Abre a conexão
_databaseConnection.Open();
// Executa o código SQL e armazena o resultado na variavel filmes
filmes = _databaseConnection.Query<Filme, Genero, Filme>(
sql.ToString(),
(f, g) =>
{
f.Genero = g;
return f;
},
splitOn: "Id,Id").ToList();
}
return filmes;
}
catch (Exception e)
{
throw e;
}
finally
{
// Verifica se a conexão com o banco está aberta
if (_databaseConnection.State != ConnectionState.Closed)
{
// Fecha a conexão com o banco apos a operação
_databaseConnection.Close();
}
// Destroi a instancia de conexão utilizada
_databaseConnection = null;
}
}
}
}
|
using System;
using System.Linq;
using System.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using System.Web;
using System.Collections.Concurrent;
using Microsoft.DataStudio.OAuthMiddleware.Models;
using System.Dynamic;
using System.Collections.Generic;
namespace Microsoft.DataStudio.OAuthMiddleware.AuthorizationServiceProvider
{
public class JwtTokenFormatter : ISecureDataFormat<AuthenticationTicket>
{
private SimpleAuthorizationServerProvider authorizationProvider;
private ConcurrentDictionary<string, TokenCacheItem> _tokenCache;
public JwtTokenFormatter(OAuthAuthorizationServerOptions oAuthServerOptions)
{
authorizationProvider = oAuthServerOptions.Provider as SimpleAuthorizationServerProvider;
_tokenCache = authorizationProvider.TokenCache;
}
public string Protect(AuthenticationTicket data)
{
if (data == null) throw new ArgumentNullException("data");
TokenCacheItem cachedItem;
List<dynamic> subscriptionlist = new List<dynamic>();
//check if we have the cached token for the user in dictionary
_tokenCache.TryGetValue(data.Identity.Name, out cachedItem);
if (cachedItem != null)
{
var errorMesage = cachedItem.LastError;
if (string.IsNullOrEmpty(errorMesage))
{
if (cachedItem.subscriptions != null)
{
var useremail = data.Identity.Name.Contains('#') == true ? data.Identity.Name.Split('#')[1] : data.Identity.Name;
var result = new CustomBearerToken { email = useremail, sessionId = cachedItem.sessionId, accessTokenRawValue = cachedItem.subscriptions.FirstOrDefault().Access_token, idTokenRawValue = cachedItem.idTokenRawValue, message = cachedItem.LastError };
foreach (var item in cachedItem.subscriptions)
{
dynamic bareminimumSubscription = new ExpandoObject();
bareminimumSubscription.subscriptionid = item.SubscriptionId;
bareminimumSubscription.access_token = item.Access_token;
bareminimumSubscription.displayName = item.DisplayName;
subscriptionlist.Add(bareminimumSubscription);
}
result.subscriptions = subscriptionlist.ToArray();
return JsonConvert.SerializeObject(result);
}
}
else
{
cachedItem.LastError = string.Empty;
return JsonConvert.SerializeObject(new CustomBearerToken { accessTokenRawValue = string.Empty, idTokenRawValue = string.Empty, message = errorMesage });
}
}
return JsonConvert.SerializeObject(new CustomBearerToken { accessTokenRawValue = string.Empty, idTokenRawValue = string.Empty, message = "Error encountered. Please relogin again." });
}
public AuthenticationTicket Unprotect(string protectedText)
{
throw new NotImplementedException();
}
}
} |
namespace PlatformRacing3.Server.API.Game.Commands;
public interface ICommandExecutor
{
uint PermissionRank { get; }
void SendMessage(string message);
bool HasPermission(string permission);
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
namespace Dao.Seguridad
{
public class PeriodoDao : GenericDao<Periodo>, IPeriodoDao
{
/// <summary>
/// Metodo que permite obtener todos los periodos activos de una empresa
/// </summary>
/// <param name="idEmpresa">Código de empresa</param>
/// <returns>Lista de periodos</returns>
public List<Periodo> GetPeriodoActivosxEmpresa(long idEmpresa)
{
List<Periodo> lista = new List<Periodo>();
SQLBDEntities _SQLBDEntities = new SQLBDEntities();
_SQLBDEntities.Configuration.ProxyCreationEnabled = false;
try
{
lista = _SQLBDEntities.Periodo.Include("Meses").Include("Ejercicio")
.Where(x => x.IdEmpresa == idEmpresa && !x.Cerrado && x.Activo)
.ToList();
}
catch (Exception e)
{
log.Error(e);
}
return lista;
}
}
}
|
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;
namespace DBMS
{
public partial class Form1 : Form
{
private readonly DataBaseHandler conn;
private DataTable dt;
private string lastTable = "";
public Form1()
{
InitializeComponent();
conn = DataBaseHandler.Instance;
}
private void populateGrid(DataTable dt)
{
dataGridView1.DataSource = dt;
dataGridView1.Update();
dataGridView1.Refresh();
}
public void Controller(string path, string cmd)
{
if (cmd.Equals("NEW"))
{
conn.DisconnectDataBase();
if (!conn.NewDataBase(path))
{
MessageBox.Show("File", "File Already Exists!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
if (cmd.Equals("OPEN"))
{
conn.DisconnectDataBase();
if (!conn.OpenDataBase(path))
{
MessageBox.Show("File", "File Does NOT Exist!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
if (path.Equals("EXEC"))
{
string[] subs = cmd.Split(' ');
Console.WriteLine(cmd);
if (subs[0].ToUpper().Equals("CREATE"))
{
Console.WriteLine("CREATE");
if (!conn.CreateTableCommand(cmd))
{
MessageBox.Show("Execute Error", $"Something went wrong with command:\n'{cmd}'",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
lastTable = subs[2];
string tmp = $"SELECT * FROM '{lastTable}'";
populateGrid(conn.ReadCommand(tmp));
}
}
if (subs[0].ToUpper().Equals("SELECT"))
{
Console.WriteLine("SELECT");
if ((dt = conn.ReadCommand(cmd)) == null)
{
MessageBox.Show("Execute Error", $"Something went wrong with command:\n'{cmd}'",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
for (int i = 0; i < subs.Length; ++i)
{
if (subs[i].ToUpper().Equals("FROM"))
{
lastTable = subs[i + 1];
break;
}
}
populateGrid(dt);
}
}
if (subs[0].ToUpper().Equals("INSERT") ||
subs[0].ToUpper().Equals("DELETE") ||
subs[0].ToUpper().Equals("DROP"))
{
Console.WriteLine("MODIFY");
if (!conn.ModifyCommand(cmd))
{
MessageBox.Show("Execute Error", $"Something went wrong with command:\n'{cmd}'",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
lastTable = subs[2];
string tmp = $"SELECT * FROM '{lastTable}'";
populateGrid(conn.ReadCommand(tmp));
}
}
}
}
private void newDataBaseToolStripMenuItem_Click(object sender, EventArgs e)
{
if(saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{
string path = saveFileDialog1.InitialDirectory + saveFileDialog1.FileName;
label1.Text = path;
Controller(path, "NEW");
}
}
private void openDataBaseToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
string path = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
label1.Text = path;
Controller(path, "OPEN");
}
}
private void executeButton_Click(object sender, EventArgs e)
{
Controller("EXEC", cmdTextBox.Text);
cmdTextBox.Clear();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
}
private void cmdTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Controller("EXEC", cmdTextBox.Text);
cmdTextBox.Clear();
e.Handled = true;
e.SuppressKeyPress = true;
}
}
}
}
|
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Timers;
namespace SnipForMammal
{
using SimpleJson;
using System.Runtime.InteropServices;
using Timer = System.Timers.Timer;
public class Spotify
{
private readonly string spotifyAPIAuthURL = @"https://accounts.spotify.com/authorize"; // Spotify Auth API
private readonly string spotifyAPICurrentlyPlayingURL = @"https://api.spotify.com/v1/me/player/currently-playing";
private readonly string spotifyAPITokenURL = @"https://accounts.spotify.com/api/token";
private readonly string localCallbackURL = @"http://localhost:8888/"; // Callback address for Auth API. Must be registered on Spotify Dashboard.
private readonly string scopes = "user-read-currently-playing"; // Spotify API scopes.
private readonly string responseType = "code"; // Required by Auth API.
private readonly string spotify64BitKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(ApplicationKeys.Spotify)); // Base64 auth keys "client_id:client_secret for auth"
private string authorizationCode = string.Empty; // Spotify Auth API Code. Provided by Auth API.
private string authorizationToken = string.Empty; // Spotify Auth API Token. Provided by Auth API.
private double authorizationTokenExpiration = 0; // Time until Spotify Auth API Token expires.
private string refreshToken = string.Empty; // Spotify Auth API Refresh Token.
private Timer updateAuthToken;
private Timer updateSpotifyTrackInfo;
private bool spotifyRunning = false;
private Process spotifyProcess;
private IntPtr spotifyHandle = IntPtr.Zero;
private string spotifyWindowTitle;
public Spotify()
{
// Authorize SnipForMammal through Spotify API
AuthorizeSnipForMammal();
// Configure timer to update auth token
ConfigureUpdateAuthTokenTimer();
// Configure timer to update current playing track
ConfigureUpdateCurrentPlayingTrackTimer();
}
private void Log(string text)
{
Global.log?.WriteLine("[Spotify] " + text);
}
#region Timers
private void ConfigureUpdateAuthTokenTimer()
{
this.updateAuthToken = new Timer(Global.updateAuthTokenInterval);
this.updateAuthToken.Elapsed += this.UpdateAuthToken_Elapsed;
this.updateAuthToken.AutoReset = true;
this.updateAuthToken.Enabled = true;
this.UpdateAuthToken_Elapsed(null, null); // Get initial token
Log("Timer updateAuthToken started. Interval " + Global.updateAuthTokenInterval + "ms");
}
private void ConfigureUpdateCurrentPlayingTrackTimer()
{
this.updateSpotifyTrackInfo = new Timer(Global.updateSpotifyTrackInfoInterval);
this.updateSpotifyTrackInfo.Elapsed += this.UpdateSpotifyTrackInformation_Elapsed;
this.updateSpotifyTrackInfo.AutoReset = true;
this.updateSpotifyTrackInfo.Enabled = true;
Log("Timer updateSpotifyTrackInformation started. Interval " + Global.updateSpotifyTrackInfoInterval + "ms");
}
private void UpdateAuthToken_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Tick UpdateAuthToken_Elapsed");
// Check for interval change.
if (updateAuthToken.Interval != Global.updateAuthTokenInterval)
{
updateAuthToken.Interval = Global.updateAuthTokenInterval;
Log("Interval for timer updateAuthToken updated to " + Global.updateAuthTokenInterval + "ms");
}
string downloadedJson = string.Empty;
if (!string.IsNullOrEmpty(this.refreshToken))
{
Console.WriteLine("SpotifyAddressContactType.AuthorizationRefresh");
downloadedJson = this.DownloadJson(spotifyAPITokenURL, SpotifyAddressContactType.AuthorizationRefresh);
}
else
{
Console.WriteLine("SpotifyAddressContactType.Authorization");
downloadedJson = this.DownloadJson(spotifyAPITokenURL, SpotifyAddressContactType.Authorization);
}
Console.WriteLine(downloadedJson);
// Set the token to be blank until filled
this.authorizationToken = string.Empty;
this.authorizationTokenExpiration = 0;
if (!string.IsNullOrEmpty(downloadedJson))
{
dynamic jsonSummary = SimpleJson.DeserializeObject(downloadedJson);
if (jsonSummary != null)
{
this.authorizationToken = jsonSummary.access_token.ToString();
this.authorizationTokenExpiration = Convert.ToDouble((long)jsonSummary.expires_in);
if (jsonSummary.refresh_token != null)
{
this.refreshToken = jsonSummary.refresh_token.ToString();
}
this.updateAuthToken.Interval = this.authorizationTokenExpiration * 1000.0;
// Debug output
Log("authToken: " + this.authorizationToken);
Log("authTokenExpiration: " + this.authorizationTokenExpiration);
Log("refreshToken: " + this.refreshToken);
}
}
else
{
Log("Failed to obtain Json from Spotify Token API.");
DisableAllTimers();
}
if (authorizationTokenExpiration > 0)
{
Log("Auth token updated.");
}
}
private void UpdateSpotifyTrackInformation_Elapsed(object sender, ElapsedEventArgs e)
{
// Check for interval change
if (updateSpotifyTrackInfo.Interval != Global.updateSpotifyTrackInfoInterval)
{
updateSpotifyTrackInfo.Interval = Global.updateSpotifyTrackInfoInterval;
Log("Interval for timer updateSpotifyTrackInfo updated to " + Global.updateSpotifyTrackInfoInterval + "ms");
}
// Ensure Spotify is running otherwise reset.
CheckForSpotifyInstance();
if (this.spotifyRunning)
{
// Get Currently Playing JSON from API.
string downloadedJson = this.DownloadJson(this.spotifyAPICurrentlyPlayingURL, SpotifyAddressContactType.API);
if (!string.IsNullOrEmpty(downloadedJson))
{
// Parse Json
dynamic jsonSummary = SimpleJson.DeserializeObject(downloadedJson);
// Is track currently playing?
if ((bool)jsonSummary.is_playing)
{
// Is this a new track?
SpotifyTrack newTrack = new SpotifyTrack(jsonSummary);
if (newTrack.ToString() != Global.currentTrack?.ToString())
{
// Update last played track
Global.IsTextOverriden = false;
Global.lastTrack = Global.currentTrack;
Global.currentTrack = newTrack;
//ResetUpdateAuthTokenTimer();
Log("Now playing: " + Global.currentTrack?.ToString());
}
else
{
RequestReset(ResetReason.NotNewSong);
}
}
else
{
RequestReset(ResetReason.SpotifyPaused);
}
}
else
{
RequestReset(ResetReason.InvalidJson);
}
}
else
{
RequestReset(ResetReason.SpotifyNotLaunched);
}
}
private void ResetUpdateAuthTokenTimer()
{
Log("Resetting timer updateAuthToken.");
this.updateAuthToken.Enabled = false;
this.updateAuthToken.Interval = Global.updateAuthTokenInterval;
this.updateAuthToken.Enabled = true;
}
private void ResetUpdateSpotifyTrackInformationTimer()
{
Log("Resetting timer updateSpotifyTrackInformation.");
this.updateSpotifyTrackInfo.Enabled = false;
this.updateSpotifyTrackInfo.Interval = Global.updateSpotifyTrackInfoInterval;
this.updateSpotifyTrackInfo.Enabled = true;
}
private void DisableAllTimers()
{
updateAuthToken.Enabled = false;
updateSpotifyTrackInfo.Enabled = false;
Log("Disabling all Snip timers");
}
#endregion Timers
private bool IsSpotifyWindowDefaultText()
{
// Checks if Spotify's Window Title is either the last track played or contains the default text indicating not playing
bool isWindowTitleLastTrackOrDefault = false;
if ((this.spotifyWindowTitle.Length > 0) && (this.spotifyWindowTitle.Contains("Spotify")))
{
isWindowTitleLastTrackOrDefault = true;
}
return isWindowTitleLastTrackOrDefault;
}
private void CheckForSpotifyInstance()
{
// Fetch all Spotify processes
Process[] allRunningProcesses = Process.GetProcessesByName("Spotify");
if (allRunningProcesses.Length > 0)
{
foreach (Process proc in allRunningProcesses)
{
// Check processes for the one with text in the window title. There are multiple Spotify processes but only one will have a non-empty window title.
if (proc.MainWindowTitle.Length > 0)
{
this.spotifyRunning = true;
this.spotifyProcess = proc;
this.spotifyHandle = proc.MainWindowHandle;
StringBuilder sb = new StringBuilder(256);
GetWindowText(this.spotifyHandle, sb, sb.Capacity);
this.spotifyWindowTitle = sb.ToString();
}
}
}
else
{
this.spotifyRunning = false;
this.spotifyProcess = null;
this.spotifyHandle = IntPtr.Zero;
this.spotifyWindowTitle = string.Empty;
}
; }
private Process OpenURL(string url)
{
string browser = Global.browser.ToLower();
Process process;
switch (browser)
{
case "chrome":
try
{
process = Process.Start("chrome", url + " --new-window");
}
catch
{
goto default;
}
break;
case "firefox":
try
{
process = Process.Start("firefox", "-new-window " + url);
}
catch
{
goto default;
}
break;
case "opera":
try
{
process = Process.Start("opera", "--new-window " + url);
}
catch
{
goto default;
}
break;
case "edge":
try
{
process = Process.Start("msedge", "--new-window " + url);
}
catch
{
goto default;
}
break;
default:
process = Process.Start(url);
break;
}
return process;
}
private void AuthorizeSnipForMammal()
{
try
{
// Start up Process to begin authorization with Spotify API
string authURL = string.Format(CultureInfo.InvariantCulture, "{0}?client_id={1}&response_type={2}&redirect_uri={3}&scope={4}", this.spotifyAPIAuthURL, ApplicationKeys.client, this.responseType, this.localCallbackURL, this.scopes);
Process authorizationProcess = OpenURL(authURL);
using (HttpListener callbackListener = new HttpListener())
{
HttpListenerTimeoutManager timeoutManager = callbackListener.TimeoutManager;
timeoutManager.IdleConnection = new TimeSpan(0, 0, 5); // hr, min, s
timeoutManager.HeaderWait = new TimeSpan(0, 0, 5);
callbackListener.Prefixes.Add(this.localCallbackURL);
callbackListener.Start();
HttpListenerContext context = callbackListener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
NameValueCollection nameValueCollection = request.QueryString;
string spotifyAPIAccessGranted = "Access granted. You may close this window now.";
string spotifyAPIAccessDenied = "Access denied. In order to use this application you must grant it access.";
string callbackHtmlStart = @"<!doctype html><html lang=en><head><meta charset=utf-8><style>div { font-size:xx-large; }</style><title>SnipForMammal Auth</title></head><body><div>";
string callbackHtmlEnd = @"</div></body></html>";
string callbackCloseWindowScript = @"<script>window.close();</script>";
string outputString = string.Empty;
foreach (string keyValue in nameValueCollection.AllKeys)
{
switch (keyValue.ToLower())
{
case "code":
if (Global.autoCloseAuthWindow)
{
outputString = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", callbackHtmlStart, callbackCloseWindowScript, spotifyAPIAccessGranted, callbackHtmlEnd);
}
else
{
outputString = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", callbackHtmlStart, spotifyAPIAccessGranted, callbackHtmlEnd);
}
this.authorizationCode = nameValueCollection[keyValue];
Log("Successfully authorized through Spotify Auth API.");
break;
case "error":
outputString = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", callbackHtmlStart, spotifyAPIAccessDenied, callbackHtmlEnd);
Log("Failed authorizing through Spotify Auth API.");
break;
default:
break;
}
}
byte[] buffer = Encoding.UTF8.GetBytes(outputString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
callbackListener.Stop();
}
}
catch (Exception e)
{
Log(e.ToString());
}
}
private string DownloadJson(string jsonAddress, SpotifyAddressContactType spotifyAddressContactType)
{
using (WebClientWithShortTimeout jsonWebClient = new WebClientWithShortTimeout())
{
try
{
// Auth uses POST instead of GET
bool usePostMethodInsteadOfGet = false;
string postParameters = string.Empty;
// Modify HTTP headers based on what's being contacted
switch (spotifyAddressContactType)
{
case SpotifyAddressContactType.Authorization:
Log("Downloading authorization json.");
usePostMethodInsteadOfGet = true;
postParameters = string.Format(CultureInfo.InvariantCulture, "grant_type=authorization_code&code={0}&redirect_uri={1}", this.authorizationCode, this.localCallbackURL);
jsonWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
jsonWebClient.Headers.Add("Authorization", string.Format(CultureInfo.InvariantCulture, "Basic {0}", this.spotify64BitKey));
break;
case SpotifyAddressContactType.AuthorizationRefresh:
Log("Downloading refresh authorization json.");
usePostMethodInsteadOfGet = true;
postParameters = string.Format(CultureInfo.InvariantCulture, "grant_type=refresh_token&refresh_token={0}", this.refreshToken);
jsonWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
jsonWebClient.Headers.Add("Authorization", string.Format(CultureInfo.InvariantCulture, "Basic {0}", this.spotify64BitKey));
break;
case SpotifyAddressContactType.API:
jsonWebClient.Headers.Add("Authorization", string.Format(CultureInfo.InvariantCulture, "Bearer {0}", this.authorizationToken));
break;
default:
break;
}
jsonWebClient.Headers.Add("User-Agent", "SnipForMammal/v1");
jsonWebClient.Encoding = Encoding.UTF8;
string downloadedJson = string.Empty;
if (usePostMethodInsteadOfGet)
{
downloadedJson = jsonWebClient.UploadString(jsonAddress, "POST", postParameters);
}
else
{
downloadedJson = jsonWebClient.DownloadString(jsonAddress);
}
if (downloadedJson.Length > 0 & downloadedJson.Length < 1000)
{
Log(downloadedJson);
}
return downloadedJson;
}
catch (WebException webException)
{
Log("WebException thrown in Spotify.DownloadJson()");
Log(" Exception Message: " + webException.Message);
// Catch "(503) Server Unavailable"
WebResponse webResponse = webException.Response;
WebHeaderCollection webHeaderCollection = webResponse.Headers;
for (int i = 0; i < webHeaderCollection.Count; i++)
{
if (webHeaderCollection.GetKey(i).ToUpperInvariant() == "RETRY-AFTER")
{
// Set the timer to the retry seconds. Plus 1 for safety.
this.updateSpotifyTrackInfo.Enabled = false;
this.updateSpotifyTrackInfo.Interval = (Double.Parse(webHeaderCollection.Get(i) + 2, CultureInfo.InvariantCulture)) * 1000;
this.updateSpotifyTrackInfo.Enabled = true;
}
}
return string.Empty;
}
catch (Exception e)
{
Log("Generic exception thrown in DownloadJson()");
Log(" Exception Message: " + e.Message);
return string.Empty;
}
}
}
private void RequestReset(ResetReason resetReason)
{
switch (resetReason)
{
case ResetReason.SpotifyNotLaunched:
Log("Reset requested. Reason: Spotify is not launched.");
this.spotifyRunning = false;
this.spotifyHandle = IntPtr.Zero;
break;
case ResetReason.SpotifyPaused:
Log("Reset requested. Reason: Spotify is paused.");
this.spotifyRunning = false;
this.spotifyHandle = IntPtr.Zero;
if (!Global.IsTextOverriden)
{
Global.currentTrack = null;
}
break;
case ResetReason.NotNewSong:
Log("Reset requested. Reason: Current song playing is not new.");
this.spotifyRunning = false;
this.spotifyHandle = IntPtr.Zero;
break;
case ResetReason.InvalidJson:
Log("Reset requested. Reason: Invalid Json.");
this.spotifyRunning = false;
this.spotifyHandle = IntPtr.Zero;
break;
case ResetReason.ForceUpdateRequested:
Log("Reset requested. Reason: Force update requested by user.");
this.spotifyRunning = false;
this.spotifyHandle = IntPtr.Zero;
ResetUpdateSpotifyTrackInformationTimer();
break;
default:
break;
}
}
public void ForceUpdate()
{
RequestReset(ResetReason.ForceUpdateRequested);
}
public void CustomTrack(string text)
{
Log("Setting custom track: " + text);
Global.currentTrack = new SpotifyTrack(text);
}
#region Extern
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
internal static extern int GetWindowText([In] IntPtr windowHandle, [Out] StringBuilder windowText, [In] int maxCount);
#endregion Extern
#region Enums
private enum SpotifyAddressContactType
{
Authorization,
AuthorizationRefresh,
API,
Default
}
private enum ResetReason
{
SpotifyNotLaunched,
SpotifyPaused,
NotNewSong,
ForceUpdateRequested,
InvalidJson
}
#endregion Enums
}
}
|
namespace Labs.WPF.TvShowOrganizer.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class t : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Episodes",
c => new
{
ID = c.Guid(nullable: false),
TvShowId = c.Guid(nullable: false),
EpisodeId = c.Int(nullable: false),
Name = c.String(nullable: false, maxLength: 50),
Number = c.Int(nullable: false),
Season = c.Int(nullable: false),
Overview = c.String(maxLength: 500),
LastUpdated = c.Double(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.TvShows", t => t.TvShowId, cascadeDelete: true)
.Index(t => t.TvShowId);
AddColumn("dbo.TvShows", "LastUpdated", c => c.Double(nullable: false));
}
public override void Down()
{
DropForeignKey("dbo.Episodes", "TvShowId", "dbo.TvShows");
DropIndex("dbo.Episodes", new[] { "TvShowId" });
DropColumn("dbo.TvShows", "LastUpdated");
DropTable("dbo.Episodes");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using SQLite.Net;
namespace Trabalho2.Models
{
class CompraRepository : IDisposable
{
private SQLiteConnection _conexao;
public CompraRepository()
{
var config = DependencyService.Get<IConfig>();
_conexao = new SQLiteConnection(config.Plataforma, System.IO.Path.Combine(config.DiretorioDB, "trabalho2.db3"));
_conexao.CreateTable<Compra>();
}
public void Insert(Compra compra)
{
_conexao.Insert(compra);
}
public void Update(Compra compra)
{
_conexao.Update(compra);
}
public void Delete(Compra compra)
{
_conexao.Delete(compra);
}
public List<Compra> Listar()
{
return _conexao.Table<Compra>().OrderBy(p => p.Id).ToList();
}
public Compra ObterPorId(int id)
{
return _conexao.Table<Compra>().FirstOrDefault(c => c.Id == id);
}
public void Dispose()
{
_conexao.Dispose();
}
}
}
|
namespace SVN.Pdf.Enums
{
public enum VAlign
{
Top, Middle, Bottom
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GraphQLSampleAPI.Contexts;
using GraphQLSampleAPI.Models;
using HotChocolate.Fetching;
using Microsoft.EntityFrameworkCore;
namespace GraphQLSampleAPI.DataLoader
{
public class GadgetsByBrandDataLoader : BatchDataLoader<string, IEnumerable<Gadget>>
{
private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;
public GadgetsByBrandDataLoader(IDbContextFactory<ApplicationDbContext> dbContextFactory, BatchScheduler batchScheduler) : base(batchScheduler)
{
_dbContextFactory = dbContextFactory;
}
protected override async Task<IReadOnlyDictionary<string, IEnumerable<Gadget>>> LoadBatchAsync(IReadOnlyList<string> keys, CancellationToken cancellationToken)
{
await using (var dbContext = _dbContextFactory.CreateDbContext())
{
var gadgets = await dbContext.Gadgets.Where(g => keys.Select(_ => _.ToLower()).ToList().Contains(g.brandName.ToLower())).ToListAsync();
return gadgets.GroupBy(_ => _.brandName.ToLower())
.Select(_ => new
{
key = _.Key,
Gadgets = _.AsEnumerable()
}).ToDictionary(k => k.key, v => v.Gadgets);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
public partial class add_advertise : System.Web.UI.Page
{
SqlConnection con = null;
public string uname = "";
public int uid;
protected void Page_Load(object sender, EventArgs e)
{
uid = Convert.ToInt32(Session["uid"]);
uname = Session["uname"].ToString();
// Response.Write(uid);
// Response.Write(uname);
}
protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\WebSite_ocs\ocs.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("@title", title.Text);
cmd.Parameters.AddWithValue("@cat", cat.SelectedItem.Value);
cmd.Parameters.AddWithValue("@desc", desc.Text);
cmd.Parameters.AddWithValue("@status", status.SelectedItem.Value);
cmd.Parameters.AddWithValue("@city", city.Text);
cmd.Parameters.AddWithValue("@no", no.Text);
cmd.Parameters.AddWithValue("@eid", eid.Text);
cmd.Parameters.AddWithValue("@add", add.Text);
cmd.Parameters.AddWithValue("@date", date.Text);
cmd.Parameters.AddWithValue("@pin", pin.Text);
cmd.Parameters.AddWithValue("@img",f1.FileName);
cmd.Parameters.AddWithValue("@uid",uid);
if (f1.HasFile)
{
string filename = f1.PostedFile.FileName.ToString();
f1.SaveAs(Server.MapPath("img\\") + Path.GetFileName(filename));
cmd.Parameters.AddWithValue("@im", Server.MapPath("img\\") + Path.GetFileName(filename));
}
cmd.CommandText = "insert into ad_master values(@cat,@title,@desc,@date,@status,@city,@add,@pin,@no,@eid,@img,@uid)";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
//Response.Write("Advertise Add successfully!");
Label1.Text = "Advertise Add successfully";
}
protected void Button2_Click(object sender, EventArgs e)
{
title.Text = "";
desc.Text = "";
date.Text = "";
city.Text = "";
add.Text = "";
pin.Text = "";
no.Text = "";
eid.Text = "";
cat.SelectedIndex = 0;
status.SelectedIndex = 0;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.